javascript (中间值).toBigNumber不是函数

ff29svar  于 2023-01-04  发布在  Java
关注(0)|答案(5)|浏览(101)

我正在学习构建你的第一个区块链教程(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文件

inn6fuwd

inn6fuwd1#

我包含了这个版本的web3,而不是v=1.0.0
https://cdn.jsdelivr.net/gh/ethereum/web3.js@0.20.6/dist/web3.min.js
这修复了问题

1tuwyuhd

1tuwyuhd2#

根本原因是因为教程使用了旧版本库,
我正在尝试相同的教程,得到了相同的问题和修复
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.更新索引. 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>

1.使用this link中的函数更新loadWeb3函数

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!');
 }

});
1.更新loadContract函数

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

1.尝试重新启动浏览器并查看

fiei3ece

fiei3ece3#

正如Mikko指出的,请使用最新的lib(v1.2)
您也可以在web3.utils. web3.utils.toBN(number)中使用“BN”作为BigNumber

fjaof16o

fjaof16o4#

我做了同样的教程,这是我如何修复我得到的所有错误

    • 应用程序. 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();
    })
})
tsm1rwdh

tsm1rwdh5#

更新web3.js cdn link为我修复了这个问题。大多数情况下,这个问题是由于包不一致造成的。

相关问题