diff --git a/apps/cartesify/backend/js-template/src/example.js b/apps/cartesify/backend/js-template/src/example.js deleted file mode 100644 index 2cf396b..0000000 --- a/apps/cartesify/backend/js-template/src/example.js +++ /dev/null @@ -1,291 +0,0 @@ - -console.log('starting app.js...') -const { CartesifyBackend } = require("@calindra/cartesify-backend") -const { createWallet } = require("@deroll/wallet") -let dapp, wallet - -CartesifyBackend.createDapp().then(initDapp => { - initDapp.start(() => { - console.log('Dapp started'); - }).catch((e) => { - console.error(e); - process.exit(1); - }); - dapp = initDapp - - wallet = createWallet() - dapp.addAdvanceHandler(() => { - console.log('before wallet handler') - return "reject" - }) - dapp.addAdvanceHandler(wallet.handler); - dapp.addAdvanceHandler(() => { - console.log('final handler') - return "reject" - }) -}) - -const express = require("express") - -const app = express(); -const port = 8383; -app.use(express.json()); - -let totalAmount = 0 - -let games = [] - - -app.get("/health", (req, res) => { - res.send({ some: "response" }); -}); - - -app.get("/wallet/:address", async (req, res) => { - console.log(`Checking balance ${req.params.address}`) - const userWallet = await wallet.getWalletOrNew(req.params.address) - const json = JSON.stringify(userWallet, (_key, value) => { - if (typeof value === 'bigint') { - return value.toString() - } else if (typeof value === 'object' && value instanceof Map) { - return Object.fromEntries(value) - } else if (typeof value === 'object' && value instanceof Set) { - return [...value] - } else { - return value - } - }) - res.setHeader('Content-Type', 'application/json; charset=utf-8') - res.send(json) -}) - -app.post("/wallet/ether/transfer", async (req, res) => { - try { - await wallet.transferEther( - req.get('x-msg_sender'), - req.body.to, - BigInt(req.body.amount), - ) - res.send({ ok: 1 }) - } catch (e) { - // Here, we need to detect the type of error to send the appropriate status. - res.status(400).send({ message: e.message }) - } -}) - -app.post("/wallet/ether/withdraw", async (req, res) => { - try { - const voucher = await wallet.withdrawEther( - req.get('x-msg_sender'), - BigInt(req.body.amount) - ) - const voucherResult = await dapp.createVoucher(voucher) - res.send({ - ok: 1, voucherResult, inputIndex: req.get('x-input_index') - }) - } catch (e) { - // Here, we need to detect the type of error to send the appropriate status. - res.status(400).send({ message: e.message }) - } -}) - -app.post("/wallet/erc-20/withdraw", async (req, res) => { - try { - const voucher = await wallet.withdrawERC20( - req.body.token, - req.get('x-msg_sender'), - BigInt(req.body.amount) - ) - const voucherResult = await dapp.createVoucher(voucher) - res.send({ - ok: 1, voucherResult, inputIndex: req.get('x-input_index') - }) - } catch (e) { - // Here, we need to detect the type of error to send the appropriate status. - res.status(400).send({ message: e.message }) - } -}) - -app.post("/wallet/erc-20/transfer", async (req, res) => { - try { - await wallet.transferERC20( - req.body.token, - req.get('x-msg_sender'), - req.body.to, - BigInt(req.body.amount), - ) - res.send({ ok: 1 }) - } catch (e) { - // Here, we need to detect the type of error to send the appropriate status. - res.status(400).send({ message: e.message }) - } -}) - -app.post("/wallet/erc-721/transfer", async (req, res) => { - try { - await wallet.transferERC721( - req.body.token, - req.get('x-msg_sender'), - req.body.to, - BigInt(req.body.tokenId), - ) - res.send({ ok: 1 }) - } catch (e) { - // Here, we need to detect the type of error to send the appropriate status. - res.status(400).send({ message: e.message }) - } -}) - -app.post("/wallet/erc-1155/transfer", async (req, res) => { - try { - await wallet.transferERC1155( - req.body.token, - req.get('x-msg_sender'), - req.body.to, - - // deepcode ignore HTTPSourceWithUncheckedType: doing the type validation - req.body.tokenIds.map(id => { - if (typeof id !== 'number') { - throw new Error(`BadRequest id ${value} is not a number`) - } - return BigInt(id) - }), - - // deepcode ignore HTTPSourceWithUncheckedType: doing the type validation - req.body.values.map(value => { - if (typeof value !== 'number') { - throw new Error(`BadRequest value ${value} is not a number`) - } - return BigInt(value) - }), - ) - res.send({ ok: 1 }) - } catch (e) { - // Here, we need to detect the type of error to send the appropriate status. - res.status(400).send({ message: e.message }) - } -}) - -app.post("/wallet/erc-721/withdraw", async (req, res) => { - try { - const voucher = await wallet.withdrawERC721( - req.body.token, - req.get('x-msg_sender'), - BigInt(req.body.tokenId) - ) - const voucherResult = await dapp.createVoucher(voucher) - res.send({ - ok: 1, voucherResult, inputIndex: req.get('x-input_index') - }) - } catch (e) { - // Here, we need to detect the type of error to send the appropriate status. - res.status(400).send({ message: e.message }) - } -}) - -app.post("/wallet/erc-1155/withdraw", async (req, res) => { - try { - const voucher = await wallet.withdrawERC1155( - req.body.token, - req.get('x-msg_sender'), - - // deepcode ignore HTTPSourceWithUncheckedType: doing the type validation - req.body.tokenIds.map(id => { - if (typeof id !== 'number') { - throw new Error('BadRequest') - } - return BigInt(id) - }), - - // deepcode ignore HTTPSourceWithUncheckedType: doing the type validation - req.body.values.map(value => { - if (typeof value !== 'number') { - throw new Error('BadRequest') - } - return BigInt(value) - }), - ) - - const voucherResult = await dapp.createVoucher(voucher) - res.send({ - ok: 1, voucherResult, inputIndex: req.get('x-input_index') - }) - } catch (e) { - // Here, we need to detect the type of error to send the appropriate status. - res.status(400).send({ message: e.message }) - } -}) - -app.get("/token/:tokenId/owners", (req, res) => { - res.send({ owners }) -}) - -app.post("/new-game", async (req, res) => { - let player1 = req.header("x-msg_sender") - let commit1 = req.body.commit // = hash(move + nonce) - games.push({ - player1, - commit1 - }) - res.send({ created: games.length }) -}) - -app.post('/deposit', (req, res) => { - axios.post('http://deroll/voucher') -}) - -app.get("/", (req, res) => { - res.send({ some: "response" }); -}); - -app.get('/games', (req, res) => { - console.log('hi') - res.send({ ok: 1 }) -}) - -app.put('/update', (req, res) => { - res.send({ updateBody: req.body }) -}) - -app.patch('/patch', (req, res) => { - res.send({ patchBody: req.body }) -}) - -app.delete('/delete', (req, res) => { - res.send({ query: req.query }) -}) - -app.post('/player', (req, res) => { - const name = req.body.name - const id = req.user.id - res.send({ msg: "created", player: { id, name } }) -}) - -app.post('/games', (req, res) => { - req.body.startBid - res.send({ msg: "game created" }) -}) - -app.post('/hit', (req, res) => { - // req.user.id === 'msg_sender' - if (!Number.isNaN(+req.body.amount)) { - totalAmount += +req.body.amount - } - res.send({ amount: totalAmount, myPost: req.body }); -}); - -app.post('/echo', (req, res) => { - res.send({ myPost: req.body }); -}); - -app.post('/echo/headers', (req, res) => { - res.send({ headers: req.headers }); -}); - -app.get('/echo/headers', (req, res) => { - res.send({ headers: req.headers }); -}) - -app.listen(port, () => { - console.log(`[server]: Server is running at http://localhost:${port}`); -}); \ No newline at end of file diff --git a/apps/cartesify/backend/js-template/src/examples/greeting.js b/apps/cartesify/backend/js-template/src/examples/greeting.js index 9fcf976..fc9ff23 100644 --- a/apps/cartesify/backend/js-template/src/examples/greeting.js +++ b/apps/cartesify/backend/js-template/src/examples/greeting.js @@ -1,183 +1,73 @@ -const express = require('express'); -const { appConfig } = require("./init-config"); +const { Request, Response } = require('express'); +const { appConfig } = require('./init-config'); console.log('starting app.js...'); const { app } = appConfig(); -const greetings = []; +let greetings = []; let nextId = 1; -// Create a new greeting app.post('/greetings', (req, res) => { - const sender = req.header("x-msg_sender"); - const { message } = req.body; + const { message, sender } = req.body; const newGreeting = { id: nextId++, message, sender }; greetings.push(newGreeting); - res.status(201).send(newGreeting); -}); - -// Get all greetings from a specific sender -app.get('/greetings', (req, res) => { - const sender = req.header("x-msg_sender"); - if (!sender) { - return res.status(400).send({ message: 'Sender not provided' }); + if (message) { + res.status(200).json(newGreeting); + } else { + res.status(400).json({ error: 'Please provide a greeting' }); } - const senderGreetings = greetings.filter(g => g.sender === sender); - res.send(senderGreetings); }); -// Get a single greeting by ID app.get('/greetings/:id', (req, res) => { - const id = parseInt(req.params.id, 10); - const sender = req.header("x-msg_sender"); - const greeting = greetings.find(g => g.id === id); - - if (!sender) { - return res.status(400).send({ message: 'Sender not provided' }); + try { + const id = parseInt(req.params.id, 10); + const greet = greetings.find(greet => greet.id === id); + if (greet) { + res.status(200).json({ message: greet }); + } else { + res.status(404).json({ error: 'Greeting not found' }); + } + } catch (e) { + res.status(400).json({ error: 'No greeting provided' }); } +}); - if (greeting) { - if (greeting.sender !== sender) { - return res.status(403).send({ message: 'You can only view your own greetings' }); +app.get('/greetings', (req, res) => { + try { + if (greetings) { + res.status(200).json({ greetings }); } - res.send(greeting); - } else { - res.status(404).send({ message: 'Greeting not found' }); + } catch (e) { + res.status(400).json({ error: 'No greeting provided' }); } }); -// Update a greeting by ID app.put('/greetings/:id', (req, res) => { const id = parseInt(req.params.id, 10); - const { message } = req.body; - const sender = req.header("x-msg_sender"); - const greeting = greetings.find(g => g.id === id); + const index = greetings.findIndex(greet => greet.id === id); - if (!sender) { - return res.status(400).send({ message: 'Sender not provided' }); + if (index === -1) { + return res.status(404).json({ error: 'Item not found' }); } - if (greeting) { - if (greeting.sender !== sender) { - return res.status(403).send({ message: 'You can only update your own greetings' }); - } - greeting.message = message; - res.send(greeting); - } else { - res.status(404).send({ message: 'Greeting not found' }); - } + const updatedGreeting = { id: id, message: req.body.message, sender: greetings[index].sender }; + greetings[index] = updatedGreeting; + + res.json(updatedGreeting); }); -// Delete a greeting by ID app.delete('/greetings/:id', (req, res) => { const id = parseInt(req.params.id, 10); - const sender = req.header("x-msg_sender"); - const index = greetings.findIndex(g => g.id === id); - - if (!sender) { - return res.status(400).send({ message: 'Sender not provided' }); + const index = greetings.findIndex(greet => greet.id === id); + if (index === -1) { + return res.status(404).json({ error: 'Item not found' }); } - - if (index !== -1) { - if (greetings[index].sender !== sender) { - return res.status(403).send({ message: 'You can only delete your own greetings' }); - } - greetings.splice(index, 1); - res.status(204).send(); - } else { - res.status(404).send({ message: 'Greeting not found' }); - } -}); - -// Delete all greetings from a specific sender -app.delete('/greetings/sender', (req, res) => { - const sender = req.header("x-msg_sender"); - - if (!sender) { - return res.status(400).send({ message: 'Sender not provided' }); - } - - const initialLength = greetings.length; - for (let i = greetings.length - 1; i >= 0; i--) { - if (greetings[i].sender === sender) { - greetings.splice(i, 1); - } - } - - const finalLength = greetings.length; - const deletedCount = initialLength - finalLength; - - res.status(200).send({ message: `${deletedCount} greetings deleted` }); -}); - -// Get all greetings (no sender check) -app.get('/greetings', (req, res) => { - res.send(greetings); + greetings = greetings.filter(greet => greet.id !== id); + res.json({ message: 'Item deleted successfully' }); }); -// Delete all greetings (no sender check) -app.delete('/greetings/all', (req, res) => { - const deletedCount = greetings.length; - greetings.length = 0; - res.status(200).send({ message: `${deletedCount} greetings deleted` }); +app.delete('/greetings', (req, res) => { + const deletedCount = greetings.length; + greetings.length = 0; + res.status(200).send({ message: `${deletedCount} greetings deleted` }); }); - - -// POST request to the /greeting endpoint -// app.post('/greeting', (req, res) => { -// let greet = req.body; -// greetings.push(greet) -// if (greet) { -// res.status(200).json({ message: greet }); -// } else { -// res.status(400).json({ error: 'Please provide a greeting' }); -// } -// }); - -// // GET request to the /greeting endpoint -// app.get('/greetings/:id', (req, res) => { -// try{ -// const id = parseInt(req.params.id); -// const greet = greetings.find(greet => greet.id === id); -// if(greet){ -// res.status(200).json({ message: greet }); -// } -// }catch(e){ -// res.status(400).json({ error: 'No greeting provided' }); -// } -// }); - -// app.get('/greetings', (req, res) => { -// try{ -// if(greet){ -// res.status(200).json({ greetings }); -// } -// }catch(e){ -// res.status(400).json({ error: 'No greeting provided' }); -// } -// }); - -// app.put('/greetings/:id', (req, res) => { -// const id = parseInt(req.params.id); -// const index = greetings.findIndex(greet => greet.id === id); - -// if (index === -1) { -// return res.status(404).json({ error: 'Item not found' }); -// } - -// const updatedGreeting = { id: id, message: req.body.message }; // Assuming request body contains the updated item data -// greetings[index] = updatedGreeting; - -// res.json(updatedGreeting); -// }); - - -// app.delete('/greetings/:id', (req, res) => { -// const id = parseInt(req.params.id); -// const index = greetings.findIndex(greet => greet.id === id); -// if (index === -1) { -// return res.status(404).json({ error: 'Item not found' }); -// } -// greetings = greetings.filter(greetings => greetings.id !== id); -// res.json({ message: 'Item deleted successfully' }); -// }); \ No newline at end of file diff --git a/apps/cartesify/backend/js-template/src/examples/init-config.js b/apps/cartesify/backend/js-template/src/examples/init-config.js index ef0889a..eaa9be0 100644 --- a/apps/cartesify/backend/js-template/src/examples/init-config.js +++ b/apps/cartesify/backend/js-template/src/examples/init-config.js @@ -5,8 +5,8 @@ const { createWallet } = require("@deroll/wallet"); let dapp; let wallet; -const appConfig = () => { - CartesifyBackend.createDapp().then(initDapp => { +const appConfig = () => { + CartesifyBackend.createDapp().then(async initDapp => { console.log('Dapp started'); initDapp.start().catch((e) => { console.error(e); @@ -14,8 +14,7 @@ const appConfig = () => { }); dapp = initDapp; - wallet = createWallet(); - + wallet = await createWallet(); dapp.addAdvanceHandler(() => { console.log('before wallet handler'); return "reject"; diff --git a/apps/cartesify/backend/js-template/src/examples/wallet-examples.js b/apps/cartesify/backend/js-template/src/examples/wallet-examples.js index 2127a91..81d27b2 100644 --- a/apps/cartesify/backend/js-template/src/examples/wallet-examples.js +++ b/apps/cartesify/backend/js-template/src/examples/wallet-examples.js @@ -9,7 +9,7 @@ const { app, wallet, dapp } = appConfig(); app.get("/wallet/:address", async (req, res) => { console.log(`Checking balance ${req.params.address}`); - const userWallet = await wallet.getWalletOrNew(req.params.address); + const userWallet = await wallet.etherBalanceOf(req.params.address); const json = JSON.stringify(userWallet, (_key, value) => { if (typeof value === 'bigint') { return value.toString(); diff --git a/apps/cartesify/backend/ts-template/src/examples/greeting.ts b/apps/cartesify/backend/ts-template/src/examples/greeting.ts index c2d1180..87bed8a 100644 --- a/apps/cartesify/backend/ts-template/src/examples/greeting.ts +++ b/apps/cartesify/backend/ts-template/src/examples/greeting.ts @@ -7,125 +7,77 @@ const { app } = appConfig() interface Greeting { id: number; message: string; - sender: string | undefined; + sender: string } -const greetings: Greeting[] = []; +let greetings: Greeting[] = []; let nextId = 1; -// Create a new greeting app.post('/greetings', (req: Request, res: Response) => { - const sender = req.header("x-msg_sender"); - const { message } = req.body; + // const sender = req.header("x-msg_sender"); + const { message, sender } = req.body; const newGreeting: Greeting = { id: nextId++, message, sender }; greetings.push(newGreeting); - res.status(201).send(newGreeting); -}); - -// Get all greetings from a specific sender -app.get('/greetings', (req: Request, res: Response) => { - const sender = req.header("x-msg_sender"); - if (!sender) { - return res.status(400).send({ message: 'Sender not provided' }); + if (message) { + res.status(200).json(newGreeting); + } else { + res.status(400).json({ error: 'Please provide a greeting' }); } - const senderGreetings = greetings.filter(g => g.sender === sender); - res.send(senderGreetings); }); -// Get a single greeting by ID +// GET request to the /greeting/:id endpoint app.get('/greetings/:id', (req: Request, res: Response) => { - const id = parseInt(req.params.id!, 10); - const sender = req.header("x-msg_sender"); - const greeting = greetings.find(g => g.id === id); - - if (!sender) { - return res.status(400).send({ message: 'Sender not provided' }); + try { + const id = parseInt(req.params.id!, 10); + const greet = greetings.find(greet => greet.id === id); + if (greet) { + res.status(200).json({ message: greet }); + } else { + res.status(404).json({ error: 'Greeting not found' }); + } + } catch (e) { + res.status(400).json({ error: 'No greeting provided' }); } +}); - if (greeting) { - if (greeting.sender !== sender) { - return res.status(403).send({ message: 'You can only view your own greetings' }); +// GET request to the /greetings endpoint +app.get('/greetings', (req: Request, res: Response) => { + try { + if (greetings) { + res.status(200).json({ greetings }); } - res.send(greeting); - } else { - res.status(404).send({ message: 'Greeting not found' }); + } catch (e) { + res.status(400).json({ error: 'No greeting provided' }); } }); -// Update a greeting by ID app.put('/greetings/:id', (req: Request, res: Response) => { const id = parseInt(req.params.id!, 10); - const { message } = req.body; - const sender = req.header("x-msg_sender"); - const greeting = greetings.find(g => g.id === id); + const index = greetings.findIndex(greet => greet.id === id); - if (!sender) { - return res.status(400).send({ message: 'Sender not provided' }); + if (index === -1) { + return res.status(404).json({ error: 'Item not found' }); } - if (greeting) { - if (greeting.sender !== sender) { - return res.status(403).send({ message: 'You can only update your own greetings' }); - } - greeting.message = message; - res.send(greeting); - } else { - res.status(404).send({ message: 'Greeting not found' }); - } + const updatedGreeting = { id: id, message: req.body.message } as Greeting; // Assuming request body contains the updated item data + greetings[index] = updatedGreeting; + + res.json(updatedGreeting); }); -// Delete a greeting by ID app.delete('/greetings/:id', (req: Request, res: Response) => { const id = parseInt(req.params.id!, 10); - const sender = req.header("x-msg_sender"); - const index = greetings.findIndex(g => g.id === id); - - if (!sender) { - return res.status(400).send({ message: 'Sender not provided' }); + const index = greetings.findIndex(greet => greet.id === id); + if (index === -1) { + return res.status(404).json({ error: 'Item not found' }); } - - if (index !== -1) { - if (greetings[index]!.sender !== sender) { - return res.status(403).send({ message: 'You can only delete your own greetings' }); - } - greetings.splice(index, 1); - res.status(204).send(); - } else { - res.status(404).send({ message: 'Greeting not found' }); - } -}); - -// Delete all greetings from a specific sender -app.delete('/greetings/sender', (req: Request, res: Response) => { - const sender = req.header("x-msg_sender"); - - if (!sender) { - return res.status(400).send({ message: 'Sender not provided' }); - } - - const initialLength = greetings.length; - for (let i = greetings.length - 1; i >= 0; i--) { - if (greetings[i]!.sender === sender) { - greetings.splice(i, 1); - } - } - - const finalLength = greetings.length; - const deletedCount = initialLength - finalLength; - - res.status(200).send({ message: `${deletedCount} greetings deleted` }); -}); - -// without the sender check -// Get all greetings -app.get('/greetings', (req: Request, res: Response) => { - res.send(greetings); + greetings = greetings.filter(greet => greet.id !== id); + res.json({ message: 'Item deleted successfully' }); }); -app.delete('/greetings/all', (req: Request, res: Response) => { +app.delete('/greetings', (req: Request, res: Response) => { const deletedCount = greetings.length; greetings.length = 0; res.status(200).send({ message: `${deletedCount} greetings deleted` }); -}); - +}); \ No newline at end of file diff --git a/apps/cartesify/backend/ts-template/src/examples/init-config.ts b/apps/cartesify/backend/ts-template/src/examples/init-config.ts index e3c3ad2..02899ae 100644 --- a/apps/cartesify/backend/ts-template/src/examples/init-config.ts +++ b/apps/cartesify/backend/ts-template/src/examples/init-config.ts @@ -1,9 +1,9 @@ import express from 'express'; import { CartesifyBackend } from "@calindra/cartesify-backend"; -import { createWallet } from "@deroll/wallet"; +import { WalletApp, createWallet } from "@deroll/wallet"; let dapp: any; -let wallet: any; +let wallet: WalletApp; export const appConfig = () => { CartesifyBackend.createDapp().then(initDapp => { @@ -15,7 +15,6 @@ export const appConfig = () => { dapp = initDapp; wallet = createWallet(); - dapp.addAdvanceHandler((): string => { console.log('before wallet handler'); return "reject"; diff --git a/apps/cartesify/backend/ts-template/src/examples/wallet-examples.ts b/apps/cartesify/backend/ts-template/src/examples/wallet-examples.ts index cff5192..229c290 100644 --- a/apps/cartesify/backend/ts-template/src/examples/wallet-examples.ts +++ b/apps/cartesify/backend/ts-template/src/examples/wallet-examples.ts @@ -1,47 +1,13 @@ -import express, { Request, Response } from 'express'; -import { CartesifyBackend } from "@calindra/cartesify-backend"; -import { createWallet } from "@deroll/wallet"; +import { Request, Response } from 'express'; import axios from "axios" import { appConfig } from "./init-config" console.log('starting app.js...'); const { app, wallet, dapp } = appConfig() -// let dapp: any; -// let wallet: any; - -// CartesifyBackend.createDapp().then(initDapp => { -// console.log('Dapp started'); -// initDapp.start().catch((e: Error) => { -// console.error(e); -// process.exit(1); -// }); - -// dapp = initDapp; -// wallet = createWallet(); - -// dapp.addAdvanceHandler((): string => { -// console.log('before wallet handler'); -// return "reject"; -// }); - -// dapp.addAdvanceHandler(wallet.handler); - -// dapp.addAdvanceHandler((): string => { -// console.log('final handler'); -// return "reject"; -// }); -// }); - -// const app = express(); -// const port = 8383; -// app.use(express.json()); - - - app.get("/wallet/:address", async (req: Request, res: Response) => { console.log(`Checking balance ${req.params.address}`); - const userWallet = await wallet.getWalletOrNew(req.params.address); + const userWallet = wallet.etherBalanceOf(req.params.address!); const json = JSON.stringify(userWallet, (_key, value) => { if (typeof value === 'bigint') { return value.toString(); @@ -59,7 +25,7 @@ app.get("/wallet/:address", async (req: Request, res: Response) => { app.post("/wallet/ether/transfer", async (req: Request, res: Response) => { try { - await wallet.transferEther( + wallet.transferEther( req.get('x-msg_sender') as string, req.body.to, BigInt(req.body.amount), @@ -72,8 +38,8 @@ app.post("/wallet/ether/transfer", async (req: Request, res: Response) => { app.post("/wallet/ether/withdraw", async (req: Request, res: Response) => { try { - const voucher = await wallet.withdrawEther( - req.get('x-msg_sender') as string, + const voucher = wallet.withdrawEther( + req.get('x-msg_sender') as `0x${string}`, BigInt(req.body.amount) ); const voucherResult = await dapp.createVoucher(voucher); @@ -87,9 +53,9 @@ app.post("/wallet/ether/withdraw", async (req: Request, res: Response) => { app.post("/wallet/erc-20/withdraw", async (req: Request, res: Response) => { try { - const voucher = await wallet.withdrawERC20( + const voucher = wallet.withdrawERC20( req.body.token, - req.get('x-msg_sender') as string, + req.get('x-msg_sender') as `0x${string}`, BigInt(req.body.amount) ); const voucherResult = await dapp.createVoucher(voucher); @@ -103,11 +69,11 @@ app.post("/wallet/erc-20/withdraw", async (req: Request, res: Response) => { app.post("/wallet/erc-20/transfer", async (req: Request, res: Response) => { try { - await wallet.transferERC20( + wallet.transferERC20( req.body.token, req.get('x-msg_sender') as string, req.body.to, - BigInt(req.body.amount), + BigInt(req.body.amount) ); res.send({ ok: 1 }); } catch (e: any) { @@ -117,11 +83,11 @@ app.post("/wallet/erc-20/transfer", async (req: Request, res: Response) => { app.post("/wallet/erc-721/transfer", async (req: Request, res: Response) => { try { - await wallet.transferERC721( + wallet.transferERC721( req.body.token, req.get('x-msg_sender') as string, req.body.to, - BigInt(req.body.tokenId), + BigInt(req.body.tokenId) ); res.send({ ok: 1 }); } catch (e: any) { @@ -131,7 +97,7 @@ app.post("/wallet/erc-721/transfer", async (req: Request, res: Response) => { app.post("/wallet/erc-1155/transfer", async (req: Request, res: Response) => { try { - await wallet.transferERC1155( + wallet.transferERC1155( req.body.token, req.get('x-msg_sender') as string, req.body.to, @@ -146,7 +112,7 @@ app.post("/wallet/erc-1155/transfer", async (req: Request, res: Response) => { throw new Error(`BadRequest value ${value} is not a number`); } return BigInt(value); - }), + }) ); res.send({ ok: 1 }); } catch (e: any) { @@ -156,9 +122,9 @@ app.post("/wallet/erc-1155/transfer", async (req: Request, res: Response) => { app.post("/wallet/erc-721/withdraw", async (req: Request, res: Response) => { try { - const voucher = await wallet.withdrawERC721( + const voucher = wallet.withdrawERC721( req.body.token, - req.get('x-msg_sender') as string, + req.get('x-msg_sender') as `0x${string}`, BigInt(req.body.tokenId) ); const voucherResult = await dapp.createVoucher(voucher); @@ -172,9 +138,9 @@ app.post("/wallet/erc-721/withdraw", async (req: Request, res: Response) => { app.post("/wallet/erc-1155/withdraw", async (req: Request, res: Response) => { try { - const voucher = await wallet.withdrawERC1155( + const voucher = wallet.withdrawERC1155( req.body.token, - req.get('x-msg_sender') as string, + req.get('x-msg_sender') as `0x${string}`, req.body.tokenIds.map((id: number) => { if (typeof id !== 'number') { throw new Error('BadRequest'); @@ -187,6 +153,7 @@ app.post("/wallet/erc-1155/withdraw", async (req: Request, res: Response) => { } return BigInt(value); }), + "0x" ); const voucherResult = await dapp.createVoucher(voucher); res.send({ @@ -201,6 +168,4 @@ app.post('/deposit', (req: Request, res: Response) => { axios.post('http://deroll/voucher'); }); -// app.listen(port, () => { -// console.log(`[server]: Server is running at http://localhost:${port}`); -// }); + diff --git a/apps/cartesify/backend/ts-template/src/index.ts b/apps/cartesify/backend/ts-template/src/index.ts index 88fdf41..8ac6117 100644 --- a/apps/cartesify/backend/ts-template/src/index.ts +++ b/apps/cartesify/backend/ts-template/src/index.ts @@ -1,139 +1,41 @@ + import { Request, Response } from 'express'; +import axios from "axios" import { appConfig } from "./examples/init-config" +import { createWallet } from "@deroll/wallet"; console.log('starting app.js...'); -const { app } = appConfig() +const { app, dapp } = appConfig() interface Greeting { id: number; message: string; - sender: string | undefined; + sender: string } let greetings: Greeting[] = []; let nextId = 1; -// Create a new greeting -// app.post('/greetings', (req: Request, res: Response) => { -// const sender = req.header("x-msg_sender"); -// const { message } = req.body; -// const newGreeting: Greeting = { id: nextId++, message, sender }; -// greetings.push(newGreeting); -// res.status(201).send(newGreeting); -// }); - -// // Get all greetings from a specific sender -// app.get('/greetings', (req: Request, res: Response) => { -// const sender = req.header("x-msg_sender"); -// if (!sender) { -// return res.status(400).send({ message: 'Sender not provided' }); -// } -// const senderGreetings = greetings.filter(g => g.sender === sender); -// res.send(senderGreetings); -// }); - -// // Get a single greeting by ID -// app.get('/greetings/:id', (req: Request, res: Response) => { -// const id = parseInt(req.params.id!, 10); -// const sender = req.header("x-msg_sender"); -// const greeting = greetings.find(g => g.id === id); - -// if (!sender) { -// return res.status(400).send({ message: 'Sender not provided' }); -// } - -// if (greeting) { -// if (greeting.sender !== sender) { -// return res.status(403).send({ message: 'You can only view your own greetings' }); -// } -// res.send(greeting); -// } else { -// res.status(404).send({ message: 'Greeting not found' }); -// } -// }); - -// // Update a greeting by ID -// app.put('/greetings/:id', (req: Request, res: Response) => { -// const id = parseInt(req.params.id!, 10); -// const { message } = req.body; -// const sender = req.header("x-msg_sender"); -// const greeting = greetings.find(g => g.id === id); - -// if (!sender) { -// return res.status(400).send({ message: 'Sender not provided' }); -// } - -// if (greeting) { -// if (greeting.sender !== sender) { -// return res.status(403).send({ message: 'You can only update your own greetings' }); -// } -// greeting.message = message; -// res.send(greeting); -// } else { -// res.status(404).send({ message: 'Greeting not found' }); -// } -// }); - -// // Delete a greeting by ID -// app.delete('/greetings/:id', (req: Request, res: Response) => { -// const id = parseInt(req.params.id!, 10); -// const sender = req.header("x-msg_sender"); -// const index = greetings.findIndex(g => g.id === id); - -// if (!sender) { -// return res.status(400).send({ message: 'Sender not provided' }); -// } - -// if (index !== -1) { -// if (greetings[index]!.sender !== sender) { -// return res.status(403).send({ message: 'You can only delete your own greetings' }); -// } -// greetings.splice(index, 1); -// res.status(204).send(); -// } else { -// res.status(404).send({ message: 'Greeting not found' }); -// } -// }); - -// // Delete all greetings from a specific sender -// app.delete('/greetings/sender', (req: Request, res: Response) => { -// const sender = req.header("x-msg_sender"); - -// if (!sender) { -// return res.status(400).send({ message: 'Sender not provided' }); -// } - -// const initialLength = greetings.length; -// for (let i = greetings.length - 1; i >= 0; i--) { -// if (greetings[i]!.sender === sender) { -// greetings.splice(i, 1); -// } -// } - -// const finalLength = greetings.length; -// const deletedCount = initialLength - finalLength; - -// res.status(200).send({ message: `${deletedCount} greetings deleted` }); -// }); - -// // without the sender check -// // Get all greetings -// app.get('/greetings', (req: Request, res: Response) => { -// res.send(greetings); -// }); - -// app.delete('/greetings/all', (req: Request, res: Response) => { -// const deletedCount = greetings.length; -// greetings.length = 0; -// res.status(200).send({ message: `${deletedCount} greetings deleted` }); -// }); - -app.post('/greeting', (req: Request, res: Response) => { - let greet = req.body as Greeting; - greetings.push(greet); - if (greet) { - res.status(200).json({ message: greet }); +const wallet = createWallet(); + +// Ensure the wallet object is defined and has the etherBalanceOf method +if (!wallet || !wallet.etherBalanceOf + || !wallet.transferEther || !wallet.transferERC20 || + !wallet.transferERC721 || !wallet.transferERC1155 || !wallet.getWallet + || !wallet.withdrawEther || !wallet.withdrawERC20 || !wallet.withdrawERC721 + || !wallet.withdrawERC1155 +) { + throw new Error('Wallet object is not defined'); +} + +app.post('/greetings', (req: Request, res: Response) => { + // const sender = req.header("x-msg_sender"); + const { message, sender } = req.body; + const newGreeting: Greeting = { id: nextId++, message, sender }; + greetings.push(newGreeting); + if (message) { + res.status(200).json(newGreeting); } else { res.status(400).json({ error: 'Please provide a greeting' }); } @@ -189,3 +91,193 @@ app.delete('/greetings/:id', (req: Request, res: Response) => { res.json({ message: 'Item deleted successfully' }); }); +app.delete('/greetings', (req: Request, res: Response) => { + const deletedCount = greetings.length; + greetings.length = 0; + res.status(200).send({ message: `${deletedCount} greetings deleted` }); +}); + + +app.get("/wallet/:address", async (req: Request, res: Response) => { + console.log(`Checking balance ${req.params.address}`); + const userWallet = await wallet.getWallet(req.params.address!); + console.log("UserWallet", userWallet) + const json = JSON.stringify(userWallet, (_key, value) => { + if (typeof value === 'bigint') { + return value.toString(); + } else if (typeof value === 'object' && value instanceof Map) { + return Object.fromEntries(value); + } else if (typeof value === 'object' && value instanceof Set) { + return [...value]; + } else { + return value; + } + }); + res.setHeader('Content-Type', 'application/json; charset=utf-8'); + res.send(json); +}); + +app.post("/wallet/ether/transfer", async (req: Request, res: Response) => { + try { + wallet.transferEther( + req.get('x-msg_sender') as string, + req.body.to, + BigInt(req.body.amount), + ); + res.send({ ok: 1 }); + } catch (e: any) { + res.status(400).send({ message: e.message }); + } +}); + +app.post("/wallet/ether/withdraw", async (req: Request, res: Response) => { + try { + const voucher = wallet.withdrawEther( + req.get('x-msg_sender') as `0x${string}`, + BigInt(req.body.amount) + ); + const voucherResult = await dapp.createVoucher(voucher); + res.send({ + ok: 1, voucherResult, inputIndex: req.get('x-input_index') + }); + } catch (e: any) { + res.status(400).send({ message: e.message }); + } +}); + +app.post("/wallet/erc-20/withdraw", async (req: Request, res: Response) => { + try { + const voucher = wallet.withdrawERC20( + req.body.token, + req.get('x-msg_sender') as `0x${string}`, + BigInt(req.body.amount) + ); + const voucherResult = await dapp.createVoucher(voucher); + res.send({ + ok: 1, voucherResult, inputIndex: req.get('x-input_index') + }); + } catch (e: any) { + res.status(400).send({ message: e.message }); + } +}); + +app.post("/wallet/erc-20/transfer", async (req: Request, res: Response) => { + try { + wallet.transferERC20( + req.body.token, + req.get('x-msg_sender') as string, + req.body.to, + BigInt(req.body.amount) + ); + res.send({ ok: 1 }); + } catch (e: any) { + res.status(400).send({ message: e.message }); + } +}); + +app.post("/wallet/erc-721/transfer", async (req: Request, res: Response) => { + try { + wallet.transferERC721( + req.body.token, + req.get('x-msg_sender') as string, + req.body.to, + BigInt(req.body.tokenId) + ); + res.send({ ok: 1 }); + } catch (e: any) { + res.status(400).send({ message: e.message }); + } +}); + +app.post("/wallet/erc-1155/transfer", async (req: Request, res: Response) => { + try { + wallet.transferERC1155( + req.body.token, + req.get('x-msg_sender') as string, + req.body.to, + req.body.tokenIds.map((id: number) => { + if (typeof id !== 'number') { + throw new Error(`BadRequest id ${id} is not a number`); + } + return BigInt(id); + }), + req.body.values.map((value: number) => { + if (typeof value !== 'number') { + throw new Error(`BadRequest value ${value} is not a number`); + } + return BigInt(value); + }) + ); + res.send({ ok: 1 }); + } catch (e: any) { + res.status(400).send({ message: e.message }); + } +}); + +app.post("/wallet/erc-721/withdraw", async (req: Request, res: Response) => { + try { + const voucher = wallet.withdrawERC721( + req.body.token, + req.get('x-msg_sender') as `0x${string}`, + BigInt(req.body.tokenId) + ); + const voucherResult = await dapp.createVoucher(voucher); + res.send({ + ok: 1, voucherResult, inputIndex: req.get('x-input_index') + }); + } catch (e: any) { + res.status(400).send({ message: e.message }); + } +}); + +app.post("/wallet/erc-1155/withdraw", async (req: Request, res: Response) => { + try { + const voucher = wallet.withdrawERC1155( + req.body.token, + req.get('x-msg_sender') as `0x${string}`, + req.body.tokenIds.map((id: number) => { + if (typeof id !== 'number') { + throw new Error('BadRequest'); + } + return BigInt(id); + }), + req.body.values.map((value: number) => { + if (typeof value !== 'number') { + throw new Error('BadRequest'); + } + return BigInt(value); + }), + "0x" + ); + const voucherResult = await dapp.createVoucher(voucher); + res.send({ + ok: 1, voucherResult, inputIndex: req.get('x-input_index') + }); + } catch (e: any) { + res.status(400).send({ message: e.message }); + } +}); + +app.post('/deposit', (req: Request, res: Response) => { + axios.post('http://deroll/voucher'); + }); + + app.get("/health", (req: Request, res: Response) => { + res.send({ some: "response" }); + }); + + app.post('/echo', (req: Request, res: Response) => { + res.send({ myPost: req.body }); + }); + + app.post('/echo', (req: Request, res: Response) => { + res.send({ myPost: req.body }); + }); + + app.post('/echo/headers', (req: Request, res: Response) => { + res.send({ headers: req.headers }); + }); + + app.get('/echo/headers', (req: Request, res: Response) => { + res.send({ headers: req.headers }); + }); \ No newline at end of file diff --git a/apps/cartesify/frontend/next-app/app/cartesi/Balance.tsx b/apps/cartesify/frontend/next-app/app/cartesi/Balance.tsx index 103638e..da6a480 100644 --- a/apps/cartesify/frontend/next-app/app/cartesi/Balance.tsx +++ b/apps/cartesify/frontend/next-app/app/cartesi/Balance.tsx @@ -1,5 +1,6 @@ -import React from "react"; -import { ethers } from "ethers"; +import React, { useState } from "react"; +import { fetchWallet } from "./services/RestApiCalls" +import { callDAppAddressRelay } from "./services/Portal" import { Table, Thead, @@ -12,11 +13,17 @@ import { Stack, Box, } from '@chakra-ui/react' + import { useAccount } from "wagmi" + import { useEthersSigner } from "../utils/useEtherSigner" export const Balance: React.FC = () => { - + const [backendResponse, setResponse] = useState('') + const signer = useEthersSigner() + const { chain } = useAccount() + console.log(backendResponse) return ( - +
+ @@ -30,13 +37,22 @@ export const Balance: React.FC = () => { + {backendResponse === "" ? + : + }
looks like your cartesi dapp balance is zero! 🙁{backendResponse}
- + +
+
); }; diff --git a/apps/cartesify/frontend/next-app/app/cartesi/RestExample.tsx b/apps/cartesify/frontend/next-app/app/cartesi/RestExample.tsx deleted file mode 100644 index aeb1e75..0000000 --- a/apps/cartesify/frontend/next-app/app/cartesi/RestExample.tsx +++ /dev/null @@ -1,48 +0,0 @@ -'use client' -import { useEffect, useState } from "react" -import { Button } from "@chakra-ui/react" -import { useEthersSigner } from "../utils/useEtherSigner" -import { createOrUpdateRequest, fetchWallet, getRequest } from "./services/RestApiCalls" -import { callDAppAddressRelay } from "./services/Portal" -import { useAccount } from "wagmi" - -export function RestExample() { - const [backendResponse, setResponse] = useState('') - const signer = useEthersSigner() - const { chain } = useAccount() - - return ( -
-
- - - - - -
- - - -
- - -
- Backend response:
{backendResponse}
-
-
- -
- ) -} \ No newline at end of file diff --git a/apps/cartesify/frontend/next-app/app/cartesi/Transfers.tsx b/apps/cartesify/frontend/next-app/app/cartesi/Transfers.tsx index 1a8604f..313d325 100644 --- a/apps/cartesify/frontend/next-app/app/cartesi/Transfers.tsx +++ b/apps/cartesify/frontend/next-app/app/cartesi/Transfers.tsx @@ -21,6 +21,7 @@ import { depositBatchERC1155, depositERC20, depositERC721, depositEther, deposit import { batchWithdraw, getERC1155Balance, getERC20Balance, getERC721Balance, getEtherBalance, transferErc1155, transferErc20, transferErc721, transferEther, withdrawErc1155, withdrawErc20, withdrawErc721, withdrawEther } from "./services/RestApiCalls"; import { Batch } from "./model"; import { errorAlert } from "../utils/customAlert"; +import { parseEther } from "ethers"; const Transfers: React.FC = () => { @@ -102,14 +103,9 @@ const clear1155Batch = () => { }; return ( - + - 🚀 REST Example { - - -
-
Cartesi dApps recieve asset deposits via Portal smart contracts on @@ -311,7 +303,7 @@ const clear1155Batch = () => { size="sm" onClick={async () => { setLoadL2ERC20(true) - await transferErc20(signer, erc20Token, toAddress, Number(erc20Amount)) + await transferErc20(signer, erc20Token, toAddress, erc20Amount) setLoadL2ERC20(false) }} > {loadL2ERC20 ? "Transferring please wait..🤑" :"L2 Transfer"} @@ -323,9 +315,10 @@ const clear1155Batch = () => { colorScheme="" size="sm" onClick={async () => { + if(!erc20Token) return errorAlert("Token field required") setLoadERC20Balance(true) - await getERC20Balance(signer!, erc20Token,setErc20balanceL1, setErc20balanceL2 ) - setLoadERC20Balance(true) + await getERC20Balance(signer!, erc20Token, setErc20balanceL1, setErc20balanceL2 ) + setLoadERC20Balance(false) }} > {loadERC20Balance ? "Fetching balance please wait..🤑" :"Get Balance"} @@ -370,8 +363,8 @@ const clear1155Batch = () => { color="slategrey" variant="outline" placeholder="Receipient address required for L2 transfer" - onChange={(e) => setErc20Token(String(e.target.value))} - value={erc20Token} + onChange={(e) => setToAddress(String(e.target.value))} + value={toAddress} /> )} @@ -458,195 +451,195 @@ const clear1155Batch = () => { - setErc1155(String(e.target.value))} - value={erc1155} - /> - {isL2transfer && ( - setToAddress(e.target.value)} - value={toAddress} // Fixed the value to use toAddress instead of erc20Token - /> - )} - setErc1155Id(e.target.value)} - value={erc1155Id} - /> - setErc1155Amount(e.target.value)} - value={erc1155Amount} - /> - {!isChecked && !isL2transfer && ( -
- - -
-

L1 Balance: {erc1155balanceL1}

-

L2 Balance: {erc1155balanceL2}

-
-
+ setErc1155(String(e.target.value))} + value={erc1155} + /> + {isL2transfer && ( + setToAddress(e.target.value)} + value={toAddress} // Fixed the value to use toAddress instead of erc20Token + /> + )} + setErc1155Id(e.target.value)} + value={erc1155Id} + /> + setErc1155Amount(e.target.value)} + value={erc1155Amount} + /> + {!isChecked && !isL2transfer && ( +
+ + +
+

L1 Balance: {erc1155balanceL1}

+

L2 Balance: {erc1155balanceL2}

+
+
- )} - {isL2transfer && !isChecked && ( -
- - -
- )} - {isChecked && !isL2transfer && ( -
- - {/*
-

L1 Balance: {erc1155balanceL1}

-

L2 Balance: {erc1155balanceL2}

-
*/} - - Ids: {erc1155IdsStr} - Amounts: {erc1155AmountsStr} - - - - - {/* */} - {/* */} -
- )} -
+ )} + {isL2transfer && !isChecked && ( +
+ + +
+ )} + {isChecked && !isL2transfer && ( +
+ + {/*
+

L1 Balance: {erc1155balanceL1}

+

L2 Balance: {erc1155balanceL2}

+
*/} + + Ids: {erc1155IdsStr} - Amounts: {erc1155AmountsStr} + + + + + {/* */} + {/* */} +
+ )} +
diff --git a/apps/cartesify/frontend/next-app/app/cartesi/VoucherView.tsx b/apps/cartesify/frontend/next-app/app/cartesi/VoucherView.tsx index 0d5bcb6..ab73013 100644 --- a/apps/cartesify/frontend/next-app/app/cartesi/VoucherView.tsx +++ b/apps/cartesify/frontend/next-app/app/cartesi/VoucherView.tsx @@ -6,6 +6,7 @@ import { Button } from "@chakra-ui/react" import { DAPP_ADDRESS } from "../utils/constants" import { useEthersSigner } from "../utils/useEtherSigner" import { executeVoucher } from "./services/Portal" +import { useAccount } from "wagmi" export default function VoucherView() { @@ -48,14 +49,14 @@ export default function VoucherView() { function VoucherERC1155({ voucher }: { voucher: Voucher }) { const signer = useEthersSigner() - + const { chain } = useAccount() const hasProof = !!voucher.proof?.validity return ( <> {voucher.destination} {hasProof ? ( ) : ( waiting for proof diff --git a/apps/cartesify/frontend/next-app/app/cartesi/services/Portal.ts b/apps/cartesify/frontend/next-app/app/cartesi/services/Portal.ts index 3f15953..73748b5 100644 --- a/apps/cartesify/frontend/next-app/app/cartesi/services/Portal.ts +++ b/apps/cartesify/frontend/next-app/app/cartesi/services/Portal.ts @@ -17,7 +17,7 @@ export const balanceERC20 = async (erc20address: string, signer: JsonRpcSigner) try{ const contract = IERC20__factory.connect(erc20address, signer) const balance = await contract.balanceOf(signer.address) - return balance + return balance }catch(error){ console.log(error) } @@ -102,7 +102,8 @@ export const depositERC20 = async (dappAddress: string, erc20address: string, const portal = ERC20Portal__factory.connect(portalAddress, signer) const tx = await portal.depositERC20Tokens(erc20address, dappAddress, parseUnits(erc20value, 6), '0x') const receipt = await (tx as any).wait() - successAlert(`${explorer/+"tx"/receipt.hash}`) + console.log(explorer) + successAlert(`Successfully deposited`) } catch (error) { console.log(error) errorAlert(error) @@ -116,7 +117,7 @@ export const depositERC721 = async (dappAddress: string, erc721address: string, const explorer = config[toHex(chain.id)].explorer const contract = IERC721__factory.connect(erc721address, signer) await contract.approve(portalAddress, erc721id) - const portal = ERC721Portal__factory.connect(portalAddress, signer) + const portal = ERC721Portal__factory.connect(portalAddress, signer) const tx = await portal.depositERC721Token(erc721address, dappAddress, erc721id, '0x', '0x') const receipt = await (tx as any).wait() successAlert(`${explorer/+"tx"/receipt.hash}`) @@ -191,7 +192,9 @@ export const callDAppAddressRelay = async (signer: JsonRpcSigner | undefined, ch const relay = DAppAddressRelay__factory.connect(portalAddress, signer) const tx = await relay.relayDAppAddress(DAPP_ADDRESS) const receipt = await (tx as any).wait() - console.log('Executed!', receipt) + console.log('Executed!', receipt.hash) + console.log("hash", receipt.hash) + console.log("explorer", explorer) successAlert(`${explorer/+"tx"/receipt.hash}`) } catch (error) { errorAlert(error) diff --git a/apps/cartesify/frontend/next-app/app/cartesi/services/RestApiCalls.ts b/apps/cartesify/frontend/next-app/app/cartesi/services/RestApiCalls.ts index 512c8c3..3bcc80a 100644 --- a/apps/cartesify/frontend/next-app/app/cartesi/services/RestApiCalls.ts +++ b/apps/cartesify/frontend/next-app/app/cartesi/services/RestApiCalls.ts @@ -1,4 +1,4 @@ -import { JsonRpcSigner } from "ethers"; +import { JsonRpcSigner, parseEther } from "ethers"; import { RPC_URL, BASE_URL } from "../../utils/constants"; import { fetch } from '../../utils/cartersify-init' import { Batch } from "../model"; @@ -24,7 +24,7 @@ export const transferEther = async ( try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) } successAlert("Transfer successful") console.log('Success!') @@ -37,7 +37,7 @@ export const transferEther = async ( export const transferErc20 = async ( signer: JsonRpcSigner | undefined, erc20address: string, toAddress: string, - erc20value: number + erc20value: string ) => { const res = await fetch(`${BASE_URL}/wallet/erc-20/transfer`, { method: 'POST', @@ -54,7 +54,7 @@ export const transferErc20 = async ( try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) } successAlert("Success") console.log('Success!') @@ -84,7 +84,7 @@ export const transferErc721 = async ( try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) } console.log('Success!') successAlert("Success!") @@ -112,7 +112,7 @@ export const transferErc1155 = async (signer: JsonRpcSigner, erc1155address: st try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) } const json = await res.json() console.log(json) @@ -137,14 +137,14 @@ export const withdrawEther = async ( }) try { if (!res.ok) { - console.log(res.status, res.text()) - return + console.log(res.status, await res.text()) + return errorAlert(`${(await res.text())}`) } console.log('Success!') successAlert("Withdrawn successfully!") - } catch (error) { + } catch (error: any) { console.log(error) - errorAlert(error) + errorAlert(error.message) } } @@ -167,7 +167,7 @@ export const withdrawErc20 = async ( try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) } successAlert("Success") console.log('Success!') @@ -197,8 +197,8 @@ export const withdrawErc20 = async ( }) try { if (!res.ok) { - console.log(res.status, res.text()) - return + console.log(res.status, await res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) } successAlert('Success!') } catch (error) { @@ -229,7 +229,7 @@ export const withdrawErc1155 = async ( try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) } successAlert('Success!') } catch (error) { @@ -257,7 +257,8 @@ export const batchWithdraw = async ( try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() console.log(json) @@ -268,7 +269,16 @@ export const batchWithdraw = async ( export const fetchBatchBalance = async (signer: JsonRpcSigner, erc1155address: string, batch: Batch[]) => { try { - const res = await fetch(`${BASE_URL}/wallet/${signer.address}`) + const res = await fetch(`${BASE_URL}/wallet/${signer.address}`,{ + method: "GET", + headers: { + "Content-Type": "application/json", + }, + }) + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const wallet = await res.json() const erc1155tokens = wallet.erc1155[erc1155address] if (erc1155tokens) { @@ -281,19 +291,21 @@ export const fetchBatchBalance = async (signer: JsonRpcSigner, erc1155address: s } } +// This function handles get request export const getRequest = async ( - signer: JsonRpcSigner | undefined, endpoint: string, ) => { try { - const address = await signer?.getAddress() const res = await fetch(`${BASE_URL}/${endpoint}`, { method: "GET", headers: { "Content-Type": "application/json", - 'x-msg_sender': address! }, }) + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() return JSON.stringify(json) } catch (error) { @@ -301,23 +313,27 @@ export const getRequest = async ( } } +// This function can be used for both create, update and delete export const createOrUpdateRequest = async ( signer: JsonRpcSigner | undefined, endpoint: string, method: string, body?: string, ) => { - const address = await signer?.getAddress() const res = await fetch(`${BASE_URL}/${endpoint}`, { method, headers: { 'Content-Type': 'application/json', - 'x-msg_sender': address! + // 'x-msg_sender': address! }, body, signer }) try{ + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() return JSON.stringify(json, null, 4) }catch(error){ @@ -330,27 +346,50 @@ export const fetchWallet = async (signer: JsonRpcSigner | undefined, setResponse: Function ) => { try { - const res = await fetch(`${BASE_URL}/${signer?.address}`) + const res = await fetch(`${BASE_URL}/wallet/${signer?.address}`, { + method: "GET", + headers: { + "Content-Type": "application/json", + }, + }) + console.log("res", res.status) + + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() setResponse(JSON.stringify(json, null, 4)) successAlert("Successful!") - } catch (error) { - errorAlert(error) + } catch (error: any) { + errorAlert(error.message) } } export const getEtherBalance = async (signer: JsonRpcSigner | undefined, setEtherBalanceL1: Function, setEtherBalanceL2: Function ) => { try { - const res = await fetch(`${BASE_URL}/${signer?.address}`) + console.log("Address", signer?.address) + const res = await fetch(`${BASE_URL}/wallet/${signer?.address}`, + { + method: "GET", + headers: { + "Content-Type": "application/json", + }, + } + ) + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() setEtherBalanceL2(json.ether) const balance = await signer?.provider.getBalance(signer.address) setEtherBalanceL1(balance?.toString()) console.log('Success!') successAlert("Succesfully fetched balance") - } catch (error) { + } catch (error: any) { console.log(error) - errorAlert(error) + errorAlert(error.message) } } @@ -362,9 +401,14 @@ export const getERC20Balance = async ( ) => { try { const res = await fetch(`${BASE_URL}/wallet/${signer?.address}`) + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() setErc20balanceL2(json.erc20[erc20address] ?? '0') const balance = await balanceERC20(erc20address, signer) + console.log(balance) setErc20balanceL1(balance.toString()) console.log('Success!') successAlert("Success") @@ -405,6 +449,10 @@ export const getERC1155Balance = async ( try { const url = `${BASE_URL}/wallet/${signer.address}` const res = await fetch(url) + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() setErc1155balanceL2(json.erc1155[erc1155address]?.length ?? '0') const balance = await balanceERC1155(erc1155address, signer!, tokenId) @@ -434,8 +482,12 @@ export const sendRPCCommand = async (method: string, params: any[]) => { }; try { - const response = await fetch(rpcUrl, requestOptions); - const responseData = await response.json(); + const res = await fetch(rpcUrl, requestOptions); + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } + const responseData = await res.json(); console.log(responseData); } catch (error) { console.error(error) diff --git a/apps/cartesify/frontend/next-app/app/components/greetings.tsx b/apps/cartesify/frontend/next-app/app/components/greetings.tsx index 4bebd5a..c80a239 100644 --- a/apps/cartesify/frontend/next-app/app/components/greetings.tsx +++ b/apps/cartesify/frontend/next-app/app/components/greetings.tsx @@ -1,98 +1,166 @@ -'use client' -import {useState, useEffect, useCallback } from 'react' -import { useAccount } from 'wagmi' -import { useEthersSigner } from '../utils/useEtherSigner' -import { createOrUpdateRequest, getRequest } from '../cartesi/services/RestApiCalls' -import { errorAlert, successAlert } from '../utils/customAlert' +'use client'; +import { useState, useEffect, useCallback } from 'react'; +import { useAccount } from 'wagmi'; +import { useEthersSigner } from '../utils/useEtherSigner'; +import { createOrUpdateRequest, getRequest } from '../cartesi/services/RestApiCalls'; +import { errorAlert, successAlert } from '../utils/customAlert'; +import { + Table, + Thead, + Tbody, Tr, + Th, + Td, + TableCaption, + TableContainer +} from '@chakra-ui/react'; + export default function Greetings() { - const [loading, setLoading] = useState(false) - const [data, setData] = useState('') - const [listMessages, setMessageList] = useState<[]>() - const [fetching, setFetching] = useState(false) - const [message, setMessage] = useState('') - const { address } = useAccount() - const signer = useEthersSigner() - - const messageArray = [] - const handleMessageChange = (e: React.ChangeEvent) => setMessage(e.target.value) + const [loading, setLoading] = useState(false); + const [listMessages, setMessageList] = useState([]); + const [fetching, setFetching] = useState(false); + const [message, setMessage] = useState(''); + const [isEdit, setEdit] = useState(false); + const [id, setId] = useState(0); + + const { address } = useAccount(); + const signer = useEthersSigner(); + + const handleMessageChange = (e: React.ChangeEvent) => setMessage(e.target.value); const sendGreeting = async () => { - try{ - if(!message) return errorAlert("Field required") - if(!address) return errorAlert("Ensure your wallet is connect") - setLoading(true) - const res = await createOrUpdateRequest(signer, "greeting", "POST", - JSON.stringify({ message})) - setLoading(false) - successAlert(res) - }catch(error){ - setLoading(false) - console.log(error) - errorAlert(error) + try { + if (!message) return errorAlert("Field required"); + if (!address) return errorAlert("Ensure your wallet is connected"); + setLoading(true); + await createOrUpdateRequest(signer, "greetings", "POST", + JSON.stringify({ message, sender: address })); + setMessage(""); + setLoading(false); + successAlert("Successfully sent!"); + await getGreetings(); + } catch (error) { + setLoading(false); + console.log(error); + errorAlert(error); } - } + }; - const getGreeting = useCallback( async () => { - try{ - setFetching(true) - await getRequest(signer, "greetings?id=1") - setFetching(false) - }catch(error){ - setFetching(false) - console.log("error", error) + const updateMessage = async (id: number) => { + try { + if (!message) return errorAlert("Field required"); + if (!address) return errorAlert("Ensure your wallet is connected"); + setLoading(true); + await createOrUpdateRequest(signer, `greetings/${id}`, "PUT", JSON.stringify({ message, sender: address })); + setMessage(""); + setLoading(false); + successAlert("Successfully sent!"); + setEdit(false); + await getGreetings(); + } catch (error) { + setLoading(false); + errorAlert(error); } - }, []) + }; - const getAllGreeting = useCallback( async () => { - try{ - setFetching(true) - const res = await getRequest(signer, "greetings") - setMessageList(JSON.parse(res!)) - setFetching(false) - }catch(error){ - setFetching(false) - console.log("error", error) + const getGreeting = useCallback(async (id: number) => { + try { + setFetching(true); + await getRequest(`greetings/${id}`); + setFetching(false); + } catch (error) { + setFetching(false); + console.log("error", error); } - }, [signer]) + }, []); + + const getGreetings = useCallback(async () => { + try { + setFetching(true); + const res = await getRequest("greetings"); + console.log("res", res); + console.log(JSON.parse(res!).greetings); + setMessageList(JSON.parse(res!).greetings); // Assuming res is JSON string + setFetching(false); + } catch (error) { + setFetching(false); + console.log("error", error); + } + }, []); + + console.log("listMessages", listMessages); + console.log("id", id); + useEffect(() => { + getGreetings(); + }, [getGreetings]); - console.log("listMessages", listMessages) - useEffect(() =>{ - getAllGreeting() - },[data, getAllGreeting]) + return ( +
+

Welcome! Say Hello 👋

+ + + {fetching && (

Fetching data...

)} - return ( -
-

Welcome! Say Hello 👋

- - - {/* {fetching ? (

Fetching data...

) : data ? ( -
-

Output

-

{ - listMessages && listMessages?.length > 0 && ( - listMessages.map((item: any, index: any) =>

- {item.message} -

) - ) - }

-
- ) :
- } */} + {listMessages && listMessages.length === 0 ? "" : + ( +
+

Output

+ + + { + try { + await createOrUpdateRequest(signer, 'greetings', "DELETE"); + successAlert("Successfully deleted"); + await getGreetings(); + } catch (error) { + errorAlert(error); + } -
-

Output

-

{ - listMessages && listMessages.length && ( - listMessages.map((item: any, index: any) =>

- {item.message} - -

) - ) - }

-
- + }} textColor={"purple"} paddingBottom={"24px"} className='text-red-400'>Delete all messages
+ + + + + + + + + {listMessages.map((item: any, index: any) => ( + + + + + + ))} + +
S/NMessageRemove
{item.id} { + try { + setId(item.id); + setEdit(true); + setMessage(item.message); + } catch (error) { + errorAlert(error); + } + }} className='text-gray-400'>{item.message} { + try { + await createOrUpdateRequest(signer, `greetings/${item.id}`, "DELETE"); + successAlert("Successfully deleted"); + await getGreetings(); + } catch (error) { + errorAlert(error); + } + }} className='bg-red-400 rounded p-4'>🗑️
+
+
+ )} +
); } diff --git a/apps/cartesify/frontend/next-app/app/page.tsx b/apps/cartesify/frontend/next-app/app/page.tsx index e8422c0..f0e88c7 100644 --- a/apps/cartesify/frontend/next-app/app/page.tsx +++ b/apps/cartesify/frontend/next-app/app/page.tsx @@ -1,5 +1,5 @@ "use client" -import Greetings from "./components/greetings"; +import Greetings from './components/Greetings'; const Home: React.FC = () => { diff --git a/apps/cartesify/frontend/react-app/src/cartesi/Balance.tsx b/apps/cartesify/frontend/react-app/src/cartesi/Balance.tsx index 103638e..da6a480 100644 --- a/apps/cartesify/frontend/react-app/src/cartesi/Balance.tsx +++ b/apps/cartesify/frontend/react-app/src/cartesi/Balance.tsx @@ -1,5 +1,6 @@ -import React from "react"; -import { ethers } from "ethers"; +import React, { useState } from "react"; +import { fetchWallet } from "./services/RestApiCalls" +import { callDAppAddressRelay } from "./services/Portal" import { Table, Thead, @@ -12,11 +13,17 @@ import { Stack, Box, } from '@chakra-ui/react' + import { useAccount } from "wagmi" + import { useEthersSigner } from "../utils/useEtherSigner" export const Balance: React.FC = () => { - + const [backendResponse, setResponse] = useState('') + const signer = useEthersSigner() + const { chain } = useAccount() + console.log(backendResponse) return ( - +
+ @@ -30,13 +37,22 @@ export const Balance: React.FC = () => { + {backendResponse === "" ? + : + }
looks like your cartesi dapp balance is zero! 🙁{backendResponse}
- + +
+
); }; diff --git a/apps/cartesify/frontend/react-app/src/cartesi/RestExample.tsx b/apps/cartesify/frontend/react-app/src/cartesi/RestExample.tsx deleted file mode 100644 index aeb1e75..0000000 --- a/apps/cartesify/frontend/react-app/src/cartesi/RestExample.tsx +++ /dev/null @@ -1,48 +0,0 @@ -'use client' -import { useEffect, useState } from "react" -import { Button } from "@chakra-ui/react" -import { useEthersSigner } from "../utils/useEtherSigner" -import { createOrUpdateRequest, fetchWallet, getRequest } from "./services/RestApiCalls" -import { callDAppAddressRelay } from "./services/Portal" -import { useAccount } from "wagmi" - -export function RestExample() { - const [backendResponse, setResponse] = useState('') - const signer = useEthersSigner() - const { chain } = useAccount() - - return ( -
-
- - - - - -
- - - -
- - -
- Backend response:
{backendResponse}
-
-
- -
- ) -} \ No newline at end of file diff --git a/apps/cartesify/frontend/react-app/src/cartesi/Transfers.tsx b/apps/cartesify/frontend/react-app/src/cartesi/Transfers.tsx index 6afda0c..6470645 100644 --- a/apps/cartesify/frontend/react-app/src/cartesi/Transfers.tsx +++ b/apps/cartesify/frontend/react-app/src/cartesi/Transfers.tsx @@ -1,3 +1,4 @@ +"use client" import React, { useState, useEffect } from "react"; import { Tabs, TabList, TabPanels, TabPanel, Tab, Card, CardBody, Checkbox } from "@chakra-ui/react"; import { Button, Box } from "@chakra-ui/react"; @@ -101,14 +102,9 @@ const clear1155Batch = () => { }; return ( - + - 🚀 REST Example { - - -
-
Cartesi dApps recieve asset deposits via Portal smart contracts on @@ -457,195 +449,195 @@ const clear1155Batch = () => {
- setErc1155(String(e.target.value))} - value={erc1155} - /> - {isL2transfer && ( - setToAddress(e.target.value)} - value={toAddress} // Fixed the value to use toAddress instead of erc20Token - /> - )} - setErc1155Id(e.target.value)} - value={erc1155Id} - /> - setErc1155Amount(e.target.value)} - value={erc1155Amount} - /> - {!isChecked && !isL2transfer && ( -
- - -
-

L1 Balance: {erc1155balanceL1}

-

L2 Balance: {erc1155balanceL2}

-
-
+ setErc1155(String(e.target.value))} + value={erc1155} + /> + {isL2transfer && ( + setToAddress(e.target.value)} + value={toAddress} // Fixed the value to use toAddress instead of erc20Token + /> + )} + setErc1155Id(e.target.value)} + value={erc1155Id} + /> + setErc1155Amount(e.target.value)} + value={erc1155Amount} + /> + {!isChecked && !isL2transfer && ( +
+ + +
+

L1 Balance: {erc1155balanceL1}

+

L2 Balance: {erc1155balanceL2}

+
+
- )} - {isL2transfer && !isChecked && ( -
- - -
- )} - {isChecked && !isL2transfer && ( -
- - {/*
-

L1 Balance: {erc1155balanceL1}

-

L2 Balance: {erc1155balanceL2}

-
*/} - - Ids: {erc1155IdsStr} - Amounts: {erc1155AmountsStr} - - - - - {/* */} - {/* */} -
- )} -
+ )} + {isL2transfer && !isChecked && ( +
+ + +
+ )} + {isChecked && !isL2transfer && ( +
+ + {/*
+

L1 Balance: {erc1155balanceL1}

+

L2 Balance: {erc1155balanceL2}

+
*/} + + Ids: {erc1155IdsStr} - Amounts: {erc1155AmountsStr} + + + + + {/* */} + {/* */} +
+ )} +
diff --git a/apps/cartesify/frontend/react-app/src/cartesi/services/RestApiCalls.ts b/apps/cartesify/frontend/react-app/src/cartesi/services/RestApiCalls.ts index 8154362..e714a04 100644 --- a/apps/cartesify/frontend/react-app/src/cartesi/services/RestApiCalls.ts +++ b/apps/cartesify/frontend/react-app/src/cartesi/services/RestApiCalls.ts @@ -24,7 +24,7 @@ export const transferEther = async ( try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) } successAlert("Transfer successful") console.log('Success!') @@ -54,7 +54,7 @@ export const transferErc20 = async ( try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) } successAlert("Success") console.log('Success!') @@ -84,7 +84,7 @@ export const transferErc721 = async ( try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) } console.log('Success!') successAlert("Success!") @@ -112,7 +112,7 @@ export const transferErc1155 = async (signer: JsonRpcSigner, erc1155address: st try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) } const json = await res.json() console.log(json) @@ -137,14 +137,14 @@ export const withdrawEther = async ( }) try { if (!res.ok) { - console.log(res.status, res.text()) - return + console.log(res.status, await res.text()) + return errorAlert(`${(await res.text())}`) } console.log('Success!') successAlert("Withdrawn successfully!") - } catch (error) { + } catch (error: any) { console.log(error) - errorAlert(error) + errorAlert(error.message) } } @@ -167,7 +167,7 @@ export const withdrawErc20 = async ( try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) } successAlert("Success") console.log('Success!') @@ -197,8 +197,8 @@ export const withdrawErc20 = async ( }) try { if (!res.ok) { - console.log(res.status, res.text()) - return + console.log(res.status, await res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) } successAlert('Success!') } catch (error) { @@ -229,7 +229,7 @@ export const withdrawErc1155 = async ( try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) } successAlert('Success!') } catch (error) { @@ -257,7 +257,8 @@ export const batchWithdraw = async ( try { if (!res.ok) { console.log(res.status, res.text()) - return + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() console.log(json) @@ -268,7 +269,16 @@ export const batchWithdraw = async ( export const fetchBatchBalance = async (signer: JsonRpcSigner, erc1155address: string, batch: Batch[]) => { try { - const res = await fetch(`${BASE_URL}/wallet/${signer.address}`) + const res = await fetch(`${BASE_URL}/wallet/${signer.address}`,{ + method: "GET", + headers: { + "Content-Type": "application/json", + }, + }) + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const wallet = await res.json() const erc1155tokens = wallet.erc1155[erc1155address] if (erc1155tokens) { @@ -281,8 +291,8 @@ export const fetchBatchBalance = async (signer: JsonRpcSigner, erc1155address: s } } +// This function handles get request export const getRequest = async ( - setResponse: Function, endpoint: string, ) => { try { @@ -292,14 +302,18 @@ export const getRequest = async ( "Content-Type": "application/json", }, }) + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() - setResponse(JSON.stringify(json)) return JSON.stringify(json) } catch (error) { console.log(error) } } +// This function can be used for both create, update and delete export const createOrUpdateRequest = async ( signer: JsonRpcSigner | undefined, endpoint: string, @@ -309,12 +323,17 @@ export const createOrUpdateRequest = async ( const res = await fetch(`${BASE_URL}/${endpoint}`, { method, headers: { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', + // 'x-msg_sender': address! }, body, signer }) try{ + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() return JSON.stringify(json, null, 4) }catch(error){ @@ -327,27 +346,43 @@ export const fetchWallet = async (signer: JsonRpcSigner | undefined, setResponse: Function ) => { try { - const res = await fetch(`${BASE_URL}/${signer?.address}`) + const res = await fetch(`${BASE_URL}/wallet/${signer?.address}`) + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() setResponse(JSON.stringify(json, null, 4)) successAlert("Successful!") - } catch (error) { - errorAlert(error) + } catch (error: any) { + errorAlert(error.message) } } export const getEtherBalance = async (signer: JsonRpcSigner | undefined, setEtherBalanceL1: Function, setEtherBalanceL2: Function ) => { try { - const res = await fetch(`${BASE_URL}/${signer?.address}`) + console.log("Address", signer?.address) + const res = await fetch(`${BASE_URL}/wallet/${signer?.address}`, + { + method: "GET", + headers: { + "Content-Type": "application/json", + }, + } + ) + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() setEtherBalanceL2(json.ether) const balance = await signer?.provider.getBalance(signer.address) setEtherBalanceL1(balance?.toString()) console.log('Success!') successAlert("Succesfully fetched balance") - } catch (error) { + } catch (error: any) { console.log(error) - errorAlert(error) + errorAlert(error.message) } } @@ -359,6 +394,10 @@ export const getERC20Balance = async ( ) => { try { const res = await fetch(`${BASE_URL}/wallet/${signer?.address}`) + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() setErc20balanceL2(json.erc20[erc20address] ?? '0') const balance = await balanceERC20(erc20address, signer) @@ -402,6 +441,10 @@ export const getERC1155Balance = async ( try { const url = `${BASE_URL}/wallet/${signer.address}` const res = await fetch(url) + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } const json = await res.json() setErc1155balanceL2(json.erc1155[erc1155address]?.length ?? '0') const balance = await balanceERC1155(erc1155address, signer!, tokenId) @@ -431,8 +474,12 @@ export const sendRPCCommand = async (method: string, params: any[]) => { }; try { - const response = await fetch(rpcUrl, requestOptions); - const responseData = await response.json(); + const res = await fetch(rpcUrl, requestOptions); + if (!res.ok) { + console.log(res.status, res.text()) + return errorAlert(`${res.status}, ${await res.text()}`) + } + const responseData = await res.json(); console.log(responseData); } catch (error) { console.error(error) diff --git a/apps/cartesify/frontend/react-app/src/pages/Greetings.tsx b/apps/cartesify/frontend/react-app/src/pages/Greetings.tsx index b0b2356..9afbcdc 100644 --- a/apps/cartesify/frontend/react-app/src/pages/Greetings.tsx +++ b/apps/cartesify/frontend/react-app/src/pages/Greetings.tsx @@ -1,66 +1,165 @@ -'use client' -import {useState, useEffect, useCallback } from 'react' -import { useAccount } from 'wagmi' -import { useEthersSigner } from '../utils/useEtherSigner' -import { createOrUpdateRequest, getRequest } from '../cartesi/services/RestApiCalls' -import { errorAlert, successAlert } from '../utils/customAlert' +import { useState, useEffect, useCallback } from 'react'; +import { useAccount } from 'wagmi'; +import { useEthersSigner } from '../utils/useEtherSigner'; +import { createOrUpdateRequest, getRequest } from '../cartesi/services/RestApiCalls'; +import { errorAlert, successAlert } from '../utils/customAlert'; +import { + Table, + Thead, + Tbody, Tr, + Th, + Td, + TableCaption, + TableContainer +} from '@chakra-ui/react'; + export default function Greetings() { - const [loading, setLoading] = useState(false) - const [data, setData] = useState('') - const [fetching, setFetching] = useState(false) - const [message, setMessage] = useState('') - const { address } = useAccount() - const signer = useEthersSigner() - - const handleMessageChange = (e: React.ChangeEvent) => setMessage(e.target.value) + const [loading, setLoading] = useState(false); + const [listMessages, setMessageList] = useState([]); + const [fetching, setFetching] = useState(false); + const [message, setMessage] = useState(''); + const [isEdit, setEdit] = useState(false); + const [id, setId] = useState(0); + + const { address } = useAccount(); + const signer = useEthersSigner(); + + const handleMessageChange = (e: React.ChangeEvent) => setMessage(e.target.value); const sendGreeting = async () => { - try{ - if(!message) return errorAlert("Field required") - if(!address) return errorAlert("Ensure your wallet is connect") - setLoading(true) - const res = await createOrUpdateRequest(signer, "POST", "greeting", - JSON.stringify({ message})) - setLoading(false) - successAlert(res) - }catch(error){ - setLoading(false) - console.log(error) - errorAlert(error) + try { + if (!message) return errorAlert("Field required"); + if (!address) return errorAlert("Ensure your wallet is connected"); + setLoading(true); + await createOrUpdateRequest(signer, "greetings", "POST", + JSON.stringify({ message, sender: address })); + setMessage(""); + setLoading(false); + successAlert("Successfully sent!"); + await getGreetings(); + } catch (error) { + setLoading(false); + console.log(error); + errorAlert(error); + } + }; + + const updateMessage = async (id: number) => { + try { + if (!message) return errorAlert("Field required"); + if (!address) return errorAlert("Ensure your wallet is connected"); + setLoading(true); + await createOrUpdateRequest(signer, `greetings/${id}`, "PUT", JSON.stringify({ message, sender: address })); + setMessage(""); + setLoading(false); + successAlert("Successfully sent!"); + setEdit(false); + await getGreetings(); + } catch (error) { + setLoading(false); + errorAlert(error); + } + }; + + const getGreeting = useCallback(async (id: number) => { + try { + setFetching(true); + await getRequest(`greetings/${id}`); + setFetching(false); + } catch (error) { + setFetching(false); + console.log("error", error); } - } + }, []); - const getGreeting = useCallback( async () => { - try{ - setFetching(true) - await getRequest(setData, "greetings?id=1") - setFetching(false) - }catch(error){ - setFetching(false) - console.log("error", error) + const getGreetings = useCallback(async () => { + try { + setFetching(true); + const res = await getRequest("greetings"); + console.log("res", res); + console.log(JSON.parse(res!).greetings); + setMessageList(JSON.parse(res!).greetings); // Assuming res is JSON string + setFetching(false); + } catch (error) { + setFetching(false); + console.log("error", error); } - }, []) + }, []); + + console.log("listMessages", listMessages); + console.log("id", id); + useEffect(() => { + getGreetings(); + }, [getGreetings]); + return ( +
+

Welcome! Say Hello 👋

+ + + {fetching && (

Fetching data...

)} - useEffect(() =>{ - getGreeting() - },[data, getGreeting]) + {listMessages && listMessages.length === 0 ? "" : + ( +
+

Output

+ + + { + try { + await createOrUpdateRequest(signer, 'greetings', "DELETE"); + successAlert("Successfully deleted"); + await getGreetings(); + } catch (error) { + errorAlert(error); + } - return ( -
-

Welcome! Say Hello 👋

- - - {fetching ? (

Fetching data...

) : data ? ( -
-

Output

-

{data}

-
- ) :
- } -
+ }} textColor={"purple"} paddingBottom={"24px"} className='text-red-400'>Delete all messages
+ + + + + + + + + {listMessages.map((item: any, index: any) => ( + + + + + + ))} + +
S/NMessageRemove
{item.id} { + try { + setId(item.id); + setEdit(true); + setMessage(item.message); + } catch (error) { + errorAlert(error); + } + }} className='text-gray-400'>{item.message} { + try { + await createOrUpdateRequest(signer, `greetings/${item.id}`, "DELETE"); + successAlert("Successfully deleted"); + await getGreetings(); + } catch (error) { + errorAlert(error); + } + }} className='bg-red-400 rounded p-4'>🗑️
+
+
+ )} +
); }