Param undefined in Index.js file that is a part of Web3.js

So I’m following the cloning Rarible in 24 hours series on Youtube and came across the following error when I press buy on any NFT that is up for sale. I’ve cross-checked the code multiple times but still couldn’t manage to locate the issue. Is anyone else facing a similar problem?
Great job on that Youtube series btw! Kudos to the Moralis team!

index.js:223 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'length')
    at c.formatParam (index.js:223:30)
    at index.js:99:22
    at Array.map (<anonymous>)
    at c.encodeParameters (index.js:93:21)
    at index.js:450:20
    at Array.map (<anonymous>)
    at Object.y._encodeMethodABI (index.js:449:8)
    at Object.y._processExecuteArguments (index.js:713:39)
    at Object.y._executeMethod (index.js:732:68)
    at buyItem (main.js:308:57)

can you paste that line from index.js with number 223?
it looks like there is a variable that is undefined

Sure
This is line number 223
" if (size / 8 < param.length) { "

I think I’m not getting arguments from the previous calls

ABICoder.prototype.formatParam = function (type, param) {
    const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);
    const paramTypeBytesArray = new RegExp(/^bytes([0-9]*)\[\]$/);
    const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);
    const paramTypeNumberArray = new RegExp(/^(u?int)([0-9]*)\[\]$/);
    // Format BN to string
    if (utils.isBN(param) || utils.isBigNumber(param)) {
        return param.toString(10);
    }
    if (type.match(paramTypeBytesArray) || type.match(paramTypeNumberArray)) {
        return param.map(p => this.formatParam(type.replace('[]', ''), p));
    }
    // Format correct width for u?int[0-9]*
    let match = type.match(paramTypeNumber);
    if (match) {
        let size = parseInt(match[2] || "256");
        if (size / 8 < param.length) {   // LINE NUMBER 223
            // pad to correct bit width
            param = utils.leftPad(param, size);
        }
    }
    // Format correct length for bytes[0-9]+
    match = type.match(paramTypeBytes);
    if (match) {
        if (Buffer.isBuffer(param)) {
            param = utils.toHex(param);
        }
        // format to correct length
        let size = parseInt(match[1]);
        if (size) {
            let maxSize = size * 2;
            if (param.substring(0, 2) === '0x') {
                maxSize += 2;
            }
            if (param.length < maxSize) {
                // pad to correct length
                param = utils.rightPad(param, size * 2);
            }
        }
        // format odd-length bytes to even-length
        if (param.length % 2 === 1) {
            param = '0x0' + param.substring(2);
        }
    }
    return param;
};

this means that param is undefined at that moment, now you get back to see where from that param should be initialised with a value

Exactly!
I traced it back in the stack

encodeParameters() function is called from the below method, which then calls the above mentioned formatParam()
" return abi.encodeParameters(inputs, args).replace(‘0x’, ‘’); "

But in the below method, I think the args is initialized as empty and I don’t know the reason for that
" args = this.arguments || []; "

Btw I did not write index.js
Its a part of Web3.js

Contract.prototype._encodeMethodABI = function _encodeMethodABI() {
    var methodSignature = this._method.signature, args = this.arguments || [];
    var signature = false, paramsABI = this._parent.options.jsonInterface.filter(function (json) {
        return ((methodSignature === 'constructor' && json.type === methodSignature) ||
            ((json.signature === methodSignature || json.signature === methodSignature.replace('0x', '') || json.name === methodSignature) && json.type === 'function'));
    }).map(function (json) {
        var inputLength = (Array.isArray(json.inputs)) ? json.inputs.length : 0;
        if (inputLength !== args.length) {
            throw new Error('The number of arguments is not matching the methods required number. You need to pass ' + inputLength + ' arguments.');
        }
        if (json.type === 'function') {
            signature = json.signature;
        }
        return Array.isArray(json.inputs) ? json.inputs : [];
    }).map(function (inputs) {
        return abi.encodeParameters(inputs, args).replace('0x', '');
    })[0] || '';
    // return constructor
    if (methodSignature === 'constructor') {
        if (!this._deployData)
            throw new Error('The contract has no contract data option set. This is necessary to append the constructor parameters.');
        if (!this._deployData.startsWith('0x')) {
            this._deployData = '0x' + this._deployData;
        }
        return this._deployData + paramsABI;
    }
    // return method
    var returnValue = (signature) ? signature + paramsABI : paramsABI;
    if (!returnValue) {
        throw new Error('Couldn\'t find a matching contract method named "' + this._method.name + '".');
    }
    return returnValue;
};

ok, what is the line from the script that you wrote that generates that error?

Yes, the line that I wrote is at buyItem (main.js:308:57)
await marketplaceContract.methods.buyItem(item.uid).send({from: user.get('ethAddress'), value: item.askingPrice}); //Buying an item

After this, the execution goes to index.js

Here is my buyItem method in marketplaceContract.sol file

// Function to buy the item that is up for sale

    function buyItem(uint256 id) payable external ItemExists(id) IsForSale(id) HasTransferApproval(itemsForSale[id].tokenAddress, itemsForSale[id].tokenId){

        require(msg.value >= itemsForSale[id].askingPrice, "Not enough funds sent");
        require(msg.sender != itemsForSale[id].seller);   

        itemsForSale[id].isSold = true; //Flag the item as sold
        activeItems[itemsForSale[id].tokenAddress][itemsForSale[id].tokenId] = false;  

        // .safeTransferFrom(From, To, TokenID)

        IERC721(itemsForSale[id].tokenAddress).safeTransferFrom(itemsForSale[id].seller, msg.sender, itemsForSale[id].tokenId); // Transfering the token to the buyer's address
        itemsForSale[id].seller.transfer(msg.value);    // Transfering the funds from buyers address to the sellers address

        emit itemSold(id, msg.sender, itemsForSale[id].askingPrice);    //Item sold event is triggerd

    }

maybe is a problem with the abi that was used when initialising marketplaceContract, now you can also use Moralis.executeFunction if it seems easier

also you should check that from and value parameters have the expected value

Still getting the same error!

I triple-checked the values of " from and value ", they’re correct.
I did " truffle migrate --reset " again, and replaced the new contract addresses in main.js
Also, copy-pasted the marketplaceContractAbi from MorarableMarketContract.json to abi.js

I don’t understand where the issue is

you could try to run that code separately to see if it still gets you that error, in particular you need only the abi for that function, you could run it directly from your browser console too with Moralis.executeFunction or with web3 how it is written now

OK thanks!
I’m going to try that