Last active
August 2, 2021 20:37
-
-
Save PraneshASP/e8e5beed66e2837138f83ced1bdfb53a to your computer and use it in GitHub Desktop.
This script is used to send ethereum based push notifications.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require("dotenv").config(); | |
const Ipfs = require("nano-ipfs-store"); // Used to spin up local ipfs node | |
const ethers = require("ethers"); | |
const epnsAbi = require("../abis/epnsAbi.json"); | |
const { EPNS_PROXY_ADDRESS, PROVIDER } = require("../constants"); | |
async function newMessage(newsTitle, description) { | |
return await new Promise((resolve, reject) => { | |
const title = newsTitle; | |
const message = description; | |
const payloadTitle = newsTitle; | |
const payloadMsg = description; | |
const payload = { | |
notification: { | |
title: title, | |
body: message, | |
}, | |
data: { | |
type: "1", // Group Message | |
secret: "", | |
asub: payloadTitle, | |
amsg: payloadMsg, | |
acta: "https://medium.com", | |
aimg: "", | |
}, | |
}; | |
resolve(payload); | |
}); | |
} | |
async function sendMessage(title, description) { | |
return new Promise((resolve, reject) => { | |
let EPNS_CONTRACT_ABI = epnsAbi; | |
let EPNS_CONTRACT_ADDR = EPNS_PROXY_ADDRESS; | |
let channelPK = process.env.PRIVATE_KEY; | |
//Initialize the EPNS Contract | |
const contract = new ethers.Contract( | |
EPNS_CONTRACT_ADDR, | |
EPNS_CONTRACT_ABI, | |
PROVIDER // Ropsten Provider | |
); | |
const wallet = new ethers.Wallet(channelPK, PROVIDER); | |
contractWithSigner = contract.connect(wallet); //Connect the signer | |
newMessage(title, description).then((payload) => { | |
const jsonizedPayload = JSON.stringify(payload); | |
const ipfs = Ipfs.at("https://ipfs.infura.io:5001"); | |
// Upload the IPFS payload | |
ipfs.add(jsonizedPayload).then((ipfshash) => { | |
const notificationType = parseInt(payload.data.type); | |
const identity = notificationType + "+" + ipfshash; | |
const identityBytes = ethers.utils.toUtf8Bytes(identity); | |
const channelAddress = "YOUR_CHANNEL_ADDR"; | |
//Send the notification | |
const txPromise = contractWithSigner.sendNotification( | |
channelAddress, | |
identityBytes | |
); | |
txPromise | |
.then(async function (tx) { | |
console.log("News update sent", tx.hash); | |
resolve(tx); | |
}) | |
.catch((err) => { | |
console.log("failed"); | |
reject("Unable to complete transaction, error: %o", err); | |
}); | |
}); | |
}); | |
}); | |
} | |
module.exports = { sendMessage }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment