Ethereum: Access to variables of an Ethereum Smart Treaty of JavaScript
In this article, we will examine how you can access the variables of an Ethereum -Smart contract. We focus on access to variables with their names.
Set up an intelligent contract
Before we deal with the solution, we create a simple intelligent contract in solidity:
`Solidity
// SPDX-Licens-Idifier: with
Pragma solidity ^0.8.0;
Simply contract {
String32 public message;
Function simple () {
Message = “Hello world!”;
}
}
`
Access to variables with their names
In order to be able to access variables of an intelligent contract with JavaScript, we can use the “Solc” compiler to compile our solidity code into an Ethereum-compatible smart contract. For example:
`Bash
NPX SOLC -L Solidity -0.8.17 Simple.sol
After compiling, we can write JavaScript code that interacts with the contract:
`JavaScript
Const contract = demands (‘./ simple.json’);
Asynchrical function main () {
attempt {
Const contract = new contract ();
// access to variables with the name with the property “Contract.Name”
console.log (contract.message);
// Use the variable contract.message
directly (not recommended)
console.log (contract.message.value);
} Catch (error) {
console.error (error);
}
}
`
In this example, we create the contract and create a new instance in JavaScript. We then use the “Contract.Name” property to access the news variable with your name.
Note:
The Contract.Name 'property returns the value assigned with the name of the contract (e.g." simply "). This does not correspond to access to variables directly using their names, which means that the actual address of the contract or the use of another method such as Web3.js.
Best Practice
It is possible to access intelligent contract variables in JavaScript with names, but it is generally recommended to use the "Web3" library and its integrated methods for interaction with Ethereum Smart Contracts. The "Web3 library” offers a safer and more convenient way to work with intelligent contracts, especially when using Web3.js.
To start with web3
, you can install it via NPM:
`Bash
NPM install Web3
Then import the “Web3class" into your JavaScript code:
JavaScript
Const Web3 = demands (‘Web3’);
`
With “Web3” you can use your integrated methods for interaction with intelligent contracts, e.g. B. the contract address and sending transactions. For example:
`JavaScript
Const web3 = new web3 (new web3.providers.httpprovider (‘
// access to variables with the name with the property “Contract.Name”
console.log (contract.message);
// Use the “Contract.Address” property to receive the address of the contract
console.log (contract.Address);
`
In summary, it can be said that it can access intelligent contract variables in JavaScript with names, “Web3.Js” offers a safer and more convenient way to work with Ethereum -Smart Contracts.
Leave a Reply