4.11 Twitter Dapp 02 Javascript

閱讀時間約 17 分鐘

Overview

1. Request Wallet Connection from Metamask get account function

get account function

2. Set your smart contract address

injected provider address

3. connect to the contract using web3

connect app and smart contract with web3.js

4. call the contract createTweet method in order to crete the actual TWEET

call the function to create the actual tweet

waiting for the function to complete completely

5. call the function getAllTweets from smart contract to get all the tweets

.send - I'm giving you this data

.call - give it to me



6. Call the displayTweets function with address as input

7. Uncomment the displayTweets function! PRETTY EASY 🔥

8. call the likeTweet function from smart contract


index.js

import contractABI from "./abi.json";

// 2️⃣ Set your smart contract address 👇
const contractAddress = "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4";

let web3 = new Web3(window.ethereum);
// 3️⃣ connect to the contract using web3
// HINT: https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#new-contract
// let contract = YOUR CODE
let contract = new web3.eth.Contract(contractABI, contractAddress);


async function connectWallet() {
if (window.ethereum) {
// 1️⃣ Request Wallet Connection from Metamask
// ANSWER can be found here: https://docs.metamask.io/wallet/get-started/set-up-dev-environment/
// const accounts = YOUR CODE
const accounts = await window.ethereum
.request({method: "eth_requestAccounts"})
.catch((err) => {
if (err.code === 4001) {
console.log("Please connect to MetaMask.");
} else {
console.error(err);
}
});

console.log(accounts);

setConnected(accounts[0]);
} else {
console.error("No web3 provider detected");
document.getElementById("connectMessage").innerText =
"No web3 provider detected. Please install MetaMask.";
}
}

async function createTweet(content) {
const accounts = await web3.eth.getAccounts();
try {
// 4️⃣ call the contract createTweet method in order to crete the actual TWEET
// HINT: https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#methods-mymethod-send
// use the "await" feature to wait for the function to finish execution
// what is await? https://javascript.info/async-await
await contract.methods.createTweet(content).send({from: accounts[0]});


// 7️⃣ Uncomment the displayTweets function! PRETTY EASY 🔥
// GOAL: reload tweets after creating a new tweet
displayTweets(accounts[0]);
} catch (error) {
console.error("User rejected request:", error);
}
}

async function displayTweets(userAddress) {
const tweetsContainer = document.getElementById("tweetsContainer");
const tempTweets = [];
tweetsContainer.innerHTML = "";
// 5️⃣ call the function getAllTweets from smart contract to get all the tweets
// HINT: https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#methods-mymethod-call
// tempTweets = await YOUR CODE
tempTweets = await contract.methods.getAllTweets(userAddress).call();

// we do this so we can sort the tweets by timestamp
const tweets = [...tempTweets];
tweets.sort((a, b) => b.timestamp - a.timestamp);
for (let i = 0; i < tweets.length; i++) {
const tweetElement = document.createElement("div");
tweetElement.className = "tweet";

const userIcon = document.createElement("img");
userIcon.className = "user-icon";
userIcon.src = `https://avatars.dicebear.com/api/human/${tweets[i].author}.svg`;
userIcon.alt = "User Icon";

tweetElement.appendChild(userIcon);

const tweetInner = document.createElement("div");
tweetInner.className = "tweet-inner";

tweetInner.innerHTML += `
<div class="author">${shortAddress(tweets[i].author)}</div>
<div class="content">${tweets[i].content}</div>
`;

const likeButton = document.createElement("button");
likeButton.className = "like-button";
likeButton.innerHTML = `
<i class="far fa-heart"></i>
<span class="likes-count">${tweets[i].likes}</span>
`;
likeButton.setAttribute("data-id", tweets[i].id);
likeButton.setAttribute("data-author", tweets[i].author);

addLikeButtonListener(
likeButton,
userAddress,
tweets[i].id,
tweets[i].author
);
tweetInner.appendChild(likeButton);
tweetElement.appendChild(tweetInner);

tweetsContainer.appendChild(tweetElement);
}
}

function addLikeButtonListener(likeButton, address, id, author) {
likeButton.addEventListener("click", async (e) => {
e.preventDefault();

e.currentTarget.innerHTML = '<div class="spinner"></div>';
e.currentTarget.disabled = true;
try {
await likeTweet(author, id);
displayTweets(address);
} catch (error) {
console.error("Error liking tweet:", error);
}
});
}

function shortAddress(address, startLength = 6, endLength = 4) {
return `${address.slice(0, startLength)}...${address.slice(-endLength)}`;
}

async function likeTweet(author, id) {
try {
// 8️⃣ call the likeTweet function from smart contract
// INPUT: author and id
// GOAL: Save the like in the smart contract
// HINT: don't forget to use await 😉 👇
await contract.methods.likeTweet(author, id).send({from: accounts[0 ]})
} catch (error) {
console.error("User rejected request:", error);
}
}

function setConnected(address) {
document.getElementById("userAddress").innerText =
"Connected: " + shortAddress(address);
document.getElementById("connectMessage").style.display = "none";
document.getElementById("tweetForm").style.display = "block";

// 6️⃣ Call the displayTweets function with address as input
// This is the function in the javascript code, not smart contract 😉
// GOAL: display all tweets after connecting to metamask
displayTweets(address);
}

document
.getElementById("connectWalletBtn")
.addEventListener("click", connectWallet);

