Issues with Ethers Utiility fuction

I built a smart contract and I am trying to test it.

It successfully deploys but not all function works(event emmitter trigger problems) , for example the issueCertificate fuction.

I had to write a debug script to test where the issue is from and then i figured it was from the ethers.utility.id method, i even went further to explicity test the utils Id.

I get this error from my debug.js when i run npx hardhat run scripts/debug.js

Error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>TypeError: Cannot read properties of undefined (reading 'id')
at main (/Users/MASTERS/ACV/scripts/debug.js:22:38)
</code>
<code>TypeError: Cannot read properties of undefined (reading 'id') at main (/Users/MASTERS/ACV/scripts/debug.js:22:38) </code>
TypeError: Cannot read properties of undefined (reading 'id')
    at main (/Users/MASTERS/ACV/scripts/debug.js:22:38)

I get this error from my testUtilsId.js when i run node scripts/testUtilsId.js
Error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>(base) ACV % node scripts/testUtilsId.js
TypeError: Cannot read properties of undefined (reading 'id')
at testUtilsId (/Users/MASTERS/ACV/scripts/testUtilsId.js:6:43)
at Object.<anonymous> (/Users/MASTERS/ACV/scripts/testUtilsId.js:15:1)
at Module._compile (node:internal/modules/cjs/loader:1364:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1422:10)
at Module.load (node:internal/modules/cjs/loader:1203:32)
at Module._load (node:internal/modules/cjs/loader:1019:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:128:12)
at node:internal/main/run_main_module:28:49
</code>
<code>(base) ACV % node scripts/testUtilsId.js TypeError: Cannot read properties of undefined (reading 'id') at testUtilsId (/Users/MASTERS/ACV/scripts/testUtilsId.js:6:43) at Object.<anonymous> (/Users/MASTERS/ACV/scripts/testUtilsId.js:15:1) at Module._compile (node:internal/modules/cjs/loader:1364:14) at Module._extensions..js (node:internal/modules/cjs/loader:1422:10) at Module.load (node:internal/modules/cjs/loader:1203:32) at Module._load (node:internal/modules/cjs/loader:1019:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:128:12) at node:internal/main/run_main_module:28:49 </code>
(base) ACV % node scripts/testUtilsId.js     

TypeError: Cannot read properties of undefined (reading 'id')
    at testUtilsId (/Users/MASTERS/ACV/scripts/testUtilsId.js:6:43)
    at Object.<anonymous> (/Users/MASTERS/ACV/scripts/testUtilsId.js:15:1)
    at Module._compile (node:internal/modules/cjs/loader:1364:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1422:10)
    at Module.load (node:internal/modules/cjs/loader:1203:32)
    at Module._load (node:internal/modules/cjs/loader:1019:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:128:12)
    at node:internal/main/run_main_module:28:49

Below is the code of the smartcontract.sol, the debug.js and the testUtilsId.js

