我正在为Dapp制作前端,因此在创建智能合约实例并设置了提供程序之后,我尝试部署合约,获取令牌余额并将其显示在网页上,但出现错误:
Cannot read property 'deployed' of undefined
在我的浏览器中。
请注意,正如我在FixedSupplyToken.json文件中看到的那样,我的FixedSupplyToken.sol已部署在测试RPC上,它具有一个地址。当时以为这是问题,但没有运气...
app.js:
// Import libraries we need.
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract'
// Import our contract artifacts and turn them into usable abstractions.
import exchange_artifacts from '../../build/contracts/Exchange.json'
import token_artifacts from '../../build/contracts/FixedSupplyToken.json'
var accounts;
var account;
var ExchangeContract = contract(exchange_artifacts);
var TokenContract = contract(token_artifacts);
window.App = {
start: function() {
//bootstrap everything
ExchangeContract = web3.setProvider(web3.currentProvider);
TokenContract = web3.setProvider(web3.currentProvider);
},
//update balance function
updateTokenBalance: function() {
var tokenInstance;
**TokenContract.deployed().then(function (instance) { // getting the Uncaught TypeError: Cannot read property 'deployed' of undefined**
tokenInstance = instance;
return tokenInstance.balanceOf.call(account);
}).then(function (value) {
var balance_element = document.getElementById("balanceTokenInToken");
balance_element.innerHTML = value.valueOf();
}).catch(function (e) {
console.log(e);
App.setStatus("Error getting balance; see log.");
});
},
即使我取消注释web3.setProvider(web3.currentProvider),我也会收到setProvider未定义的错误。
感谢您的反馈意见:)
答案 0 :(得分:1)
在Promise.all (pages Array)
函数中,您正在重新分配start
变量。
尝试更改
TokenContract
收件人:
ExchangeContract = web3.setProvider(web3.currentProvider);
TokenContract = web3.setProvider(web3.currentProvider);
根据评论进行编辑:
问题的根源是ExchangeContract.setProvider(web3.currentProvider);
TokenContract.setProvider(web3.currentProvider);
方法返回void或web3.setProvider
,因此在语句undefined
中您将TokenContract = web3.setProvider(web3.currentProvider);
分配给undefined
,因此错误。设置web3提供程序和Truffle合同提供程序是两个不同的操作。不知道TokenContract
中是否还有更多代码,但是如果由于某些原因需要显式设置提供程序,请尝试将代码更改为:
//bootstrap everything
但是,如果正确配置了Web3,则不需要第一行。我建议为此阅读本文,因为这样做的方式有所变化:https://medium.com/@awantoch/how-to-connect-web3-js-to-metamask-in-2020-fee2b2edf58a。
其要旨是:
web3.setProvider(web3.currentProvider);
ExchangeContract.setProvider(web3.currentProvider);
TokenContract.setProvider(web3.currentProvider);
答案 1 :(得分:0)
此行:
import token_artifacts from '../../build/contracts/FixedSupplyToken.json'
我猜您本地的Web服务器植根于HTML页面所在的位置。因此,将内容从Web服务器根目录(例如,从..
文件夹中)拉出的任何尝试都将被拒绝。
使用正在运行的F12工具重新加载页面,以显示网络流量。我怀疑当页面尝试执行GET ../../build/contracts/FixedSupplyToken.json
因此,token_artifacts
未定义,因此创建的所有其他内容也未定义。
快速的技巧是将FixedSupplyToken.json移至您的Web根目录并适当地调整导入语句。
我的python网络服务器遇到的另一个问题是,即使将json移到了网络根目录之后,我正在运行的python -m http.server
事情还是在Content-Type
标头中返回了mime类型被javascript导入程序拒绝。我所做的快速修改只是将json声明粘贴到.js文件中,并为其分配了变量,例如:
window.FizzBuzzContract = // added this line
{
"contractName": "FizzBuzz",
"abi": [...