Implementé el siguiente contrato inteligente en la red de prueba Ropsten ethereum y luego intenté realizar una transacción usando el paquete @alch/alchemy-web3 npm (Sí, estoy usando la API de Alchemy), pero como puede ver, recibí una tarifa por la transacción. ¿Porqué es eso? ¿No se supone que las llamadas de función de vista pública cuestan 0 gasolina?
contrato inteligente implementado
// SPDX-Lincense-Identifier: MIT pragma solidity ^0.8.11; contract VendingMachine { address public owner; mapping(address => uint256) public donutBalances; constructor() { owner = msg.sender; donutBalances[address(this)] = 100; } function getVendingMachineBalance() public view returns (uint256) { return donutBalances[address(this)]; } function restock(uint amount) public { require(msg.sender == owner, "Only the owner can restock this machine."); donutBalances[address(this)] += amount; } function purchase(uint amount) public payable { require(msg.sender == owner, "Only the owner can restock this machine."); require(donutBalances[address(this)] >= amount, "Not enough donuts in stock to fulfill purchase request."); require(msg.value >= amount*2 ether, "You must pay at least 2 ether / donut."); donutBalances[address(this)] -= amount; donutBalances[msg.sender] += amount; } }codigo de transaccion javascript
const { API_URL, METAMASK_ACCOUNT_PRIVATE_KEY, METAMASK_ACCOUNT_PUBLIC_KEY } = process.env; const { createAlchemyWeb3 } = require("@alch/alchemy-web3"); const web3 = createAlchemyWeb3(`${API_URL}`); const contractAddress = '0xc7E286A86e4c5b8F7d52fA3F4Fe7D9DE6601b6F9' const contractAPI = new web3.eth.Contract(contract.abi, contractAddress) const nonce = await web3.eth.getTransactionCount(METAMASK_ACCOUNT_PUBLIC_KEY, 'latest'); const transaction = { to: contractAddress, // faucet address to return eth gas: 500000, nonce: nonce, data: contractAPI.methods.getVendingMachineBalance().encodeABI() // optional data field to send message or execute smart contract }; const signedTx = await web3.eth.accounts.signTransaction(transaction, METAMASK_ACCOUNT_PRIVATE_KEY) web3.eth.sendSignedTransaction(signedTx.rawTransaction, function (error, hash) { if (!error) { console.log("🎉 The hash of your transaction is: ", hash, "\n Check Alchemy's Mempool to view the status of your transaction!"); } else { console.log("❗Something went wrong while submitting your transaction:", error) } });Transacción: https://ropsten.etherscan.io/tx/0x8ce3a288072809a804adac2206dc566dfb3eb3ddba3330bcb52ca6be71963b71
Hay dos formas de interactuar con un contrato inteligente. Una transacción (lectura-escritura, costos de tarifas de gas) y una llamada (solo lectura, sin gas).
Su fragmento JS envía una transacción. Si desea invocar la función getVendingMachineBalance() usando una llamada (sin gasolina), puede usar el método .call() web3js.
const contractAPI = new web3.eth.Contract(contract.abi, contractAddress); const response = await contractAPI.methods.getVendingMachineBalance().call();