【发布时间】:2021-07-22 00:23:05
【问题描述】:
我对以太坊智能合约还很陌生,所以这可能是一个愚蠢的问题,但我需要有人帮助我。我已经在我的机器(MacOS 11)上设置了 Galanche,并使用 truffle 编写了一个非常简单的货币智能合约(我不打算将其用作实际货币,我只是想了解智能合约)。
我已经编译好合约并成功部署到我的 Galanche 区块链。
现在,我想使用 web3.js 与它进行交互。我已经建立了一个 nodejs 项目并安装了 web3。作为第一个测试,我运行了以下脚本:
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);
})();
地址0x2d0616BF48214513f70236D59000F1b4f395a2Fd是Galanche显示给我的第一个地址
它按预期工作并返回默认数量的硬币。
现在,我想运行一个名为buyMyCoin 的方法,它需要付款。我试着跑了:
...
MyCoin
.methods
.buyMyCoin
.send(
{
from: '0x2d0616BF48214513f70236D59000F1b4f395a2Fd',
value: some_amount_of_wei
}
);
...
我希望当我再次运行这个 node.js 脚本时,第一部分会告诉我总共有<n> 个硬币,但事实并非如此。它只是返回与上次相同的值。
我是在 web3.js 上做错了什么,还是我的合同有问题?
顺便说一句:我没有看到任何资金离开 Galanche 的地址 0x2d0616BF48214513f70236D59000F1b4f395a2Fd,所以我很确定这不是我的合同......
我希望在某个地方我必须使用它的公钥登录这个地址,但我在 web3.js 文档中找不到任何不是很模棱两可的东西......
编辑:这是我的 buyMyCoin 方法的代码:
...
/**
* @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;
}
...
【问题讨论】:
-
请编辑您的问题并显示 Solidity
buyMyCoin()函数及其依赖项。代码中可能有一个要求(我的猜测是缺少payable修饰符或失败require())导致事务恢复......顺便说一句,它是Ganache,而不是Galanche :) -
@PetrHejda 是的,有一个要求要求交易价值大于 1 gwei... 有没有办法检测失败的要求?顺便说一句:错误事件似乎也没有触发......
-
没有代码我看不出来。
-
@PetrHejda 我现在添加了代码
标签: ethereum smartcontracts web3 truffle web3js