I'm fairly new to Ethereum smart contracts, so this might be a stupid question, but I need someone to help me out. I've set up Galanche on my machine (MacOS 11) and written a very simple currency smart contract (I don't intend to use it as an actual currency, I just want to learn about smart contracts) using truffle.
I've compiled the contract and deployed it to my Galanche blockchain successfully.
Now, I want to interact with it using web3.js. I have set up a nodejs project and installed web3. As a first test, I ran the following script:
const Web3 = require("web3");
const fs = require("fs");
const web3 = new Web3("http://192.168.178.49:7545");
const abi = JSON.parse(
fs.readFileSync("path/to/compiled/MyCoin.json").toString()
).abi;
const MyCoin = new web3.eth.Contract(
abi,
// My contract's address
"0x3265aA0A2c3ac15D0eDd67BC0fa62A446c112F98"
);
(async () => {
console.log("Starting!");
var coinCount = await MyCoin.methods
.getTotalCoins()
.call({ from: "0x2d0616BF48214513f70236D59000F1b4f395a2Fd" });
console.log("Current registered MyCoin tokens:", coinCount);
})();
The address 0x2d0616BF48214513f70236D59000F1b4f395a2Fd
is the first address displayed to me in Galanche
It works as expected and returns the default amount of coins.
Now, I want to run a method called buyMyCoin
which requires a payment. I tried running:
...
MyCoin
.methods
.buyMyCoin
.send(
{
from: '0x2d0616BF48214513f70236D59000F1b4f395a2Fd',
value: some_amount_of_wei
}
);
...
I'd expect that when I run this node.js script again, the first part would tell me that there are <n>
total coins, but it doesn't. It just returns the same value as the last time.
Am I doing something wrong with web3.js or is this an issue with my contract?
BTW: I didn't see any funds leave the address 0x2d0616BF48214513f70236D59000F1b4f395a2Fd
in Galanche, so I'm pretty sure it's not my contract...
I expect that somewhere I'd have to sign into this address using its public key, but I can't find anything about that in the web3.js docs that isn't very ambiguous...
Edit: Here's the code for my buyMyCoin method:
...
/**
* @dev Buy MyCoin
*/
function buyMyCoin() external payable {
require(msg.value > 1 gwei, "Minimum transaction is 1 gwei"); // Not very much
uint256 amount = convert(msg.value, conversionRate, true);
balances[msg.sender].owner = payable(msg.sender);
balances[msg.sender].amount += amount;
totalCoins += amount;
}
...
buyMyCoin()
function and its dependencies. There might be a requirement in the code (my guess is missingpayable
modifier or failingrequire()
) that causes the transaction to revert... And btw, it's Ganache, not Galanche :) – Petr Hejda