CertificateManagement.sol:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract CertificateManagement {
// Struct to store certificate information
struct Certificate {
uint256 id;
string studentName;
string course;
uint256 issueDate;
bool isValid;
string issuer;
}
// Mapping from certificate ID to certificate details
mapping(uint256 => Certificate) public certificates;
// Mapping from an address to a boolean indicating if it is authorized to issue and revoke certificates
mapping(address => bool) public authorizedIssuers;
// Event emitted when a certificate is issued
event CertificateIssued(uint256 indexed certificateID, string studentName, string issuer);
// Event emitted when a certificate is revoked
event CertificateRevoked(uint256 indexed certificateID);
// Modifier to check if the caller is an authorized issuer
modifier onlyAuthorized() {
require(authorizedIssuers[msg.sender], "Caller is not authorized");
_;
}
constructor() {
// The deployer of the contract is the initial authorized issuer
authorizedIssuers[msg.sender] = true;
}
// Function to authorize a new issuer
function addIssuer(address issuer) external onlyAuthorized {
authorizedIssuers[issuer] = true;
}
// Function to revoke issuer rights
function removeIssuer(address issuer) external onlyAuthorized {
authorizedIssuers[issuer] = false;
}
// Function to issue a new certificate
function issueCertificate(string memory studentName, string memory course, string memory issuer) public onlyAuthorized returns (uint256) {
uint256 newCertificateID = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, studentName, course)));
certificates[newCertificateID] = Certificate(newCertificateID, studentName, course, block.timestamp, true, issuer);
emit CertificateIssued(newCertificateID, studentName, issuer); // Ensure this line is correct
return newCertificateID;
}
// Function to revoke a certificate
function revokeCertificate(uint256 certificateID) public onlyAuthorized {
require(certificates[certificateID].isValid, "Certificate already revoked");
certificates[certificateID].isValid = false;
emit CertificateRevoked(certificateID);
}
// Function to verify the validity of a certificate
function verifyCertificate(uint256 certificateID) public view returns (bool) {
return certificates[certificateID].isValid;
}
}
</code>
<code>// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract CertificateManagement { // Struct to store certificate information struct Certificate { uint256 id; string studentName; string course; uint256 issueDate; bool isValid; string issuer; } // Mapping from certificate ID to certificate details mapping(uint256 => Certificate) public certificates; // Mapping from an address to a boolean indicating if it is authorized to issue and revoke certificates mapping(address => bool) public authorizedIssuers; // Event emitted when a certificate is issued event CertificateIssued(uint256 indexed certificateID, string studentName, string issuer); // Event emitted when a certificate is revoked event CertificateRevoked(uint256 indexed certificateID); // Modifier to check if the caller is an authorized issuer modifier onlyAuthorized() { require(authorizedIssuers[msg.sender], "Caller is not authorized"); _; } constructor() { // The deployer of the contract is the initial authorized issuer authorizedIssuers[msg.sender] = true; } // Function to authorize a new issuer function addIssuer(address issuer) external onlyAuthorized { authorizedIssuers[issuer] = true; } // Function to revoke issuer rights function removeIssuer(address issuer) external onlyAuthorized { authorizedIssuers[issuer] = false; } // Function to issue a new certificate function issueCertificate(string memory studentName, string memory course, string memory issuer) public onlyAuthorized returns (uint256) { uint256 newCertificateID = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, studentName, course))); certificates[newCertificateID] = Certificate(newCertificateID, studentName, course, block.timestamp, true, issuer); emit CertificateIssued(newCertificateID, studentName, issuer); // Ensure this line is correct return newCertificateID; } // Function to revoke a certificate function revokeCertificate(uint256 certificateID) public onlyAuthorized { require(certificates[certificateID].isValid, "Certificate already revoked"); certificates[certificateID].isValid = false; emit CertificateRevoked(certificateID); } // Function to verify the validity of a certificate function verifyCertificate(uint256 certificateID) public view returns (bool) { return certificates[certificateID].isValid; } } </code>
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract CertificateManagement {
    // Struct to store certificate information
    struct Certificate {
        uint256 id;
        string studentName;
        string course;
        uint256 issueDate;
        bool isValid;
        string issuer;
    }

    // Mapping from certificate ID to certificate details
    mapping(uint256 => Certificate) public certificates;
    // Mapping from an address to a boolean indicating if it is authorized to issue and revoke certificates
    mapping(address => bool) public authorizedIssuers;
    // Event emitted when a certificate is issued
    event CertificateIssued(uint256 indexed certificateID, string studentName, string issuer);
    // Event emitted when a certificate is revoked
    event CertificateRevoked(uint256 indexed certificateID);

    // Modifier to check if the caller is an authorized issuer
    modifier onlyAuthorized() {
        require(authorizedIssuers[msg.sender], "Caller is not authorized");
        _;
    }

    constructor() {
        // The deployer of the contract is the initial authorized issuer
        authorizedIssuers[msg.sender] = true;
    }

    // Function to authorize a new issuer
    function addIssuer(address issuer) external onlyAuthorized {
        authorizedIssuers[issuer] = true;
    }

    // Function to revoke issuer rights
    function removeIssuer(address issuer) external onlyAuthorized {
        authorizedIssuers[issuer] = false;
    }

    // Function to issue a new certificate
    function issueCertificate(string memory studentName, string memory course, string memory issuer) public onlyAuthorized returns (uint256) {
        uint256 newCertificateID = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, studentName, course)));
        certificates[newCertificateID] = Certificate(newCertificateID, studentName, course, block.timestamp, true, issuer);
        emit CertificateIssued(newCertificateID, studentName, issuer); // Ensure this line is correct
        return newCertificateID;
    }

    // Function to revoke a certificate
    function revokeCertificate(uint256 certificateID) public onlyAuthorized {
        require(certificates[certificateID].isValid, "Certificate already revoked");
        certificates[certificateID].isValid = false;
        emit CertificateRevoked(certificateID);
    }

    // Function to verify the validity of a certificate
    function verifyCertificate(uint256 certificateID) public view returns (bool) {
        return certificates[certificateID].isValid;
    }
}

