Last active
February 11, 2022 11:08
-
-
Save himawari2021/2066ebda1002c0088c22a556f33ad8c3 to your computer and use it in GitHub Desktop.
simple ethers.js example for accessing to smart contract on Polygon
This file contains 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
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"></script> | |
<script type="text/javascript"> | |
var myContract = null; | |
window.onload = createContract; | |
async function createContract() { | |
if(!window.ethereum) { | |
div1.innerHTML = "Metamask Not Installed!"; | |
return; | |
}else{ | |
div1.innerHTML = "Please switch network to Polygon!"; | |
} | |
const provider = new ethers.providers.Web3Provider(window.ethereum); | |
await provider.send("eth_requestAccounts", []); | |
const signer = provider.getSigner(); | |
//const cnt = "0x9A01E584faD44e1Ce139ea11Ab411923142f7C01"; | |
const cnt = "0x8b02EB24A5b1af257E22C520406C3dD9c1B55fd8"; //Polygon | |
abi = [ | |
{ | |
"inputs": [], | |
"name": "get", | |
"outputs": [ | |
{ | |
"internalType": "string", | |
"name": "", | |
"type": "string" | |
} | |
], | |
"stateMutability": "view", | |
"type": "function" | |
}, | |
{ | |
"inputs": [ | |
{ | |
"internalType": "string", | |
"name": "_message", | |
"type": "string" | |
} | |
], | |
"name": "set", | |
"outputs": [], | |
"stateMutability": "nonpayable", | |
"type": "function" | |
} | |
]; | |
//https://docs.ethers.io/v5/getting-started/#getting-started--contracts | |
myContract = new ethers.Contract(cnt, abi, signer);//状態変更する呼び出しのときはsignerを入れる | |
console.log(myContract); | |
} | |
async function fireGet() { | |
const ret = await myContract.get();//awaitで結果が返ってくるまで待機 | |
console.log(ret); | |
text1.value=ret; | |
div1.innerHTML = "get message!"; | |
} | |
function fireSet() { | |
console.log("send"); | |
const message = text1.value; | |
text1.value = ""; | |
console.log(message); | |
myContract.set(message); | |
div1.innerHTML = "sent message!"; | |
} | |
</script> | |
</head> | |
<body> | |
<h2>My First Smart Contract UI (:</h2> | |
message <input type="text" id="text1"> | |
<input type="button" value="get" onclick="fireGet()"> | |
<input type="button" value="set" onclick="fireSet()"> | |
<div id="div1"></div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment