Write your first contract with Solidity.
console.log
with Hardhat, with some restrictions.
Hello World
and delete the .deps
folder..prettierrc.json
and click the settings gear in the bottom left.contracts
, and within that folder, create a file called hello-world.sol
.UNLICENSED
. Common open source licenses, such as MIT
and GPL-3.0
are popular as well. Add your license identifier:
contract
called HelloWorld
. You should end up with:
SayHello
:
public
the most appropriate visibility specifier?
It would work, but you won’t be calling this function from within the contract, so external
is more appropriate.
You also need to specify a return type, and we’ve decided this function should return a string. You’ll learn more about this later, but in Solidity, many of the more complex types require you to specify if they are storage
or memory
. You can then have your function return a string of "Hello World!"
.
Don’t forget your semicolon. They’re mandatory in Solidity!
You should have:
Compiler
plugin. You’ve got one last warning:
Warning: Function state mutability can be restricted to pureModifiers are used to modify the behavior of a function. The
pure
modifier prevents the function from modifying, or even accessing state. While not mandatory, using these modifiers can help you and other programmers know the intention and impact of the functions you write. Your final function should be similar to:
HelloWorld
function is to expand the entry in the console. You should see a decoded output of:
Greeter
and giving it a parameter for a string memory _name
. The underscore is a common convention to mark functions and variables as internal to their scope. Doing so helps you tell the difference between a storage variable, and a memory variable that only exists within the call.
Finally, try creating a return string similar to how you might in another language with "Hello " + _name
. You should have:
TypeError: Operator + not compatible with types literal_string “Hello” and string memory.You might think that there is some sort of type casting or conversion error that could be solved by explicitly casting the string literal to string memory, or vice versa. This is a great instinct. Solidity is a very explicit language. However, you receive a similar error with
"Hello " + "world"
.
String concatenation is possible in Solidity, but it’s a bit more complicated than most languages, for good reason. Working with string costs a large amount of gas, so it’s usually better to handle this sort of processing on the front end.
returns (string memory, string memory)
Now, your function can return a tuple containing two strings!
return ("Hello", _name)
;
Deploy and test your contract. You should get a decoded output with: