Skip to content

Instantly share code, notes, and snippets.

@mgks
Created May 13, 2023 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgks/83b54745e514c974a0d2947d6c26de98 to your computer and use it in GitHub Desktop.
Save mgks/83b54745e514c974a0d2947d6c26de98 to your computer and use it in GitHub Desktop.
Simple smart contract using Solidity and then interact with it using web3.js
// Following git demonstrates the use of decentralized applications and blockchain technology using web3.js.
// Here's an example of a simple smart contract that stores and returns a message.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MessageContract {
string private message;
function setMessage(string memory newMessage) public {
message = newMessage;
}
function getMessage() public view returns (string memory) {
return message;
}
}
// We can deploy this contract to a test network like Ropsten or Rinkeby using Remix or another Solidity development tool. Then, we can use web3.js to interact with the deployed contract and set/get the message.
// Here's some example JavaScript code that uses web3.js to interact with the contract
const Web3 = require('web3');
const web3 = new Web3('https://ropsten.infura.io/v3/YOUR_INFURA_PROJECT_ID');
const abi = [ // add the contract ABI here
{
"inputs": [],
"name": "getMessage",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "string",
"name": "newMessage",
"type": "string"
}
],
"name": "setMessage",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
];
const contractAddress = '0x123...'; // add the deployed contract address here
const contract = new web3.eth.Contract(abi, contractAddress);
// set the message
contract.methods.setMessage('Hello, world!').send({ from: '0xabc...', gas: 1000000 })
.on('receipt', (receipt) => {
console.log('Transaction receipt:', receipt);
});
// get the message
contract.methods.getMessage().call({ from: '0xabc...' })
.then((message) => {
console.log('Message:', message);
});
// Ofcourse, you'll need to replace the contract address and ABI with your own values, and replace the Infura project ID and account addresses with your own as well. But this should give you an idea of how to interact with a smart contract using web3.js.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment