literate-nil/contracts.org

83 lines
1.9 KiB
Org Mode

#+title: Playing with smart contracts in org-mode
* Simple counter contract in Solidity
Nothing fancy really. A function to increment a value,
and a function to read a value.
#+name: simple_storage
#+begin_example solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
int32 private value;
function increment() public {
value += 1;
}
function get() public view returns(int32) {
return value;
}
}
#+end_example
* Compile the contract
Using off-the-shelf ~solc~, the default Solidity compiler.
We feed in the code from the previous slide.
#+begin_src bash :var contract=simple_storage
mkdir -p contract
echo "$contract" | solc -o contract/ --bin --abi --overwrite -
#+end_src
* Initialize the config and create a wallet
Because without a wallet we are powerless.
#+name: wallet
#+begin_src bash
mkdir -p ~/.config/nil/
rm -rf ~/.config/nil/*
touch ~/.config/nil/config.yaml
nil_cli config set rpc_endpoint "http://127.0.0.1:8529" 2> /dev/null
nil_cli keygen new 2> /dev/null
nil_cli wallet new 2> /dev/null
wallet=$(nil_cli wallet info 2>&1 | grep -oP 'Address: \K\w+')
echo $wallet
#+end_src
* Top-up the wallet
Gimme some tokens. Display new balance.
#+begin_src bash
nil_cli wallet top-up 100000000 2> /dev/null
nil_cli wallet balance 2>&1 | grep -oP 'balance: \K\w+'
#+end_src
* Deploy the contract
Save the address and reuse it later.
#+name: contract
#+begin_src bash
nil_cli wallet deploy ./contract/SimpleStorage.bin 2>&1 | grep -oP 'address: \K\w+'
#+end_src
* Call the contract
Notice that we use ~$address~ from the previous execution of ~nil_cli~.
#+begin_src bash :var address=contract
nil_cli wallet send-message "$address" increment --abi ./contract/SimpleStorage.abi 2>&1 | grep -oP 'Transaction hash: \K\w+'
#+end_src
#+begin_src bash :var address=contract
nil_cli contract call-readonly "$address" get --abi ./contract/SimpleStorage.abi 2>&1 | grep -oP 'Call result: \K\w+'
#+end_src