낙천주의! sigue dando de qué hablar - [Desarrollo en Layer 2]
Antes de comenzar
Para este tutorial ocuparás NodeJs que recomiendo descargarlo en Linux via NVM , y también nececitarás Metamask u otra wallet compatible.
1. 낙천주의 아그레가! en tu 메타마스크
En este video lanzaremos en Optimism! Testnet pero también les explico cómo hacerlo en Mainnet.
낙천주의! 메인넷
Optimistic Ethereum
https://mainnet.optimism.io
10
ETH
https://optimistic.etherscan.io
낙천주의! 테스트넷
Optimism Kovan
https://kovan.optimism.io
69
ETH
https://kovan-optimistic.etherscan.io
2. 레이어 2에서 폰도스 만들기
Sigue los siguientes pasos para obtener fondos en Optimism! 테스트넷:
3. DApp 생성
엘 스마트 계약
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
contract Hello
{
string public hello = "Hola mundo!";
function setHello(string memory _hello) public
{
hello = _hello;
}
}
엘 HTML
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<input id="connect_button" type="button" value="Connect" onclick="connectWallet()" style="display: none"></input>
<p id="account_address" style="display: none"></p>
<p id="web3_message"></p>
<p id="contract_state"></p>
<input type="input" value="" id="_hello"></input>
<input type="button" value="Set Hello" onclick="_setHello()"></input>
<br>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.3.5/web3.min.js"></script>
<script type="text/javascript" src="blockchain_stuff.js"></script>
</body>
</html>
<script>
function _setHello()
{
_hello = document.getElementById("_hello").value
setHello(_hello)
}
</script>
엘 자바스크립트
blockchain_stuff.js
const NETWORK_ID = 69
const MY_CONTRACT_ADDRESS = "0xADDRESSDELCONTRATOAQUÍ"
const MY_CONTRACT_ABI_PATH = "./json_abi/MyContract.json"
var my_contract
var accounts
var web3
function metamaskReloadCallback() {
window.ethereum.on('accountsChanged', (accounts) => {
document.getElementById("web3_message").textContent="Se cambió el account, refrescando...";
window.location.reload()
})
window.ethereum.on('networkChanged', (accounts) => {
document.getElementById("web3_message").textContent="Se el network, refrescando...";
window.location.reload()
})
}
const getWeb3 = async () => {
return new Promise((resolve, reject) => {
if(document.readyState=="complete")
{
if (window.ethereum) {
const web3 = new Web3(window.ethereum)
window.location.reload()
resolve(web3)
} else {
reject("must install MetaMask")
document.getElementById("web3_message").textContent="Error: Porfavor conéctate a Metamask";
}
}else
{
window.addEventListener("load", async () => {
if (window.ethereum) {
const web3 = new Web3(window.ethereum)
resolve(web3)
} else {
reject("must install MetaMask")
document.getElementById("web3_message").textContent="Error: Please install Metamask";
}
});
}
});
};
const getContract = async (web3, address, abi_path) => {
const response = await fetch(abi_path);
const data = await response.json();
const netId = await web3.eth.net.getId();
contract = new web3.eth.Contract(
data,
address
);
return contract
}
async function loadDapp() {
metamaskReloadCallback()
document.getElementById("web3_message").textContent="Please connect to Metamask"
var awaitWeb3 = async function () {
web3 = await getWeb3()
web3.eth.net.getId((err, netId) => {
if (netId == NETWORK_ID) {
var awaitContract = async function () {
my_contract = await getContract(web3, MY_CONTRACT_ADDRESS, MY_CONTRACT_ABI_PATH)
document.getElementById("web3_message").textContent="You are connected to Metamask"
onContractInitCallback()
web3.eth.getAccounts(function(err, _accounts){
accounts = _accounts
if (err != null)
{
console.error("An error occurred: "+err)
} else if (accounts.length > 0)
{
onWalletConnectedCallback()
document.getElementById("account_address").style.display = "block"
} else
{
document.getElementById("connect_button").style.display = "block"
}
});
};
awaitContract();
} else {
document.getElementById("web3_message").textContent="Please connect to Rinkeby";
}
});
};
awaitWeb3();
}
async function connectWallet() {
await window.ethereum.request({ method: "eth_requestAccounts" })
accounts = await web3.eth.getAccounts()
onWalletConnectedCallback()
}
loadDapp()
const onContractInitCallback = async () => {
var hello = await my_contract.methods.hello().call()
var contract_state = "Hello: " + hello
document.getElementById("contract_state").textContent = contract_state;
}
const onWalletConnectedCallback = async () => {
}
//// Functions ////
const setHello = async (_hello) => {
const result = await my_contract.methods.setHello(_hello)
.send({ from: accounts[0], gas: 0, value: 0 })
.on('transactionHash', function(hash){
document.getElementById("web3_message").textContent="Executing...";
})
.on('receipt', function(receipt){
document.getElementById("web3_message").textContent="Success."; })
.catch((revertReason) => {
console.log("ERROR! Transaction reverted: " + revertReason.receipt.transactionHash)
});
}
엘 JSON ABI
Crea el archivo
./json_abi/MyContract.json
y coloca dentro el ABI genereado por Remix o por el compilador que estés usando.4. Ahora estamos listos para probar la Dapp
Primero instalamos un servidor web.
npm install -g lite-server
Ahora lo levantamos.
lite-server
브라우저에서 실행한 결과http://localhost:3000 .
감사합니다 por ver este 튜토리얼!
Sígannos en dev.to y en para todo lo relacionado al desarrollo en Blockchain en Español.
Reference
이 문제에 관하여(낙천주의! sigue dando de qué hablar - [Desarrollo en Layer 2]), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/turupawn/optimism-sigue-dando-de-que-hablar-desarrollo-en-layer-2-463c텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)