Upgrade function
The upgrade
function appears to be designed to allow the owner of a specific non-fungible token (NFT) to upgrade its associated plan. Let's break down its functionality:
Function Explanation:
upgrade(uint256 tokenId, uint256 newPlanIndex) external payable nonReentrant
external
: This function can only be called from outside the contract.payable
: This function can receive BNB (or another native cryptocurrency, depending on the blockchain).nonReentrant
: A modifier that ensures the function cannot be re-entered during its execution, which is a common security measure to prevent reentrancy attacks.
Function Parameters:
tokenId
: The unique identifier of the NFT being upgraded.newPlanIndex
: The index of the new plan to which the NFT should be upgraded.
Function Body:
Ownership Check:
Ensures that the caller (
msg.sender
) is the owner of the NFT with the giventokenId
.
Plan Validation:
Checks if the provided
newPlanIndex
is valid. It should be less than 5 (indicating there are 5 plans) and greater than 0.
Current Plan Determination:
Retrieves the current plan associated with the NFT using its
tokenId
.Iterates through the
plans
array to determine the index of the NFT's current plan. This is done by comparing the name of each plan in theplans
array with the name of the NFT's current plan using thekeccak256
hash function. Once a match is found, the loop breaks, and thecurrentPlanIndex
is set.
JavaScript Code:
Explanation:
Initialization:
We start by initializing
web3
with an BSC node URL.We define the ABI and address of the smart contract, then create a contract instance using
web3
.
upgradeNFT
Function:This function is designed to interact with the
upgrade
function of the smart contract.It takes two parameters:
tokenId
(the ID of the NFT you want to upgrade) andnewPlanIndex
(the index of the new plan to which you want to upgrade the NFT).The
fromAddress
is the BSC address that will be calling the function. This should be the owner of the NFT.We estimate a
gasLimit
for the transaction. This is a rough estimate, and you might need to adjust it based on the actual gas requirements of your contract.Inside the function, we call the
upgrade
method of the contract and send the transaction. If successful, the transaction hash is logged to the console.
Error Handling:
If there's an issue with the transaction (e.g., not enough gas, the NFT isn't owned by the caller, the plan index is invalid), the error will be caught and logged to the console.
Example Usage:
We provide an example of how to use the
upgradeNFT
function. In this example, we're attempting to upgrade an NFT with atokenId
of 123 to a plan with an index of 2.
This JavaScript function provides a way to interact with the BSC smart contract's upgrade
function from an external application or script.
Last updated