debug.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
require("@nomicfoundation/hardhat-toolbox");
const { ethers } = require("hardhat");
const utils = ethers.utils;
async function main() {
const [deployer] = await ethers.getSigners();
const CertificateManagement = await ethers.getContractFactory("CertificateManagement");
const certManagement = await CertificateManagement.deploy();
await certManagement.waitForDeployment();
console.log("CertificateManagement deployed to:", await certManagement.getAddress());
await certManagement.addIssuer(deployer.address);
const tx = await certManagement.issueCertificate("John Doe", "Blockchain 101", "University");
const receipt = await tx.wait();
console.log("Transaction Receipt:", receipt);
const logs = receipt.logs;
console.log("Transaction Logs:", logs);
if (logs.length > 0) {
// Calculate the event signature
const eventSignature = utils.id("CertificateIssued(uint256,string,string)");
console.log("Event Signature:", eventSignature);
// Log each topic and data for inspection
logs.forEach((log, index) => {
console.log(`Log ${index} Address:`, log.address);
console.log(`Log ${index} Topics:`, log.topics);
console.log(`Log ${index} Data:`, log.data);
});
// Find the log corresponding to the event
const event = logs.find(log => log.topics[0] === eventSignature);
if (event) {
console.log("Event found:", event);
// The first topic is the event signature, and the second topic is the indexed parameter (certificateID)
const certificateID = event.topics[1];
// Decode the data part (non-indexed parameters: studentName and issuer)
const decodedData = utils.defaultAbiCoder.decode(
["string", "string"],
event.data
);
const studentName = decodedData[0];
const issuer = decodedData[1];
console.log("Issued Certificate ID:", certificateID);
console.log("Student Name:", studentName);
console.log("Issuer:", issuer);
} else {
console.log("CertificateIssued event not found in the transaction receipt.");
}
} else {
console.log("No logs found in the transaction receipt.");
}
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
</code>
<code> require("@nomicfoundation/hardhat-toolbox"); const { ethers } = require("hardhat"); const utils = ethers.utils; async function main() { const [deployer] = await ethers.getSigners(); const CertificateManagement = await ethers.getContractFactory("CertificateManagement"); const certManagement = await CertificateManagement.deploy(); await certManagement.waitForDeployment(); console.log("CertificateManagement deployed to:", await certManagement.getAddress()); await certManagement.addIssuer(deployer.address); const tx = await certManagement.issueCertificate("John Doe", "Blockchain 101", "University"); const receipt = await tx.wait(); console.log("Transaction Receipt:", receipt); const logs = receipt.logs; console.log("Transaction Logs:", logs); if (logs.length > 0) { // Calculate the event signature const eventSignature = utils.id("CertificateIssued(uint256,string,string)"); console.log("Event Signature:", eventSignature); // Log each topic and data for inspection logs.forEach((log, index) => { console.log(`Log ${index} Address:`, log.address); console.log(`Log ${index} Topics:`, log.topics); console.log(`Log ${index} Data:`, log.data); }); // Find the log corresponding to the event const event = logs.find(log => log.topics[0] === eventSignature); if (event) { console.log("Event found:", event); // The first topic is the event signature, and the second topic is the indexed parameter (certificateID) const certificateID = event.topics[1]; // Decode the data part (non-indexed parameters: studentName and issuer) const decodedData = utils.defaultAbiCoder.decode( ["string", "string"], event.data ); const studentName = decodedData[0]; const issuer = decodedData[1]; console.log("Issued Certificate ID:", certificateID); console.log("Student Name:", studentName); console.log("Issuer:", issuer); } else { console.log("CertificateIssued event not found in the transaction receipt."); } } else { console.log("No logs found in the transaction receipt."); } } main().catch((error) => { console.error(error); process.exitCode = 1; }); </code>

require("@nomicfoundation/hardhat-toolbox");
const { ethers } = require("hardhat");
const utils = ethers.utils;

async function main() {
    const [deployer] = await ethers.getSigners();
    const CertificateManagement = await ethers.getContractFactory("CertificateManagement");
    const certManagement = await CertificateManagement.deploy();
    await certManagement.waitForDeployment();
    console.log("CertificateManagement deployed to:", await certManagement.getAddress());

    await certManagement.addIssuer(deployer.address);

    const tx = await certManagement.issueCertificate("John Doe", "Blockchain 101", "University");
    const receipt = await tx.wait();
    console.log("Transaction Receipt:", receipt);

    const logs = receipt.logs;
    console.log("Transaction Logs:", logs);

    if (logs.length > 0) {
        // Calculate the event signature
        const eventSignature = utils.id("CertificateIssued(uint256,string,string)");
        console.log("Event Signature:", eventSignature);
        
        // Log each topic and data for inspection
        logs.forEach((log, index) => {
            console.log(`Log ${index} Address:`, log.address);
            console.log(`Log ${index} Topics:`, log.topics);
            console.log(`Log ${index} Data:`, log.data);
        });

        // Find the log corresponding to the event
        const event = logs.find(log => log.topics[0] === eventSignature);
        if (event) {
            console.log("Event found:", event);
            // The first topic is the event signature, and the second topic is the indexed parameter (certificateID)
            const certificateID = event.topics[1];
            
            // Decode the data part (non-indexed parameters: studentName and issuer)
            const decodedData = utils.defaultAbiCoder.decode(
                ["string", "string"],
                event.data
            );
            const studentName = decodedData[0];
            const issuer = decodedData[1];
            
            console.log("Issued Certificate ID:", certificateID);
            console.log("Student Name:", studentName);
            console.log("Issuer:", issuer);
        } else {
            console.log("CertificateIssued event not found in the transaction receipt.");
        }
    } else {
        console.log("No logs found in the transaction receipt.");
    }
}

main().catch((error) => {
    console.error(error);
    process.exitCode = 1;
});

testUtilsId.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const { ethers } = require("hardhat");
async function testUtilsId() {
// Random string
const randomString = "Hello World";
const randomStringHash = ethers.utils.id(randomString);
console.log(`Hash of "${randomString}": ${randomStringHash}`);
// Event signature
const eventSignatureString = "CertificateIssued(uint256,string,string)";
const eventSignatureHash = ethers.utils.id(eventSignatureString);
console.log(`Hash of "${eventSignatureString}": ${eventSignatureHash}`);
}
testUtilsId().catch((error) => {
console.error(error);
process.exitCode = 1;
});
</code>
<code>const { ethers } = require("hardhat"); async function testUtilsId() { // Random string const randomString = "Hello World"; const randomStringHash = ethers.utils.id(randomString); console.log(`Hash of "${randomString}": ${randomStringHash}`); // Event signature const eventSignatureString = "CertificateIssued(uint256,string,string)"; const eventSignatureHash = ethers.utils.id(eventSignatureString); console.log(`Hash of "${eventSignatureString}": ${eventSignatureHash}`); } testUtilsId().catch((error) => { console.error(error); process.exitCode = 1; }); </code>
const { ethers } = require("hardhat");

async function testUtilsId() {
    // Random string
    const randomString = "Hello World";
    const randomStringHash = ethers.utils.id(randomString);
    console.log(`Hash of "${randomString}": ${randomStringHash}`);

    // Event signature
    const eventSignatureString = "CertificateIssued(uint256,string,string)";
    const eventSignatureHash = ethers.utils.id(eventSignatureString);
    console.log(`Hash of "${eventSignatureString}": ${eventSignatureHash}`);
}

testUtilsId().catch((error) => {
    console.error(error);
    process.exitCode = 1;
});

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật