Seguimos creando nuestra tienda blockchain con solidity, react, node y otras tecnologías. en el día de hoy nos toca programar el backend la cual será desarrollado con Node usando el framework Express, vamos a conectarnos con la blockchain de ethereum para escuchar los eventos y generar el id de pago, estaremos usando MongoDb como gestor de database. así que manos a la obra.
BD.js
const mongoose = require("mongoose");
mongoose.connect("URL_HERE_MONGODBATLAS", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const paymentSchema = new mongoose.Schema({
id: String,
itemId: String,
paid: Boolean,
});
const Payment = mongoose.model("Payment", paymentSchema);
module.exports = { Payment };
SERVER.js
const express = require("express");
const cors = require("cors");
const ethers = require("ethers");
const { Payment } = require("./db");
const PaymentProcessor = require("../build/contracts/PaymentProcessor.json");
const items = {
};
1: { id: "1", url: "http://urlToDownloadItem1" },
2: { id: "2", url: "http://urlToDownloadItem2" },
const app = express();
app.use(cors());
app.get("/api/getPaymentId/:itemId", async (req, res) => {
const id = (Math.random() * 10000).toFixed(0);
await Payment.create({
id,
itemId: req.params.itemId,
paid: false,
});
res.send({ id });
});
app.get("/api/getItemUrl/:paymentId", async (req, res) => {
const payment = await Payment.findOne({ id: req.params.paymentId });
if (payment && payment.paid) {
return res.send({ url: items[payment.itemId].url });
} else {
return res.send({ url: "" });
}
});
app.listen(4000, () => {
console.log("Server on port 4000");
});
const listenToEvents = () => {
const provider = new ethers.providers.JsonRpcProvider(
);
"https://localhost:9545"
const networkId = "5777";
const paymentProcessor = new ethers.Contract(
PaymentProcessor.networks[networkId].address,
PaymentProcessor.abi,
provider
);
paymentProcessor.on("PaymentDone", async (payer, amount, paymentId, date) => {
console.log(from ${payer} amount ${amount} paymentId ${paymentId} date ${new Date(date * 1000).toLocaleDateString()}
);
const payment = await Payment.findOne({ id: paymentId });
if (payment) {
payment.paid = true;
await payment.save();
}
});
};
listenToEvents();
#solidity #nodejs #reactjs #mongodb #expressjs #ethers
▶️ 3Speak
Hola bro tremendo contenido una lastima que no se valore como se debe, sigue asi
!1UP
Thank you for sharing your code. This is a great reference for those who are interested to implement similar features. :)
Thanks
You have received a 1UP from @thecuriousfool!
@stem-curator
And they will bring !PIZZA 🍕 The following @oneup-cartel family members will soon upvote your post:
Learn more about our delegation service to earn daily rewards. Join the family on Discord.