(中间值).toBigNumber 不是函数

我正在关注构建你的第一个区块链教程( https://www.youtube.com/watch?v=coQ5dg8wM2o&t=494s )。

我的 index.html 中有以下内容:

<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
    <script src="vendor/truffle-contract/dist/truffle-contract.js"></script>
    <script src="app.js"></script> 

当我打开我的 index.html 页面时,我在控制台上收到以下错误:

   (intermediate value).toBigNumber is not a function
    at truffle-contract.js:16802
    at Object.<anonymous> (truffle-contract.js:17735)

它发生在 truffle-contract.js node_modules 包代码中:

var BigNumber = (new Web3()).toBigNumber(0).constructor;

web3.min.js 文件似乎不支持“toBigNumber”功能。我在 package-lock.json 中有以下依赖项:

 "dependencies": {
        "web3": {
          "version": "0.20.6",
          "resolved": "https://registry.npmjs.org/web3/-/web3-0.20.6.tgz",
          "integrity": "sha1-PpcwauAk+yThCj11yIQwJWIhUSA=",
          "dev": true,
          "requires": {
            "bignumber.js": "git+https://github.com/frozeman/bignumber.js-nolookahead.git",
            "crypto-js": "^3.1.4",
            "utf8": "^2.1.1",
            "xhr2": "*",
            "xmlhttprequest": "*"
          }
        }
      }

不知道在哪里可以获得支持 toBigNumber 函数的正确 web3.min.js 文件

stack overflow (intermediate value).toBigNumber is not a function
原文答案

答案:

作者头像

我包含了这个版本的 web3 而不是 v=1.0.0

https://cdn.jsdelivr.net/gh/ethereum/web3.js@0.20.6/dist/web3.min.js

这解决了问题

作者头像

根本原因是因为教程使用旧版本的库,

我正在尝试相同的教程,遇到相同的问题并通过以下方式修复

1.更新包版本

     "devDependencies": {
    "bootstrap": "4.1.3",
    "chai": "^4.1.2",
    "chai-as-promised": "^7.1.1",
    "chai-bignumber": "^2.0.2",
    "lite-server": "^2.3.0",
    "nodemon": "^1.17.3",
    "truffle": "^5.4.9",
    "@truffle/contract": "4.3.33",
    "web3": "1.5.2"
  }
  1. 更新 index.html

    
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="vendor/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="vendor/web3/dist/web3.min.js"></script>
    <script src="vendor/@truffle/contract/dist/truffle-contract.min.js"></script>
    <script src="app.js"></script>

3. 更新 loadWeb3 函数,使用  [this link](https://gist.githubusercontent.com/bitpshr/076b164843f0414077164fe7fe3278d9/raw/74c33baff7d2764d970749b95580cf368f14181a/provider-enable.js)  中的函数
 window.addEventListener('load', async () => {
 // Modern dapp browsers...
 if (window.ethereum) {
     window.web3 = new Web3(ethereum);
     try {
         // Request account access if needed
         await ethereum.enable();
         // Acccounts now exposed
         web3.eth.sendTransaction({/* ... */});
     } catch (error) {
         // User denied account access...
     }
 }
 // Legacy dapp browsers...
 else if (window.web3) {
     window.web3 = new Web3(web3.currentProvider);
     // Acccounts always exposed
     web3.eth.sendTransaction({/* ... */});
 }
 // Non-dapp browsers...
 else {
     console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
 }

``` 

});

4.更新loadContract函数

App.contracts.TodoList.setProvider(new Web3.providers.HttpProvider("http://127.0.0.1:7545"));

5.尝试重启浏览器看看

作者头像

正如 Mikko 指出的,请使用最新的库(v1.2)

也可以作为 BigNumber 在 web3.utils 中使用“BN”。 web3.utils.toBN(number)

作者头像

我做了同样的教程,这就是我修复所有错误的方法

app.js


App = {
    contracts: {},
    loading: false,

    load: async () => {
        await App.loadWeb3();
        await App.loadAccounts();
        await App.loadContract();
        await App.render();
    },

      // https://medium.com/metamask/https-medium-com-metamask-breaking-change-injecting-web3-7722797916a8
    loadWeb3: async () => {
         window.addEventListener('load', async () => {
        // Modern dapp browsers...
        if (window.ethereum) {
            window.web3 = new Web3(ethereum);
            console.log("Loaded....")
            try {
                // Request account access if needed
                await ethereum.enable();
                // Acccounts now exposed
                web3.eth.sendTransaction({/* ... */});
            } catch (error) {
                // User denied account access...
            }
        }
        // Legacy dapp browsers...
        else if (window.web3) {
            window.web3 = new Web3(web3.currentProvider);
            // Acccounts always exposed
            web3.eth.sendTransaction({/* ... */});
        }
        // Non-dapp browsers...
        else {
            console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
        }
        });
    },

    loadAccounts: async () => {
        // connect to all the accounts, we want index 0 since, its the first account
        // the account we are connected to
        App.account = await ethereum.request({ method: 'eth_accounts' });
        console.log(App.account);
    },

    loadContract: async () => {
        // create a JS version of the contracts
        const todoList = await $.getJSON('TodoList.json')
        App.contracts.TodoList = TruffleContract(todoList)
        App.contracts.TodoList.setProvider(new Web3.providers.HttpProvider("http://127.0.0.1:7545"));
        // console.log(todoList);

        // Hydrate the smart contract with values from the blockchain
        App.todoList = await App.contracts.TodoList.deployed()
    },

    render: async () => {
        if (App.loading) {
            return;
        }

        // Update app loading state
        App.setLoading(true)

        // Render Account
        $('#account').html(App.account)

        // Render Tasks
        await App.renderTasks()

        // Update loading state
        App.setLoading(false)
        },

    renderTasks: async () => {
        // load all the tasks from the blockchain
        const taskCount = await App.todoList.taskCount();
        const $tackTemplate = $(".taskTemplate");

        // render each of the tasks
        for (var i = 1; i <= taskCount; i++){
            const task = await App.todoList.tasks(i);
            const task_id = task[0].toNumber();
            const task_content = task[1];
            const task_completed = task[2];

            // Create the html for the task
            const $newTaskTemplate = $tackTemplate.clone()
            $newTaskTemplate.find('.content').html(task_content)
            $newTaskTemplate.find('input')
                            .prop('name', task_id)
                            .prop('checked', task_completed)
                            .on('click', App.toggleCompleted)

            // Put the task in the correct list
            if (task_completed) {
                $('#completedTaskList').append($newTaskTemplate)
            } else {
                $('#taskList').append($newTaskTemplate)
            }

            // Show the task
            $newTaskTemplate.show()
        }

    },

    setLoading: (boolean) => {
        App.loading = boolean;
        const loader = $('#loader');
        const content = $('#content');
        if (boolean) {
            loader.show();
            content.hide();
        } else {
            loader.hide();
            content.show();
        }
    },

    createTask: async () => {
        App.setLoading(true);
        const content = $('#newTask').val();
        await App.todoList.createTask(content, { from: App.account[0] });
        window.location.reload();
    },

    toggleCompleted: async (e) => {
        App.setLoading(true)
        const taskId = e.target.name
        await App.todoList.toggleCompleted(taskId, { from: App.account[0] });
        window.location.reload()
    },

}

$(() => {
    $(window).load(() => {
        App.load();
    })
})
作者头像

这是我使用的依赖项列表:


{
  "name": "eth-todo-list",
  "version": "1.0.0",
  "description": "Blockchain Todo List Powered By Ethereum",
  "main": "truffle-config.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "dev": "lite-server",
    "test": "echo "Error: no test specified" && sexit 1"
  },
  "author": "gregory@dappuniversity.com",
  "license": "ISC",
  "devDependencies": {
    "bootstrap": "4.1.3",
    "chai": "^4.1.2",
    "chai-as-promised": "^7.1.1",
    "chai-bignumber": "^2.0.2",
    "lite-server": "^2.3.0",
    "nodemon": "^1.17.3",
    "truffle": "^5.4.9",
    "@truffle/contract": "4.3.33",
    "web3": "1.5.2"
  },
  "dependencies": {
    "web3": "^1.7.0"
  }
}