bootcamp 1 - solidity

icon picker
seção 3

agora temos um aplicativo web completo que pode conversar com a blockchain
no final das aulas, queremos:
permitir que usuários enviem uma mensagem junto com o tchauzinho
ter dados salvos de alguma forma na blockchain
mostrar dados no site: pessoas que mandaram tchau e suas mensagens

código de contrato inteligente atualizado → WavePortal.sol

antes

contract WavePortal {
uint256 totalWaves;

constructor() {
console.log("smart? since when do lawyers create anything smart?");
}

function wave() public {
totalWaves += 1;
console.log("%s sent a hug!", msg.sender);
console.log("the difficulty to send a hug was this huge = ", block.difficulty);
}

function getTotalWaves() public view returns (uint256) {
console.log("total %d hug(s)!", totalWaves);
return totalWaves;
}
}

depois

contract WavePortal {
uint256 totalWaves;

//use o Google para entender o que são eventos em Solidity!
event NewWave(address indexed from, uint256 timestamp, string message);

//struct = tipo de dado customizado
//customizo o que quero armazenar dentro dele
struct Wave {
address waver; // Endereço do usuário que deu tchauzinho
string message; // Mensagem que o usuário envio
uint256 timestamp; // Data/hora de quando o usuário tchauzinhou.
}

//variável para armazenar array de structs, todos os tchauzinhos recebidos
Wave[] waves;

constructor() {
console.log("EU SOU UM CONTRATO INTELIGENTE. POG.");
}

//função do tchauzinho agora requer string chamada _message
//essa é a mensagem que o usuário enviou pelo frontend!
function wave(string memory _message) public {
totalWaves += 1;
console.log("%s tchauzinhou com a mensagem %s", msg.sender, _message);

//aqui é onde armazeno o tchauzinho no array
waves.push(Wave(msg.sender, _message, block.timestamp));

//use o Google para tentar entender o que tem de novo aqui! haha
emit NewWave(msg.sender, block.timestamp, _message);
}

//função que retorna os tchauzinhos
function getAllWaves() public view returns (Wave[] memory) {
return waves;
}

function getTotalWaves() public view returns (uint256) {
//opcional: adicione esta linha se você quer ver o contrato imprimir o valor!
console.log("Temos %d tchauzinhos no total!", totalWaves);
return totalWaves;
}
}

testando

sempre que alteramos nosso contrato, queremos alterar o run.js para testar a nova funcionalidade
é assim que sabemos que está funcionando como queremos

run.js atualizado

const main = async () => {
const waveContractFactory = await hre.ethers.getContractFactory("WavePortal");
const waveContract = await waveContractFactory.deploy();
await waveContract.deployed();
console.log("Endereço do contrato:", waveContract.address);

let waveCount;
waveCount = await waveContract.getTotalWaves();
console.log(waveCount.toNumber());

//deixe-me enviar alguns tchauzinhos!
let waveTxn = await waveContract.wave("Uma mensagem!");
await waveTxn.wait(); // aguarda a transação ser minerada

const [_, randomPerson] = await hre.ethers.getSigners();
waveTxn = await waveContract.connect(randomPerson).wave("Outra mensagem!");
await waveTxn.wait(); // aguarda a transação ser minerada

let allWaves = await waveContract.getAllWaves();
console.log(allWaves);
};

const runMain = async () => {
try {
await main();
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.