I need to declare a "global" constant that can be accessed by another contract. Given a very simple Solidity contract as follows:
pragma solidity ^0.4.17;
uint256 constant MY_CONSTANT = 3;
contract MyContract {
constructor() public {}
}
This is my truffle-config.js file:
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 9545,
network_id: "*",
},
},
compilers: {
solc: {
version: "^0.4.17"
}
}
};
When I run truffle develop
then truffle compile
, I got the following error:
Compiling your contracts...
===========================
> Compiling ./contracts/MyContract.sol-bin. Attempt #1
CompileError: project:/contracts/MyContract.sol:4:1: ParserError: Expected pragma, import directive or contract/interface/library definition.
uint256 constant MY_CONSTANT = 3;
^-----^
Compilation failed. See above.
at /home/thaiminhpv/.nvm/versions/node/v16.18.1/lib/node_modules/truffle/build/webpack:/packages/compile-solidity/dist/run.js:95:1
at Generator.next (<anonymous>)
at fulfilled (/home/thaiminhpv/.nvm/versions/node/v16.18.1/lib/node_modules/truffle/build/webpack:/packages/compile-solidity/dist/run.js:28:43)
Truffle v5.6.4 (core: 5.6.4)
Node v16.18.1
Here is my truffle version:
$ truffle version
Truffle v5.6.4 (core: 5.6.4)
Ganache v7.5.0
Solidity - ^0.4.17 (solc-js)
Node v16.18.1
Web3.js v1.7.4
However, everything work fine when I change the solidity compiler from ^0.4.17
to 0.8.17
in truffle-config.js
.
How can I declare constant at file level in solidity 0.4.17
?
Because a contract can not access constant of another smart contract, we can not define a smart contract and put all constants into it.
I finally managed to get around the problem by using the library's pure function
in Solidity:
library Constants {
function MY_CONSTANT() public pure returns (uint256) {
return 3;
}
}
and get the constant's value in other contracts by using:
uint256 value = Constants.MY_CONSTANT();