Home > Back-end >  Can I call a function inside a function solidity?
Can I call a function inside a function solidity?

Time:04-08

I have a function in my contract that take 2 numbers and give a random number between those 2. Can I call this function inside some others functions in the same contract?

Something like:

function point(min, max) public view returns (uint256) {
    return /* A number betwwen "min" and "max" */;
}

function generateSVG() public pure returns (string memory) {
   .
   .
   .
    svg = string(abi.encodePacked(svg, "stroke-width='" , point(1, 5) , "' "));
   .
   .
   .
}

Thank you :D

CodePudding user response:

Short answer: sometimes.

Long answer:

In solidity, we specify the visibility of functions and state variables. There are 4 types of visibility:

  • Internal
  • External
  • Public
  • Private

Unless defined explicitly, visibility defaults to internal.

Internal

A function/state variable is only visible to contracts that contains it, or inherits a contract that contains it

External

Can only be called by other contracts

Public

Any contract, whether it contains the code or not, can call

Private

Only the contract that declares it can call, not the ones that inherit it.

Beware, regarding randomness

There is no true randomness in ethereum. You can either create pseudo-random values with blockhash/block height or you can use an oracle that provides true randomness, like Chainlik

  • Related