1

I'm writing a smart contract and I want to declare global variables. I want the functions in my smart contract to be able to access and update these variables.

For example, in Solidity I can do this as follows:

pragma solidity ^0.5.0;
contract SolidityTest {
   uint someSmartContractVar;      // State variable
   constructor() public {
      someSmartContractVar = 10;   // Setting the variable
   }

   ...

}

I see the coin contract makes use of defconst here:

  (defconst COIN_CHARSET CHARSET_LATIN1
    "The default coin contract character set")

This approach is good for variables that need to be accessible by the rest of the contract, but I don't think I can change the values of these variables at some later point.

One possibility is creating a table named "global-variables" and storing the specific variables there. So then the functions can access and change these variables via table reads and updates. For example:

  (defschema global-variable-schema
    someSmartContractVar:decimal)

  (deftable global-variables:{global-variable-schema})

  (defconst GLOBAL_VAR_KEYNAME "global-vars")

  (defun constructor:string ()
    (insert global-variables GLOBAL_VAR_KEYNAME
          { 'someSmartContractVar: 10.0 }
    )
    "Global variables set"
  )

  (defun get-someSmartContractVar:decimal ()
    (at "someSmartContractVar" (read global-variables GLOBAL_VAR_KEYNAME))
  )

Is this the recommended approach for this type of use case?

1 Answers1

0

Great question and that solution should work! I don't know of any other practical way to do it.

georgep
  • 731
  • 1
  • 12