document.getElementById("tweetForm").addEventListener("submit", async (e) => {
e.preventDefault();
const content = document.getElementById("tweetContent").value;
const tweetSubmitButton = document.getElementById("tweetSubmitBtn");
tweetSubmitButton.innerHTML = '<div class="spinner"></div>';
tweetSubmitButton.disabled = true;
try {
await createTweet(content);
} catch (error) {
console.error("Error sending tweet:", error);
} finally {
// Restore the original button text
tweetSubmitButton.innerHTML = "Tweet";
tweetSubmitButton.disabled = false;
}
});

abi.json

just like a IKEA instruction manual to check the information when you get lost



[Reference]

  1. code sandbox
  2. Ultimate Solidity Smart Contract Course - For Complete Beginners
  3. Wallet connection from Metamask document
  4. web3.ethContract
    尋大神腳印, 亦步亦趨。
    留言0
    查看全部
    發表第一個留言支持創作者!
    4.4
    閱讀時間約 7 分鐘
    4.5
    閱讀時間約 1 分鐘
    KryptoCamp ERC20教學
    閱讀時間約 10 分鐘
    什麼是constant variables?
    閱讀時間約 2 分鐘
    Laura 重點專案實作
    閱讀時間約 2 分鐘
    你可能也想看
    Twitter複製品的興衰在2022年底伊隆·馬斯克收購Twitter之後,社交媒體宇宙見證了許多平台湧入,試圖成為微博愛好者的下一個首選平台。其中包括Post.News、T2(也被稱為Pebble)和Spoutible等,每個平台都有它們獨特的優勢,然而最近的發展顯示,這些新興平台的環境正在發生重大變化。
    Thumbnail
    avatar
    呷新聞 Eat News
    2024-04-24
    Twitter Node 測試 https://x.com/i/web/status/1780213284769337813
    avatar
    kuanting
    2024-04-18
    【Twitter轉變為「X」】馬斯克的新願景與挑戰Elon Musk,這位Tesla的創辦人,一直以其大膽的創新和不懼挑戰的態度引人注目。去年,他以440億美元的價格收購了Twitter,並立即進行了一系列影響深遠的改革。最近,他再次引起了全球的關注,宣布將Twitter改名為「X」,並將11年來的經典藍鳥標誌替換為黑白二色的「X」新標誌。
    Thumbnail
    avatar
    Digiworld
    2023-10-21
    Twitter小鳥即將走入歷史!部分歐美博物館準備納入歷史資料知名社群媒體Twitter的經典小藍鳥標誌即將走入歷史!
    Thumbnail
    avatar
    博物館吧The Museum Bar
    2023-07-24
    Twitter 開源推薦演算法,從中了解社群媒體推送邏輯Musk 接手Twitter後的一大工程,就是要把推特的演算法開源,讓Twitter成為更公開透明的社群媒體,並能讓大眾檢視、糾錯。 當然Musk也知道風險就是更透明的演算法,會讓更多人更容易針對推薦算法優化甚至濫用。但這會是一個動態的過程,馬斯克覺得試誤的價值是很高的。
    Thumbnail
    avatar
    IEObserve 國際經濟觀察
    2023-04-01
    Twitter 首席執行長伊隆馬斯克將興趣從加密貨幣轉向人工智能https://www.zeebiz.com/technology/news-twitter-ceo-elon-musk-switches-interest-from-cryptocurrency-to-artificial-intelligence-ai-224591 狗狗幣中文社群的群友 大家安
    Thumbnail
    avatar
    狗狗幣中文社群之新聞台
    2023-03-06
    Twitter 裁員名單包括曾曬照睡辦公室產品經理 Esther Crawford狗狗幣中文社群的群友 大家安安 今天是2023年2月28日 星期二 我是埋料犬犬的智慧孫女 安妮亞 這裡是狗狗幣中文社群之新聞台 今天要導讀的新聞來自於 Yahoo新聞 文章發表於台灣時間2023年2月27日 新聞重點是 Twitter 裁員名單包括曾曬照睡辦公室產品經理 Esther Crawfo
    Thumbnail
    avatar
    狗狗幣中文社群之新聞台
    2023-02-28
    Twitter 想到一個妙招,同時提高安全跟獲利狗狗幣中文社群的群友 大家午安 今天是2023年2月19日 星期日 我是埋料犬犬的智慧孫女 安妮亞 這裡是狗狗幣中文社群之新聞台 本頻道除了狗狗幣新聞以外 也會關注狗狗幣教父 Elon Musk 主導經營的推特公司,並提供第一手最新的資訊給大家。 今天要導讀的新聞來自於 technews 文章發表於
    Thumbnail
    avatar
    狗狗幣中文社群之新聞台
    2023-02-19
    "Twitter deal temporarily on hold",馬斯克有何盤算?(之二)馬斯克大動作的發言,也引來許多質疑。 第一,馬斯克在簽約以前,並未做盡職調查,在向主管機關的申報文件中,也明確表示「不以盡職調查完成」為先決條件,現在怎可出爾反爾?
    Thumbnail
    avatar
    Chiaheng Seetoo
    2022-05-22
    "Twitter deal temporarily on hold”,馬斯克有何盤算?(之一)2022年5月13日星期五,馬斯克在美東時間清晨五點多,發了一條新推。依據他的說法,收購推特一案「暫緩」,直到推特方面能夠提出更多證據支持「不到5%的使用者是假帳號或垃圾推文帳號」為止。這條推文一出,市場大嘩,馬斯克過了兩個小時之後又趕快補上一條推文說:仍然承諾會完成收購。
    Thumbnail
    avatar
    Chiaheng Seetoo
    2022-05-22