CoolFace
Datasetpublic

enigmare/v2-crawler

sourceHugging Faceupdated 28d agoView on Hugging Face
1likes889downloads
solidity.jsonl363 linesDownload Raw Back to stackoverflow
1{"id":"stack-64733976","source":"stackoverflow","questionId":64733976,"title":"I am having a difficulty of understanding interfaces in Solidity. What am I missing?","tags":["interface","ethereum","solidity"],"text":"Title: I am having a difficulty of understanding interfaces in Solidity. What am I missing?\nTags: interface, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI came from Java OOP background and understand interfaces.\n\nCurrently working on a simple budgeting app (https://github.com/compound-developers/compound-supply-examples) that takes ETH or Stablecoin and put in in Compound and earn interest.\n\nMy confusion is how Solidity Interfaces are used. I came from OOP (Java) background and very familiar with interfaces.\n\nSo in this code(`MyContracts.sol`) you can see that there is a `mint()` function in the interface. However, there is no implementation for it but you can see that it's used here `uint mintResult = cToken.mint(_numTokensToSupply);` without any implementation.\n\nCan anyone shade some lights on how interface functions are used without implementations ? When you call **mint** in this case, which code is actually being executed ?\n\n========================================\n\nTop Answer:\n`interface` is used for type casting. from this contract\n\n```\ninterface IReceiver {\n function receiveTokens(address tokenAddress, uint256 amount) external;\n}\n```\n\ninside contract\n\n```\ncontract UnstoppableLender is ReentrancyGuard {\n .....\n function flashLoan(uint256 borrowAmount) external nonReentrant {\n require(borrowAmount > 0, \"Must borrow at least one token\");\n uint256 balanceBefore = damnValuableToken.balanceOf(address(this));\n require(balanceBefore >= borrowAmount, \"Not enough tokens in pool\");\n assert(poolBalance == balanceBefore);\n damnValuableToken.transfer(msg.sender, borrowAmount);\n\n // that means msg.sender has receiveTokens functionality\n // we are making sure that who ever is calling this function, has this method implemented\n // we can conclude that ms.sender is a contract address\n IReceiver(msg.sender).receiveTokens(\n address(damnValuableToken),\n borrowAmount\n );\n .......\n}\n```\n\n`msg.sender` is the address that calling `flashLoan` function. By casting with the `IReceiver` interface we are saying that whichever contract address is calling `flashLoan` function must have it is own `receiveTokens` function implemented.\n\nIf you look at the contract that calling the `flashLoan` function, in fact has `receiveTokens`\n\n```\nfunction receiveTokens(address tokenAddress, uint256 amount) external {\n require(msg.sender == address(pool), \"Sender must be pool\");\n // Return all tokens to the pool\n require(IERC20(tokenAddress).transfer(msg.sender, amount), \"Transfer of tokens failed\");\n }\n```\n\n========================================\n\nCode:\n```text\nMyContracts.sol\n```\n\n```text\nmint()\n```\n\n```text\nuint mintResult = cToken.mint(_numTokensToSupply);\n```\n\n```text\ninterface IERC20 { \n   function totalSupply() external view returns (uint256);\n}\n\ncontract XYZ is IERC20 {\n// then implement totalSupply here \nfunction totalSupply() external view returns (uint256) {\n// implementiation goes here. \naddress public add='0x123...4'\n}\n```\n\n```text\ninterface CEth {\n    function mint() external payable;\n\n    function exchangeRateCurrent() external returns (uint256);\n\n    function supplyRatePerBlock() external returns (uint256);\n\n    function redeem(uint) external returns (uint);\n\n    function redeemUnderlying(uint) external returns (uint);\n}\n```\n\n```text\nCEth cToken = CEth(_cEtherContract);\n```\n\n```text\ntotalSupply()\n```\n\n```text\nMyContracts.sol\n```\n\n```text\nMyContract\n```\n\n```text\nMyContracts.sol\n```\n\n```text\nsupplyEthToCompound\n```\n\n```text\n_cEtherContract\n```\n\n```text\ncToken.exchangeRateCurrent();\n```\n\n```text\ninterface IReceiver {\n    function receiveTokens(address tokenAddress, uint256 amount) external;\n}\n```\n\n```text\ncontract UnstoppableLender is ReentrancyGuard {\n    .....\n    function flashLoan(uint256 borrowAmount) external nonReentrant {\n        require(borrowAmount > 0, \"Must borrow at least one token\");\n        uint256 balanceBefore = damnValuableToken.balanceOf(address(this));\n        require(balanceBefore >= borrowAmount, \"Not enough tokens in pool\");\n        assert(poolBalance == balanceBefore);\n        damnValuableToken.transfer(msg.sender, borrowAmount);\n\n        // that means msg.sender has receiveTokens functionality\n        // we are making sure that who ever is calling this function, has this method implemented\n        // we can conclude that ms.sender is a contract address\n        IReceiver(msg.sender).receiveTokens(\n            address(damnValuableToken),\n            borrowAmount\n        );\n      .......\n}\n```\n\n```text\nfunction receiveTokens(address tokenAddress, uint256 amount) external {\n        require(msg.sender == address(pool), \"Sender must be pool\");\n        // Return all tokens to the pool\n        require(IERC20(tokenAddress).transfer(msg.sender, amount), \"Transfer of tokens failed\");\n    }\n```\n\n```text\ninterface\n```\n\n```text\nmsg.sender\n```\n\n```text\nflashLoan\n```\n\n```text\nIReceiver\n```\n\n```text\nflashLoan\n```\n\n```text\nreceiveTokens\n```\n\n```text\nflashLoan\n```\n\n```text\nreceiveTokens\n```\n\n========================================\n\nComments:\n- Hey, thank you very much for your explanation. It is very helpful. I would like to ask you (and I am sorry in advance for a silly question, but I am really new to OOP): In the code, you defined the implementation of the totalSupply() function in the contract. My question is. Why would I define the totalSupply() without implementation in interface if I subsequently define the function again in the contract? What for is the interface then? PS if you have a great source to study in order to understand, please, I would love to dive into it. Thanks in advance!\n- I still don't get it, where is the Compound contract defined and the implementation for the exchangeRateCurrent() function?","metadata":{"transformedAt":"2026-08-18T18:33:36.112Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":207,"estimatedTokens":1429}}2{"id":"stack-63712347","source":"stackoverflow","questionId":63712347,"title":"Getting error \"creation of HelloWorld errored: TypeError: Cannot convert undefined or null to object\"","tags":["ethereum","solidity","remix"],"text":"Title: Getting error \"creation of HelloWorld errored: TypeError: Cannot convert undefined or null to object\"\nTags: ethereum, solidity, remix\nSource: Stack Overflow\n\nQuestion:\nPretty new to Solidity and just tried the first HelloWorld smart contract in Remix IDE and stumbled upon this error, while trying to deploy the smart contract.\n\n```\ncreation of HelloWorld pending...\ncreation of HelloWorld errored: TypeError: Cannot convert undefined or null to object\n```\n\nMy code:\n\n```\npragma solidity ^0.5.16;\n\ncontract HelloWorld {\n string public greet = \"Hello World!\";\n}\n```\n\nThe Compiler version is set to `0.5.16+commit.9c3226ce`\n\nNot sure what I am missing, hence any all help and guidance is highly appreciated.\n\n========================================\n\nCode:\n```text\ncreation of HelloWorld pending...\ncreation of HelloWorld errored: TypeError: Cannot convert undefined or null to object\n```\n\n```text\npragma solidity ^0.5.16;\n\ncontract HelloWorld {\n    string public greet = \"Hello World!\";\n}\n```\n\n```text\n0.5.16+commit.9c3226ce\n```\n\n========================================\n\nComments:\n- I copy pasted your code in solidity remix online IDE. It compiled with no error as it should. There is nothing wrong in the code.","metadata":{"transformedAt":"2026-08-18T18:33:36.112Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":50,"estimatedTokens":305}}3{"id":"stack-68891144","source":"stackoverflow","questionId":68891144,"title":"How to fix \"Unidentified contract\"? OpenSea is unable to “understand” ERC1155","tags":["ethereum","solidity","opensea"],"text":"Title: How to fix \"Unidentified contract\"? OpenSea is unable to “understand” ERC1155\nTags: ethereum, solidity, opensea\nSource: Stack Overflow\n\nQuestion:\nI have deployed a **ERC-1155** based contract (based on OpenZeppelin) and minted some NFTs on this contract successfully. But when I want to use these NFTs in OpenSea, it always says *\"Unidentified contract\"*.\n\nExample: https://testnets.opensea.io/assets/0xc7d3e4a5A0c3e14ba8C68ea1b8a99a9dBf3ca76F/2\n\nAPI-Example: https://testnets-api.opensea.io/api/v1/asset/0xc7d3e4a5A0c3e14ba8C68ea1b8a99a9dBf3ca76F/2/?force_update=true\n\nFollowing their official Tutorial repository (which does not compile any more because of outdated dependencies and other issues) I have added some (maybe) opensea-specific functions and data that might required for OpenSea in order to work properly. However, OpenSea is able to grab all required data to display an NFT, but as long as they say \"Unidentified contract\", this all makes no sense so far.\n\nMy question has:\n\nhas someone already managed to deploy a ERC-1155 and used it with OpenSea properly without this issue? Is there anything we have to \"register\" somehow contracts that are not based on ERC-721?\n\n### 🔢 Code to reproduce\n\n```\nimport \"@openzeppelin/contracts/token/ERC1155/ERC1155.sol\";\nimport \"@openzeppelin/contracts/access/AccessControl.sol\";\nimport \"@openzeppelin/contracts/security/Pausable.sol\";\nimport \"@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol\";\n\nimport \"@openzeppelin/contracts/utils/Counters.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\ncontract OwnableDelegateProxy { }\n\ncontract ProxyRegistry {\n mapping(address => OwnableDelegateProxy) public proxies;\n}\n\ncontract MetaCoin is ERC1155, AccessControl, Pausable, ERC1155Burnable {\n bytes32 public constant URI_SETTER_ROLE = keccak256(\"URI_SETTER_ROLE\");\n bytes32 public constant PAUSER_ROLE = keccak256(\"PAUSER_ROLE\");\n bytes32 public constant MINTER_ROLE = keccak256(\"MINTER_ROLE\");\n\n address proxyRegistryAddress;\n\n constructor(address _proxyRegistryAddress) ERC1155(\"https://abcoathup.github.io/SampleERC1155/api/token/{id}.json\") { \n _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);\n _setupRole(URI_SETTER_ROLE, msg.sender);\n _setupRole(PAUSER_ROLE, msg.sender);\n _setupRole(MINTER_ROLE, msg.sender);\n\n proxyRegistryAddress = _proxyRegistryAddress;\n }\n\n function setURI(string memory newuri) public onlyRole(URI_SETTER_ROLE) {\n _setURI(newuri);\n }\n\nfunction pause() public onlyRole(PAUSER_ROLE) {\n _pause();\n}\n\nfunction unpause() public onlyRole(PAUSER_ROLE) {\n _unpause();\n}\n\nfunction supportsInterface(bytes4 interfaceId)\n public\n view\n override(ERC1155, AccessControl)\n returns (bool)\n{\n return super.supportsInterface(interfaceId);\n}\n\n function mint(address account, uint256 id, uint256 amount, bytes memory data)\n public\n onlyRole(MINTER_ROLE)\n {\n _mint(account, id, amount, data);\n }\n\n function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data)\n public\n onlyRole(MINTER_ROLE)\n {\n _mintBatch(to, ids, amounts, data);\n }\n\n function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data)\n internal\n whenNotPaused\n override\n {\n super._beforeTokenTransfer(operator, from, to, ids, amounts, data);\n }\n\n /**\n * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.\n */\n function isApprovedForAll(\n address _owner,\n address _operator\n ) public override view returns (bool isOperator) {\n // Whitelist OpenSea proxy contract for easy trading.\n ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);\n if (address(proxyRegistry.proxies(_owner)) == _operator) {\n return true;\n }\n\n return ERC1155.isApprovedForAll(_owner, _operator);\n }\n\n}\n```\n\n### 💻 Environment\n\nnode: v16.7.0\n\ndeps:\n\n```\n\"@openzeppelin/contracts\": \"^4.3.0\",\n\"@nomiclabs/buidler\": \"^1.4.8\",\n\"@nomiclabs/hardhat-ethers\": \"^2.0.2\",\n\"@nomiclabs/hardhat-etherscan\": \"^2.1.1\",\n\"@nomiclabs/hardhat-waffle\": \"^2.0.1\",\n\"@openzeppelin/hardhat-upgrades\": \"^1.9.0\",\n\"@typechain/ethers-v5\": \"^6.0.5\",\n\"@typechain/hardhat\": \"^1.0.1\",\n\"@types/chai\": \"^4.2.15\",\n\"@types/chai-as-promised\": \"^7.1.3\",\n\"@types/mocha\": \"^8.2.2\",\n\"@types/node\": \"^14.14.37\",\n\"chai\": \"^4.3.3\",\n\"chai-as-promised\": \"^7.1.1\",\n\"chai-datetime\": \"^1.8.0\",\n\"ethereum-waffle\": \"^3.3.0\",\n\"ethers\": \"^5.4.5\",\n\"hardhat\": \"^2.6.1\",\n\"hardhat-typechain\": \"^0.3.5\",\n\"ts-generator\": \"^0.1.1\",\n\"ts-node\": \"^9.1.1\",\n\"typechain\": \"^4.0.3\",\n\"typescript\": \"^4.2.4\"\n```\n\n========================================\n\nTop Answer:\nThis is taken from `name` in your contract.\n\nFor ERC-1155 tokens, add a public variable `name`\n\n`string public name = \"My Collection Name\";`\n\n========================================\n\nCode:\n```text\nimport \"@openzeppelin/contracts/token/ERC1155/ERC1155.sol\";\nimport \"@openzeppelin/contracts/access/AccessControl.sol\";\nimport \"@openzeppelin/contracts/security/Pausable.sol\";\nimport \"@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol\";\n\nimport \"@openzeppelin/contracts/utils/Counters.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\n\ncontract OwnableDelegateProxy { }\n\ncontract ProxyRegistry {\n  mapping(address => OwnableDelegateProxy) public proxies;\n}\n\n\ncontract MetaCoin is ERC1155, AccessControl, Pausable, ERC1155Burnable {\n    bytes32 public constant URI_SETTER_ROLE = keccak256(\"URI_SETTER_ROLE\");\n    bytes32 public constant PAUSER_ROLE = keccak256(\"PAUSER_ROLE\");\n    bytes32 public constant MINTER_ROLE = keccak256(\"MINTER_ROLE\");\n\n    address proxyRegistryAddress;\n\n\n    constructor(address _proxyRegistryAddress) ERC1155(\"https://abcoathup.github.io/SampleERC1155/api/token/{id}.json\") {       \n        _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);\n        _setupRole(URI_SETTER_ROLE, msg.sender);\n        _setupRole(PAUSER_ROLE, msg.sender);\n        _setupRole(MINTER_ROLE, msg.sender);\n\n        proxyRegistryAddress = _proxyRegistryAddress;\n    }\n\n    function setURI(string memory newuri) public onlyRole(URI_SETTER_ROLE) {\n        _setURI(newuri);\n    }\n\nfunction pause() public onlyRole(PAUSER_ROLE) {\n    _pause();\n}\n\nfunction unpause() public onlyRole(PAUSER_ROLE) {\n    _unpause();\n}\n\nfunction supportsInterface(bytes4 interfaceId)\n    public\n    view\n    override(ERC1155, AccessControl)\n    returns (bool)\n{\n    return super.supportsInterface(interfaceId);\n}\n\n    function mint(address account, uint256 id, uint256 amount, bytes memory data)\n        public\n        onlyRole(MINTER_ROLE)\n    {\n        _mint(account, id, amount, data);\n    }\n\n    function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data)\n        public\n        onlyRole(MINTER_ROLE)\n    {\n        _mintBatch(to, ids, amounts, data);\n    }\n\n    function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data)\n        internal\n        whenNotPaused\n        override\n    {\n        super._beforeTokenTransfer(operator, from, to, ids, amounts, data);\n    }\n\n  /**\n   * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.\n   */\n  function isApprovedForAll(\n    address _owner,\n    address _operator\n  ) public override view returns (bool isOperator) {\n    // Whitelist OpenSea proxy contract for easy trading.\n    ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);\n    if (address(proxyRegistry.proxies(_owner)) == _operator) {\n      return true;\n    }\n\n    return ERC1155.isApprovedForAll(_owner, _operator);\n  }\n\n\n}\n```\n\n```text\n\"@openzeppelin/contracts\": \"^4.3.0\",\n\"@nomiclabs/buidler\": \"^1.4.8\",\n\"@nomiclabs/hardhat-ethers\": \"^2.0.2\",\n\"@nomiclabs/hardhat-etherscan\": \"^2.1.1\",\n\"@nomiclabs/hardhat-waffle\": \"^2.0.1\",\n\"@openzeppelin/hardhat-upgrades\": \"^1.9.0\",\n\"@typechain/ethers-v5\": \"^6.0.5\",\n\"@typechain/hardhat\": \"^1.0.1\",\n\"@types/chai\": \"^4.2.15\",\n\"@types/chai-as-promised\": \"^7.1.3\",\n\"@types/mocha\": \"^8.2.2\",\n\"@types/node\": \"^14.14.37\",\n\"chai\": \"^4.3.3\",\n\"chai-as-promised\": \"^7.1.1\",\n\"chai-datetime\": \"^1.8.0\",\n\"ethereum-waffle\": \"^3.3.0\",\n\"ethers\": \"^5.4.5\",\n\"hardhat\": \"^2.6.1\",\n\"hardhat-typechain\": \"^0.3.5\",\n\"ts-generator\": \"^0.1.1\",\n\"ts-node\": \"^9.1.1\",\n\"typechain\": \"^4.0.3\",\n\"typescript\": \"^4.2.4\"\n```\n\n```text\nname\n```\n\n```text\nname\n```\n\n```text\nname\n```\n\n```text\nstring public name = \"My Collection Name\";\n```\n\n========================================\n\nComments:\n- I've followed this tutorial for the bulk upload: youtu.be/VglTdr0n5ZQ?t=1496. The images are there on the testnet and as I've defined the variable `name` in my contract, the Unidentified contract - DmXmQaXXXX issue has been solved but, how we could upload a folder to an existing collection we own on the OpenSea? Cause right now, when I use the existing collection name, it creates a new collection V2!","metadata":{"transformedAt":"2026-08-18T18:33:36.112Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":299,"estimatedTokens":2217}}4{"id":"stack-48167811","source":"stackoverflow","questionId":48167811,"title":"Network up to date on truffle deploy","tags":["blockchain","solidity","contract","truffle"],"text":"Title: Network up to date on truffle deploy\nTags: blockchain, solidity, contract, truffle\nSource: Stack Overflow\n\nQuestion:\nI've been working with `solidity` and `truffle` for a few days to develop a contract. I'm testing using the network created by Ganache an RPC client for build a local blockchain enviroment.\n\nThere is one thing I do not understand though.\n\nI these steps:\n\n- `truffle deploy`. I deploy my contract on the network.\n\n- `truffle test`. I test my contract.It's OK.\n\n- `truffle deploy`. I try to update my contract. Say me **\"Network up to date\"**\n\nBut if I restart Ganache and update my contract with `truffle deploy`, it works. This is the thing that I don't understand.\n\nWhy? Can someone explain it to me?\n\n========================================\n\nTop Answer:\ndeploy.js=>1_deploy.js\nIn Truffle, deployment scripts are named with numerical prefixes to control the order in which they are executed.\nThis prefixing system ensures that dependencies between contracts are respected during deployment.\nToken.sol => 1_deploy.js\nPresale.sol => 2_deploy.js\n\n========================================\n\nCode:\n```text\nsolidity\n```\n\n```text\ntruffle\n```\n\n```text\ntruffle deploy\n```\n\n```text\ntruffle test\n```\n\n```text\ntruffle deploy\n```\n\n```text\ntruffle deploy\n```\n\n```text\ntruffle deploy --reset\n```\n\n========================================\n\nComments:\n- Are you running `ganache-cli` while you execute the truffle commands? If you are doing that the contracts are deployed in your private ganache network, and I guess if you try to deploy the same contract again it without changes it wont let you because you will deploy contract that is the same as the one you deployed before.\n- Thank you for you explain man! I understand now!\n- You can also force a redeploy by running `truffle deploy --reset`\n- @alvarofvr I would add that restarting Ganache creates a new empty simulation environment and thus `truffle deploy` starts working again.\n- Thanks that was my issue too. However, I did the following for the current version of Truffle: `truffle migrate --reset --network ropsten`\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:36.112Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":70,"estimatedTokens":582}}5{"id":"stack-70074736","source":"stackoverflow","questionId":70074736,"title":"Do you need SafeMath in Solidity version 0.8+ , and if not, can you still import it?","tags":["ethereum","solidity","smartcontracts","evm"],"text":"Title: Do you need SafeMath in Solidity version 0.8+ , and if not, can you still import it?\nTags: ethereum, solidity, smartcontracts, evm\nSource: Stack Overflow\n\nQuestion:\nI have a solidity smart contract like this `pragma solidity >=0.7.0 <0.9.0;` can I still import SafeMath even if it's not needed for 0.8+ ? Since SafeMath is working with 0.7, but my contract specifies it accepts 0.7.0 up to lower than 0.9.0 what will SafeMath do in this case.\n\n========================================\n\nTop Answer:\n```\n* @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behaviour in high-level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with a custom message on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n *\n * _Available since v2.4.0._\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with a custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n *\n * _Available since v2.4.0._\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}\n```\n\n========================================\n\nCode:\n```text\npragma solidity >=0.7.0 <0.9.0;\n```\n\n```text\npragma solidity >=0.7.0 <0.9.0;\n\nlibrary SafeMath {\n  function add(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    c = a + b;\n    assert(c >= a);\n    return c;\n  }\n}\n\ncontract MyContract {\n    using SafeMath for uint256;\n    \n    function foo() external pure {\n        uint256 number = 1;\n        number.add(1);\n    }\n}\n```\n\n```text\n* @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behaviour in high-level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n    /**\n     * @dev Returns the addition of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `+` operator.\n     *\n     * Requirements:\n     * - Addition cannot overflow.\n     */\n    function add(uint256 a, uint256 b) internal pure returns (uint256) {\n        uint256 c = a + b;\n        require(c >= a, \"SafeMath: addition overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n        return sub(a, b, \"SafeMath: subtraction overflow\");\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting with a custom message on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity's `-` operator.\n     *\n     * Requirements:\n     * - Subtraction cannot overflow.\n     *\n     * _Available since v2.4.0._\n     */\n    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b <= a, errorMessage);\n        uint256 c = a - b;\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity's `*` operator.\n     *\n     * Requirements:\n     * - Multiplication cannot overflow.\n     */\n    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n        // benefit is lost if 'b' is also tested.\n        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n        if (a == 0) {\n            return 0;\n        }\n\n        uint256 c = a * b;\n        require(c / a == b, \"SafeMath: multiplication overflow\");\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers. Reverts on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b) internal pure returns (uint256) {\n        return div(a, b, \"SafeMath: division by zero\");\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers. Reverts with a custom message on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity's `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     *\n     * _Available since v2.4.0._\n     */\n    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        // Solidity only automatically asserts when dividing by 0\n        require(b > 0, errorMessage);\n        uint256 c = a / b;\n        // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n        return c;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * Reverts when dividing by zero.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n        return mod(a, b, \"SafeMath: modulo by zero\");\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * Reverts with a custom message when dividing by zero.\n     *\n     * Counterpart to Solidity's `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     * - The divisor cannot be zero.\n     *\n     * _Available since v2.4.0._\n     */\n    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b != 0, errorMessage);\n        return a % b;\n    }\n}\n```\n\n========================================\n\nComments:\n- ok and what happens if you don't use SafeMath and an overflow/underflow occurs, does it revert the transaction but end up costing more gas?\n- @msa720 In v0.8, the transaction reverts... In v0.7, the number just overflows or underflows. For example you have an `uint8` (min value 0, max value 255), with value 0. If you subtract 1 from this number, it underflows, resulting in 255.\n- @PetrHejda what if I need to perform division e.g. 5/2, can solidity 0.8 do it without rounding or I should use SafeMath in this case?\n- @gigs The EVM doesn't support decimal numbers. Solidity is able to calculate 5/2 but it casts to an integer (i.e. rounds down) as soon as it's stored on the EVM level (either to memory or storage)... SafeMath \"only\" prevents integer overflow and underflow but it's not related to working with decimals... A usual workaround, if you need to work with decimal numbers, is to store values multiplied by `10 ^ decimals`. For example you declare that your contract uses 2 decimal places, and then store the value of `1` as `100`.\n- @PetrHejda ok then, as I understand you right we should apply decimal multiplication only for the first number e.g. 500/2, correct?\n- @gigs Correct, assuming you're using 2 decimal places.\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:36.112Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":301,"estimatedTokens":2670}}6{"id":"stack-76328677","source":"stackoverflow","questionId":76328677,"title":"Remix: Returned error: {\"jsonrpc\":\"2.0\",\"error\":\"invalid opcode: PUSH0\", \"id\":2405507186007008}","tags":["solidity","chainlink","go-ethereum"],"text":"Title: Remix: Returned error: {\"jsonrpc\":\"2.0\",\"error\":\"invalid opcode: PUSH0\", \"id\":2405507186007008}\nTags: solidity, chainlink, go-ethereum\nSource: Stack Overflow\n\nQuestion:\nAfter runing my private chain node in geth and Chainlink node in my Ubuntu, I would like to test the function of Chainlink Any API(https://docs.chain.link/any-api/get-request/examples/single-word-response, Single Word Response).\n\nI ran these commands to run nodes:\n\n```\n## SHELL1\ncd ~/myChain/localChain/node1 && geth --datadir data --gcmode \"archive\" --syncmode=full --networkid 4190 --http --http.addr 0.0.0.0 --http.port 6789 --http.corsdomain \"*\" --ws --port 30305 --allow-insecure-unlock --unlock edd96278959aA8B27DdC14FD70ACb31f7e7beC2F --keystore ./keystore console\n\n## SHELL2\ncd ~/myChain/chainlink/.chainlink && docker run --net host -u=root -p 6688:6688 -v ~/.chainlink:/chainlink -it --env-file=.env smartcontract/chainlink:1.11.0 local n\n```\n\nI successfully deployed my `LinkToken` contract, `operator` contract and created a new job(***GET>uint256***) in my Chainlink node UI Operator. They are as followed:\n\n**LinkToken.sol**\n\n```\npragma solidity ^0.4.11;\n\nimport \"https://github.com/smartcontractkit/chainlink/contracts/src/v0.4/ERC677Token.sol\";\nimport { StandardToken as linkStandardToken } from \"https://github.com/smartcontractkit/chainlink/contracts/src/v0.4/vendor/StandardToken.sol\";\n\ncontract LinkToken is linkStandardToken, ERC677Token {\n\n uint public constant totalSupply = 10**27;\n string public constant name = \"ChainLink Token\";\n uint8 public constant decimals = 18;\n string public constant symbol = \"LINK\";\n\n function LinkToken()\n public\n {\n balances[msg.sender] = totalSupply;\n }\n\n /**\n * @dev transfer token to a specified address with additional data if the recipient is a contract.\n * @param _to The address to transfer to.\n * @param _value The amount to be transferred.\n * @param _data The extra data to be passed to the receiving contract.\n */\n function transferAndCall(address _to, uint _value, bytes _data)\n public\n validRecipient(_to)\n returns (bool success)\n {\n return super.transferAndCall(_to, _value, _data);\n }\n\n /**\n * @dev transfer token to a specified address.\n * @param _to The address to transfer to.\n * @param _value The amount to be transferred.\n */\n function transfer(address _to, uint _value)\n public\n validRecipient(_to)\n returns (bool success)\n {\n return super.transfer(_to, _value);\n }\n\n /**\n * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.\n * @param _spender The address which will spend the funds.\n * @param _value The amount of tokens to be spent.\n */\n function approve(address _spender, uint256 _value)\n public\n validRecipient(_spender)\n returns (bool)\n {\n return super.approve(_spender, _value);\n }\n\n /**\n * @dev Transfer tokens from one address to another\n * @param _from address The address which you want to send tokens from\n * @param _to address The address which you want to transfer to\n * @param _value uint256 the amount of tokens to be transferred\n */\n function transferFrom(address _from, address _to, uint256 _value)\n public\n validRecipient(_to)\n returns (bool)\n {\n return super.transferFrom(_from, _to, _value);\n }\n\n // MODIFIERS\n\n modifier validRecipient(address _recipient) {\n require(_recipient != address(0) && _recipient != address(this));\n _;\n }\n\n}\n```\n\n**operator.sol**\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity ^0.7.6;\nimport \"@chainlink/contracts/src/v0.7/Operator.sol\";\n```\n\n**job GET>uint256 (I have already change the \"YOUR_ORACLE_CONTRACT_ADDRESS\" with my `operator` contract address)**\n\n```\ntype = \"directrequest\"\nschemaVersion = 1\nname = \"Get > Uint256 - (TOML)\"\nmaxTaskDuration = \"0s\"\ncontractAddress = \"YOUR_ORACLE_CONTRACT_ADDRESS\"\nminIncomingConfirmations = 0\nobservationSource = \"\"\"\n decode_log [type=\"ethabidecodelog\"\n abi=\"OracleRequest(bytes32 indexed specId, address requester, bytes32 requestId, uint256 payment, address callbackAddr, bytes4 callbackFunctionId, uint256 cancelExpiration, uint256 dataVersion, bytes data)\"\n data=\"$(jobRun.logData)\"\n topics=\"$(jobRun.logTopics)\"]\n\n decode_cbor [type=\"cborparse\" data=\"$(decode_log.data)\"]\n fetch [type=\"http\" method=GET url=\"$(decode_cbor.get)\" allowUnrestrictedNetworkAccess=\"true\"]\n parse [type=\"jsonparse\" path=\"$(decode_cbor.path)\" data=\"$(fetch)\"]\n\n multiply [type=\"multiply\" input=\"$(parse)\" times=\"$(decode_cbor.times)\"]\n\n encode_data [type=\"ethabiencode\" abi=\"(bytes32 requestId, uint256 value)\" data=\"{ \\\\\"requestId\\\\\": $(decode_log.requestId), \\\\\"value\\\\\": $(multiply) }\"]\n encode_tx [type=\"ethabiencode\"\n abi=\"fulfillOracleRequest2(bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes calldata data)\"\n data=\"{\\\\\"requestId\\\\\": $(decode_log.requestId), \\\\\"payment\\\\\": $(decode_log.payment), \\\\\"callbackAddress\\\\\": $(decode_log.callbackAddr), \\\\\"callbackFunctionId\\\\\": $(decode_log.callbackFunctionId), \\\\\"expiration\\\\\": $(decode_log.cancelExpiration), \\\\\"data\\\\\": $(encode_data)}\"\n ]\n submit_tx [type=\"ethtx\" to=\"YOUR_ORACLE_CONTRACT_ADDRESS\" data=\"$(encode_tx)\"]\n\n decode_log -> decode_cbor -> fetch -> parse -> multiply -> encode_data -> encode_tx -> submit_tx\n\"\"\"\n```\n\n`LinkToken` contract is used to transfer LINK token to other address, and `Operator` contract is used to interact with my Chainlink node. By following the document of Chainlink, I will deploy `ATestnetConsumer` contract then request the API data.\n\nHowever, I got an error in Remix like this:\n\n```\nGas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? Returned error: {\"jsonrpc\":\"2.0\",\"error\":\"invalid opcode: PUSH0\", \"id\":2405507186007008}\n```\n\nPUSH0 Error in Remix\nAnd my geth console also got this error: PUSH0 Error in Geth\n\nI tried to reset my geth node and Chainlink node and redo all the same steps. However, they don't make sense.\n\n========================================\n\nCode:\n```text\n## SHELL1\ncd ~/myChain/localChain/node1 && geth --datadir data --gcmode \"archive\" --syncmode=full --networkid 4190 --http --http.addr 0.0.0.0 --http.port 6789 --http.corsdomain \"*\" --ws --port 30305 --allow-insecure-unlock --unlock edd96278959aA8B27DdC14FD70ACb31f7e7beC2F --keystore ./keystore console\n\n## SHELL2\ncd ~/myChain/chainlink/.chainlink && docker run --net host -u=root  -p 6688:6688 -v ~/.chainlink:/chainlink -it --env-file=.env smartcontract/chainlink:1.11.0 local n\n```\n\n```text\npragma solidity ^0.4.11;\n\nimport \"https://github.com/smartcontractkit/chainlink/contracts/src/v0.4/ERC677Token.sol\";\nimport { StandardToken as linkStandardToken } from \"https://github.com/smartcontractkit/chainlink/contracts/src/v0.4/vendor/StandardToken.sol\";\n\n\ncontract LinkToken is linkStandardToken, ERC677Token {\n\n  uint public constant totalSupply = 10**27;\n  string public constant name = \"ChainLink Token\";\n  uint8 public constant decimals = 18;\n  string public constant symbol = \"LINK\";\n\n  function LinkToken()\n    public\n  {\n    balances[msg.sender] = totalSupply;\n  }\n\n  /**\n  * @dev transfer token to a specified address with additional data if the recipient is a contract.\n  * @param _to The address to transfer to.\n  * @param _value The amount to be transferred.\n  * @param _data The extra data to be passed to the receiving contract.\n  */\n  function transferAndCall(address _to, uint _value, bytes _data)\n    public\n    validRecipient(_to)\n    returns (bool success)\n  {\n    return super.transferAndCall(_to, _value, _data);\n  }\n\n  /**\n  * @dev transfer token to a specified address.\n  * @param _to The address to transfer to.\n  * @param _value The amount to be transferred.\n  */\n  function transfer(address _to, uint _value)\n    public\n    validRecipient(_to)\n    returns (bool success)\n  {\n    return super.transfer(_to, _value);\n  }\n\n  /**\n   * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.\n   * @param _spender The address which will spend the funds.\n   * @param _value The amount of tokens to be spent.\n   */\n  function approve(address _spender, uint256 _value)\n    public\n    validRecipient(_spender)\n    returns (bool)\n  {\n    return super.approve(_spender,  _value);\n  }\n\n  /**\n   * @dev Transfer tokens from one address to another\n   * @param _from address The address which you want to send tokens from\n   * @param _to address The address which you want to transfer to\n   * @param _value uint256 the amount of tokens to be transferred\n   */\n  function transferFrom(address _from, address _to, uint256 _value)\n    public\n    validRecipient(_to)\n    returns (bool)\n  {\n    return super.transferFrom(_from, _to, _value);\n  }\n\n\n  // MODIFIERS\n\n  modifier validRecipient(address _recipient) {\n    require(_recipient != address(0) && _recipient != address(this));\n    _;\n  }\n\n}\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.7.6;\nimport \"@chainlink/contracts/src/v0.7/Operator.sol\";\n```\n\n```text\ntype = \"directrequest\"\nschemaVersion = 1\nname = \"Get > Uint256 - (TOML)\"\nmaxTaskDuration = \"0s\"\ncontractAddress = \"YOUR_ORACLE_CONTRACT_ADDRESS\"\nminIncomingConfirmations = 0\nobservationSource = \"\"\"\n    decode_log   [type=\"ethabidecodelog\"\n                  abi=\"OracleRequest(bytes32 indexed specId, address requester, bytes32 requestId, uint256 payment, address callbackAddr, bytes4 callbackFunctionId, uint256 cancelExpiration, uint256 dataVersion, bytes data)\"\n                  data=\"$(jobRun.logData)\"\n                  topics=\"$(jobRun.logTopics)\"]\n\n    decode_cbor  [type=\"cborparse\" data=\"$(decode_log.data)\"]\n    fetch        [type=\"http\" method=GET url=\"$(decode_cbor.get)\" allowUnrestrictedNetworkAccess=\"true\"]\n    parse        [type=\"jsonparse\" path=\"$(decode_cbor.path)\" data=\"$(fetch)\"]\n\n    multiply     [type=\"multiply\" input=\"$(parse)\" times=\"$(decode_cbor.times)\"]\n\n    encode_data  [type=\"ethabiencode\" abi=\"(bytes32 requestId, uint256 value)\" data=\"{ \\\\\"requestId\\\\\": $(decode_log.requestId), \\\\\"value\\\\\": $(multiply) }\"]\n    encode_tx    [type=\"ethabiencode\"\n                  abi=\"fulfillOracleRequest2(bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes calldata data)\"\n                  data=\"{\\\\\"requestId\\\\\": $(decode_log.requestId), \\\\\"payment\\\\\":   $(decode_log.payment), \\\\\"callbackAddress\\\\\": $(decode_log.callbackAddr), \\\\\"callbackFunctionId\\\\\": $(decode_log.callbackFunctionId), \\\\\"expiration\\\\\": $(decode_log.cancelExpiration), \\\\\"data\\\\\": $(encode_data)}\"\n                  ]\n    submit_tx    [type=\"ethtx\" to=\"YOUR_ORACLE_CONTRACT_ADDRESS\" data=\"$(encode_tx)\"]\n\n    decode_log -> decode_cbor -> fetch -> parse -> multiply -> encode_data -> encode_tx -> submit_tx\n\"\"\"\n```\n\n```text\nGas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? Returned error: {\"jsonrpc\":\"2.0\",\"error\":\"invalid opcode: PUSH0\", \"id\":2405507186007008}\n```\n\n```text\nLinkToken\n```\n\n```text\noperator\n```\n\n```text\noperator\n```\n\n```text\nLinkToken\n```\n\n```text\nOperator\n```\n\n```text\nATestnetConsumer\n```\n\n```js\n// hardhat.config.ts\nsolidity: {\n    compilers: [\n        {\n            version: '0.8.20',\n            settings: {\n                evmVersion: 'paris'\n            }\n        }\n    ]\n}\n```\n\n```text\nevm_version = 'paris'\n```\n\n```text\n0.8.20\n```\n\n```text\nPUSHO\n```\n\n```text\nPUSH0\n```\n\n```text\nsolc --evm-version <VERSION> <CONTRACT>\n```\n\n```text\nsolc --evm-version paris contract.sol\n```\n\n```text\nfoundry.toml\n```\n\n========================================\n\nComments:\n- Thanks, it struck me that the 0.8.20 Solidity compiler only support testnet like goerli and sepolia, but not my private chain. I changed the version of the compiler to v0.8.7 in Remix and the problem also got solved.\n- For me, changing the evmVersion to paris to deploy on arbitrum gave this error: Invalid EVM version requested.","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":364,"estimatedTokens":2983}}7{"id":"stack-74357397","source":"stackoverflow","questionId":74357397,"title":"How to aggregate multiple smart contract function calls on Rootstock?","tags":["javascript","solidity","ethers.js","rsk"],"text":"Title: How to aggregate multiple smart contract function calls on Rootstock?\nTags: javascript, solidity, ethers.js, rsk\nSource: Stack Overflow\n\nQuestion:\nI have multiple ERC20 tokens, deployed on Rootstock,\nand I want to track their balances and allowances in a real time from my DApp.\nIn ethers.js,\nI *can* track their balances by alternately calling the functions\n`balanceOf(address)` and `allowance(owner, spender)`.\nHowever, across two tokens, that equates to about\n4 JSON-RPC requests every ~30 seconds.\n\nI would prefer to reduce the frequency of JSON-RPC requests made by my application,\nby aggregating these particular requests.\n\nIs it possible to *combine* multiple smart contract data queries\ninto a single JSON-RPC request via `ethers.js` or any other library?\n\n========================================\n\nTop Answer:\nYou could use the `ethereum-multicall` project,\nwhich consists of:\n\n- Frontend library which connects to\n\n- Multicall3 smart contract\n\n### Smart contract deployments:\n\nThe advantage of this project is that both Rootstock Mainnet and Rootstock Testnet have the `Multicall3` deployments:\n\n- Mainnet `0xcA11bde05977b3631167028862bE2a173976CA11`\n\n- Testnet `0xcA11bde05977b3631167028862bE2a173976CA11`\n\n... and bonus points for the `0xca11...ca11` vanity address ;)\n\n### To make aggregated smart contract calls:\n\n- Install the npm package:\n\n```\nnpm i ethereum-multicall\n```\n\n- Import the library to your project:\n\n```\nconst { Multicall } = require('ethereum-multicall');\n```\n\n- Create Multicall instance and connect it to ethers.js provider\n\n```\nconst multicall = new Multicall({\n ethersProvider: ethersProvider,\n tryAggregate: true,\n});\n```\n\n- Create aggregated call:\n\n```\nconst aggregatedCall = [\n {\n reference: 'token1',\n contractAddress: token1Address,\n abi: token1ABI,\n calls: [\n {\n methodName: 'balanceOf',\n methodParameters: [walletAddress],\n },\n {\n methodName: 'allowance',\n methodParameters: [ownerAddress, spenderAddress],\n },\n ],\n },\n {\n reference: 'token2',\n contractAddress: token2Address,\n abi: token2ABI,\n calls: [\n {\n methodName: 'balanceOf',\n methodParameters: [walletAddress],\n },\n {\n methodName: 'allowance',\n methodParameters: [ownerAddress, spenderAddress],\n },\n ],\n },\n ];\n const { results } = await multicall.call(aggregatedCall);\n```\n\n- Extract the required data from the `results` object\n\n========================================\n\nCode:\n```text\nbalanceOf(address)\n```\n\n```text\nallowance(owner, spender)\n```\n\n```text\nethers.js\n```\n\n```bash\nnpm i @0xsequence/multicall\n```\n\n```js\nconst { providers } = require('@0xsequence/multicall');\n```\n\n```js\nconst multicallConfig = {\n  // RSK Testnet\n  31: {\n    // maximum number of calls to batch into a single JSON-RPC call\n    batchSize: 50,\n    // defines the time each call is held on buffer waiting for subsequent calls before aggregation, ms\n    timeWindow: 50,\n    // MultiCallUtils smart contract\n    contract: '0xb39d1Dea1bF91Aef02484F677925904b9d6936B4',\n  },\n};\n```\n\n```js\nconst multicallProvider = new providers.MulticallProvider(ethersProvider, multicallConfig[31]);\n```\n\n```js\nconst token1 = new ethers.Contract(\n    token1Address,\n    token1ABI,\n    multicallProvider,\n  );\nconst token2 = ...\n```\n\n```js\nfunction makeAggregatedCall() {\n  const aggregatedCall = [\n    multicallProvider.getBalance(address),\n    token1.balanceOf(address),\n    token1.allowance(owner, spender),\n    token2.balanceOf(address),\n    token2.allowance(owner, spender),\n  ];\n  [\n    rbtcBalance,\n    balance1,\n    allowance1,\n    balance2,\n    allowance2,\n  ] = await Promise.all(aggregatedCall);\n}\n```\n\n```js\nethersProvider.on('block', makeAggregatedCall);\n```\n\n```text\n@0xsequence/multicall\n```\n\n```text\nmultiCall()\n```\n\n```text\nMultiCallUtils\n```\n\n```text\n0xb39d1Dea1bF91Aef02484F677925904b9d6936B4\n```\n\n```text\nMultiCallUtils\n```\n\n```text\nmultiCall()\n```\n\n```text\nmakeAggregatedCall\n```\n\n```text\nblock\n```\n\n```bash\nnpm i ethereum-multicall\n```\n\n```js\nconst { Multicall } = require('ethereum-multicall');\n```\n\n```js\nconst multicall = new Multicall({\n    ethersProvider: ethersProvider,\n    tryAggregate: true,\n});\n```\n\n```js\nconst aggregatedCall = [\n    {\n      reference: 'token1',\n      contractAddress: token1Address,\n      abi: token1ABI,\n      calls: [\n        {\n          methodName: 'balanceOf',\n          methodParameters: [walletAddress],\n        },\n        {\n          methodName: 'allowance',\n          methodParameters: [ownerAddress, spenderAddress],\n        },\n      ],\n    },\n    {\n      reference: 'token2',\n      contractAddress: token2Address,\n      abi: token2ABI,\n      calls: [\n        {\n          methodName: 'balanceOf',\n          methodParameters: [walletAddress],\n        },\n        {\n          methodName: 'allowance',\n          methodParameters: [ownerAddress, spenderAddress],\n        },\n      ],\n    },\n  ];\n  const { results } = await multicall.call(aggregatedCall);\n```\n\n```text\nethereum-multicall\n```\n\n```text\nMulticall3\n```\n\n```text\n0xcA11bde05977b3631167028862bE2a173976CA11\n```\n\n```text\n0xcA11bde05977b3631167028862bE2a173976CA11\n```\n\n```text\n0xca11...ca11\n```\n\n```text\nresults\n```\n\n========================================\n\nComments:\n- you can find the full source code in the repo.\n- Find the source code in a repo","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":287,"estimatedTokens":1308}}8{"id":"stack-68422733","source":"stackoverflow","questionId":68422733,"title":"How do I convert a uint256 variable to an int256 one?","tags":["solidity","smartcontracts","chainlink"],"text":"Title: How do I convert a uint256 variable to an int256 one?\nTags: solidity, smartcontracts, chainlink\nSource: Stack Overflow\n\nQuestion:\nI was trying to print `uint timeStamp` by typing `return timeStamp;` right below `return price;` from this code:\n\n```\npragma solidity ^0.6.7;\n\nimport \"@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol\";\n\ncontract PriceConsumerV3 {\n\nAggregatorV3Interface internal priceFeed;\n\n/**\n * Network: Kovan\n * Aggregator: BTC/USD\n * Address: 0x6135b13325bfC4B00278B4abC5e20bbce2D6580e\n */\nconstructor() public {\n priceFeed = AggregatorV3Interface(0x6135b13325bfC4B00278B4abC5e20bbce2D6580e);\n}\n\n/**\n * Returns the latest price\n */\nfunction getThePrice() public view returns (int) {\n (\n uint80 roundID, \n int price,\n uint startedAt,\n uint timeStamp,\n uint80 answeredInRound\n ) = priceFeed.latestRoundData();\n return price;\n return timeStamp;\n}\n}\n```\n\nWhen I compiled the code above on the Remix Compiler, it replied:\n\nTypeError: Return argument type uint256 is not implicitly convertible to expected type (type of first return variable) int256. return timeStamp; ^-------^\n\nI tend to think that I would just have to type `int256 return timeStamp` or something similar instead of `return timeStamp;` but I can't figure it out.\n\nFeedback is appreciated.\n\n========================================\n\nCode:\n```text\npragma solidity ^0.6.7;\n\nimport \"@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol\";\n\ncontract PriceConsumerV3 {\n\nAggregatorV3Interface internal priceFeed;\n\n/**\n * Network: Kovan\n * Aggregator: BTC/USD\n * Address: 0x6135b13325bfC4B00278B4abC5e20bbce2D6580e\n */\nconstructor() public {\n    priceFeed = AggregatorV3Interface(0x6135b13325bfC4B00278B4abC5e20bbce2D6580e);\n}\n\n/**\n * Returns the latest price\n */\nfunction getThePrice() public view returns (int) {\n    (\n        uint80 roundID, \n        int price,\n        uint startedAt,\n        uint timeStamp,\n        uint80 answeredInRound\n    ) = priceFeed.latestRoundData();\n    return price;\n    return timeStamp;\n}\n}\n```\n\n```text\nuint timeStamp\n```\n\n```text\nreturn timeStamp;\n```\n\n```text\nreturn price;\n```\n\n```text\nint256 return timeStamp\n```\n\n```text\nreturn timeStamp;\n```\n\n```text\nreturn int(timeStamp);\n```\n\n```text\n(\n    uint80 roundID, \n    int price,\n    uint startedAt,\n    uint timeStamp,\n    uint80 answeredInRound\n) = priceFeed.latestRoundData();\nreturn price; // the `price` is returned, and the function doesn't execute after this line\nreturn timeStamp; // this is ignored because of the early return on previous line\n```\n\n```text\n// note the multiple datatypes in the `returns` block\nfunction getThePriceAndTimestamp() public view returns (int, uint) {\n    (\n        uint80 roundID, \n        int price,\n        uint startedAt,\n        uint timeStamp,\n        uint80 answeredInRound\n    ) = priceFeed.latestRoundData();\n    return (price, timeStamp); // here returning multiple values\n}\n```\n\n```text\nuint\n```\n\n```text\nint\n```\n\n```text\n2^255\n```\n\n```text\nint\n```\n\n```text\n2^256-1\n```\n\n```text\nuint\n```\n\n```text\nprice\n```\n\n========================================\n\nComments:\n- Oh, btw, does the above mean the return statement can only be used once per function declared?\n- You can use multiple returns. It makes sense in a conditional return (example: `if(user.isActive == false) { return 0; } else { return user.score; }`) ... Just in your particular case the second would be **always** ignored.\n- @PetrHejda I think you meant to say `2^255` instead of `2^255-1` in the note about the Solidity v0.8 exception? `2^255-1` is `type(int256).max`, and so it fits within `int256`.\n- @PaulRazvanBerg Yes, that was my miscalculation. Thank you, I fixed in in the post.","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":173,"estimatedTokens":923}}9{"id":"stack-69717376","source":"stackoverflow","questionId":69717376,"title":"Send a transaction from Zero Address","tags":["ethereum","solidity"],"text":"Title: Send a transaction from Zero Address\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI am writing and testing a smart contract. Using web3, I could not send a transaction from a **Zero Address** (0x0). I was wondering if it is ever possible to sign and send a transaction using the zero address. In effect the `msg.sender` in the function should be the zero address.\n\nIn other words, can this require statement any time return `true` ?\n\n```\nrequire(msg.sender == address(0))\n```\n\nFrom what I understand:\n\n- A contract A cannot call another contract B's function using a zero address. The `msg.sender` in contract B's function will always be contract A's sender.\n\n- It is not possible to generate a zero address as one of the addresses in an ethereum wallet. It will also be impossible to figure out the private key associated with the zero address.\n\nIs there something wrong with my understandings or something that I am missing ?\n\nThanks in advance for your help.\n\n========================================\n\nCode:\n```text\nrequire(msg.sender == address(0))\n```\n\n```text\nmsg.sender\n```\n\n```text\ntrue\n```\n\n```text\nmsg.sender\n```\n\n```text\nrequire(msg.sender == address(0))\n```\n\n```text\nrequire(block.timestamp == 0)\n```\n\n```text\nmsg.sender\n```\n\n```text\nTransfer()\n```\n\n```text\n0x0\n```\n\n```text\n0x0\n```\n\n```text\nmsg.sender\n```\n\n```text\n0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF\n```\n\n========================================\n\nComments:\n- hmm! 33 million dollars as of now, it is worth building a quantum computer and run a scanner to find out if such private key (for address(0)) exists","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":78,"estimatedTokens":400}}10{"id":"stack-71036736","source":"stackoverflow","questionId":71036736,"title":"How to fix / debug errors (invalid arrayify value) when deploying a solidity contract in Remix","tags":["blockchain","ethereum","solidity","smartcontracts","remix"],"text":"Title: How to fix / debug errors (invalid arrayify value) when deploying a solidity contract in Remix\nTags: blockchain, ethereum, solidity, smartcontracts, remix\nSource: Stack Overflow\n\nQuestion:\n### Problem\n\nI am trying to deploy a smart contract via Remix. Unfortunately, it fails with a very unhelpful error message.\n\n### Error Message\n\ncreation of MyContract errored: Error encoding arguments: Error: invalid arrayify value (argument=\"value\", value=\"\", code=INVALID_ARGUMENT, version=bytes/5.5.0)\n\n### Code\n\nHere is the constructor the `contract` uses:\n\n```\nstruct RRSet {\n uint32 inception;\n uint32 expiration;\n bytes20 hash;\n}\n\nconstructor(bytes memory _anchors) {\n // Insert the 'trust anchors' - the key hashes that start the chain\n // of trust for all other records.\n anchors = _anchors;\n rrsets[keccak256(hex\"00\")][DNSTYPE_DS] = RRSet({\n inception: uint32(0),\n expiration: uint32(3767581600), // May 22 2089 - the latest date we can encode as of writing this\n hash: bytes20(keccak256(anchors))\n });\n emit RRSetUpdated(hex\"00\", anchors);\n}\n```\n\n### Some thoughts\n\nMy contract uses `is` to inherit from an abstract contract as wells as from a regular contract. Is there a way to see where to error or originates from or is there a possiblity to debug it?\n\n========================================\n\nCode:\n```text\nstruct RRSet {\n    uint32 inception;\n    uint32 expiration;\n    bytes20 hash;\n}\n\nconstructor(bytes memory _anchors) {\n    // Insert the 'trust anchors' - the key hashes that start the chain\n    // of trust for all other records.\n    anchors = _anchors;\n    rrsets[keccak256(hex\"00\")][DNSTYPE_DS] = RRSet({\n        inception: uint32(0),\n        expiration: uint32(3767581600), // May 22 2089 - the latest date we can encode as of writing this\n        hash: bytes20(keccak256(anchors))\n    });\n    emit RRSetUpdated(hex\"00\", anchors);\n}\n```\n\n```text\ncontract\n```\n\n```text\nis\n```\n\n```text\n[]\n```\n\n```text\n0x\n```\n\n========================================\n\nComments:\n- It seems like there's a constructor requiring some parameters but you're passing empty or incorrectly formatted values. Can you the constructor code and what you're passing to it?\n- I updated the code with the constructor","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":85,"estimatedTokens":552}}11{"id":"stack-53499997","source":"stackoverflow","questionId":53499997,"title":"Solidity, Member \"transfer\" not found or not visible after argument-dependent","tags":["ethereum","solidity","smartcontracts"],"text":"Title: Solidity, Member \"transfer\" not found or not visible after argument-dependent\nTags: ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nUsing Solidity ^0.5.0, \nI'm actually trying to implement an old code working in ^0.4.17, but it throws an error on Remix.\nI checked syntax and everything but just can't catch what's wrong.\nAny help highly appreciated.\n\n```\npragma solidity ^0.5.0;\n\ncontract Lottery{\n address public manager;\n address[] public players;\n\n constructor() public {\n manager = msg.sender;\n }\n\n function participate() public payable {\n require(msg.value > .01 ether);\n players.push(msg.sender);\n }\n\n function pseudoRandom() private view returns(uint){\n return uint(keccak256(abi.encodePacked(block.difficulty, now, players)));\n }\n\n function pickWinner() public {\n uint index = pseudoRandom() % players.length;\n players[index].transfer(address(this).balance);\n }\n}\n```\n\nHere is the error message: \n\nbrowser/Lottery.sol:22:8: TypeError: Member \"transfer\" not found or not visible after argument-dependent \nlookup in address.\n\nplayers[index].transfer(address(msg.sender).balance);\n\n^---------------------^\n\n========================================\n\nTop Answer:\nYou are missing the payable modifier on the initial declaration. \nChange \n\n address[] public players;\n\nto \n\n address payable[] public players;\n\n========================================\n\nCode:\n```text\npragma solidity ^0.5.0;\n\ncontract Lottery{\n  address public manager;\n  address[] public players;\n\n  constructor() public {\n      manager = msg.sender;\n  }\n\n   function participate() public payable {\n       require(msg.value > .01 ether);\n       players.push(msg.sender);\n  }\n\n   function pseudoRandom() private view returns(uint){\n    return uint(keccak256(abi.encodePacked(block.difficulty, now, players)));\n  }\n\n  function pickWinner() public {\n    uint index = pseudoRandom() % players.length;\n    players[index].transfer(address(this).balance);\n  }\n}\n```\n\n```text\naddress[] public players;\n```\n\n```text\naddress payable[] public players;\n```\n\n```text\naddress payable winnerAddress = payable(players[index]);\n    winnerAddress.transfer(address(this).balance);\n```\n\n```text\n// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.9;\n\ncontract Lottery {\n    address public manager;\n    address payable[] public players;\n    \n    constructor() { }\n\n    function lottery() public {\n        manager = msg.sender;\n    }\n\n    function enter() public payable {\n        require(msg.value > .01 ether);\n        players.push(payable(msg.sender));\n    }\n\n    function random() public view returns (uint8) {\n        return uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, players)))%251);\n    }\n\n    function pickWinner() public {\n        uint index = random() % players.length;\n        players[index].transfer(address(this).balance);\n    }\n}\n```\n\n========================================\n\nComments:\n- This answer was accepted, but I don't think it's the actual issue in the above code. `players[index]` was already an `address`, so casting it doesn't do anything. I believe the actual issue is that the type is `address` rather than `address payable`. The fix would be to use `address payable[] public players`.","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":135,"estimatedTokens":806}}12{"id":"stack-53331100","source":"stackoverflow","questionId":53331100,"title":"Solidity: Storing JSON data. Any advantage in using a Struct type vs a String?","tags":["ethereum","solidity"],"text":"Title: Solidity: Storing JSON data. Any advantage in using a Struct type vs a String?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI must store JSON formatted data in my Solidity contract. I don't need to do any operations on the data. I simply need to store it, update it, and return it.\n\nLet's say I have JSON formatted data such as:\n\n```\n{'name': 'Nike', 'size':'12', 'color':'blue'}\n```\n\nI'm currently passing the data to the constructor as a string:\n\n```\nconstructor(string _data) public {\n data = _data;\n}\n```\n\nAnd updating the data by simply replacing the entire string:\n\n```\nfunction updateData(string _data) public {\n data = _data;\n}\n```\n\nI'm debating whether I should create a Struct type, named say \"Shoe\", and pass each property as an argument:\n\n```\nconstructor(string _name, uint size, string _color) public {\n Shoe memory newShoe = Shoe({\n name: _name,\n size: _size,\n color: _color\n })\n\n data = newShoe;\n}\n```\n\nI'll never need to store more than one shoe object, and it seems much simpler and easier to pass the data as a *String*, but I'm wondering if there's an advantage to using a *Struct* type.\n\n========================================\n\nCode:\n```text\n{'name': 'Nike', 'size':'12', 'color':'blue'}\n```\n\n```text\nconstructor(string _data) public {\n  data = _data;\n}\n```\n\n```text\nfunction updateData(string _data) public {\n  data = _data;\n}\n```\n\n```text\nconstructor(string _name, uint size, string _color) public {\n  Shoe memory newShoe = Shoe({\n    name: _name,\n    size: _size,\n    color: _color\n  })\n\n  data = newShoe;\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":75,"estimatedTokens":390}}13{"id":"stack-69364457","source":"stackoverflow","questionId":69364457,"title":"How to query the expiry date for an RNS domain?","tags":["solidity","rsk"],"text":"Title: How to query the expiry date for an RNS domain?\nTags: solidity, rsk\nSource: Stack Overflow\n\nQuestion:\nIn addition to direct queries, I'd also like to subscribe to events to listen for whenever the expiry date changes (e.g. when it is renewed)\n\nI've found that `NodeOwner.sol` has an\n`available` function\nwhose implementation looks promising:\n\n```\nfunction available(uint256 tokenId) public view returns(bool) {\n return expirationTime[tokenId] and that same file also defines an\n`ExpirationChanged` event:\n\n```\nevent ExpirationChanged(uint256 tokenId, uint expirationTime);\n```\n\nWhat I haven't been able to figure out is:\n\n- How to get the `NodeOwner` - which contract/ address should be queried?\n\n- If there are multiple possible addresses/ instances of `NodeOwner`, or there's only one of them.\n\n========================================\n\nCode:\n```text\nfunction available(uint256 tokenId) public view returns(bool) {\n        return expirationTime[tokenId] < now;\n    }\n```\n\n```text\nevent ExpirationChanged(uint256 tokenId, uint expirationTime);\n```\n\n```text\nNodeOwner.sol\n```\n\n```text\navailable\n```\n\n```text\nExpirationChanged\n```\n\n```text\nNodeOwner\n```\n\n```text\nNodeOwner\n```\n\n```js\nconst rskOwner = new web3.eth.Contract(rskOwnerAbi, rskOwnerAddress);\n\nconst hash = `0x${sha3('testing')}`;\n\nrskOwner.methods.expirationTime(hash).call((error, result) => {\n    console.log('expires at: ', result)\n})\n```\n\n```text\nRSKOwner\n```\n\n```text\nexpirationTime\n```\n\n```text\n0x45d3E4fB311982a06ba52359d44cB4f5980e0ef1\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":80,"estimatedTokens":379}}14{"id":"stack-68314316","source":"stackoverflow","questionId":68314316,"title":"What is the max size of a smart contract on the RSK network?","tags":["java","solidity","rsk"],"text":"Title: What is the max size of a smart contract on the RSK network?\nTags: java, solidity, rsk\nSource: Stack Overflow\n\nQuestion:\nDoes RSK have a maximum size of a compiled smart contract? If so, what is the max size of the byte code that can be deployed?\n\n========================================\n\nCode:\n```java\npublic static int getMaxContractSize() {\n        return 0x6000;\n    }\n```\n\n```java\nprivate void createContract() {\n        int createdContractSize = getLength(program.getResult().getHReturn());\n        long returnDataGasValue = GasCost.multiply(GasCost.CREATE_DATA, createdContractSize);\n        if (mEndGas < returnDataGasValue) {\n            program.setRuntimeFailure(\n                    Program.ExceptionHelper.notEnoughSpendingGas(\n                            program,\n                            \"No gas to return just created contract\",\n                            returnDataGasValue));\n            result = program.getResult();\n            result.setHReturn(EMPTY_BYTE_ARRAY);\n        } else if (createdContractSize > Constants.getMaxContractSize()) {\n            program.setRuntimeFailure(\n                    Program.ExceptionHelper.tooLargeContractSize(\n                            program,\n                            Constants.getMaxContractSize(),\n                            createdContractSize));\n            result = program.getResult();\n            result.setHReturn(EMPTY_BYTE_ARRAY);\n        } else {\n            mEndGas = GasCost.subtract(mEndGas,  returnDataGasValue);\n            program.spendGas(returnDataGasValue, \"CONTRACT DATA COST\");\n            cacheTrack.saveCode(tx.getContractAddress(), result.getHReturn());\n        }\n    }\n```\n\n```text\n24567\n```\n\n```text\nConstants#getMaxContractSize()\n```\n\n```text\nTransactionExecutor#createContract()\n```\n\n```text\n(createdContractSize > Constants.getMaxContractSize())\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":59,"estimatedTokens":464}}15{"id":"stack-49205032","source":"stackoverflow","questionId":49205032,"title":"Gas requirement of function high: infinite","tags":["ethereum","solidity","web3js"],"text":"Title: Gas requirement of function high: infinite\nTags: ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nBelow is my smart contract. When I put it in remix, I get warnings on each of the following functions.\n\nGas requirement of function MedicalRecord.addNote(bytes32,bytes32) high: infinite.\n\nGas requirement of function MedicalRecord.getDoctorsNames() high: infinite.\n\nGas requirement of function MedicalRecord.getNotes() high: infinite.\n\nGas requirement of function MedicalRecord.giveDoctorAccess(address,bytes32) high: infinite.\n\n```\npragma solidity ^0.4.17;\n\ncontract MedicalRecord {\nstruct Doctor {\n bytes32 name;\n uint id;\n}\n\nstruct Note {\n bytes32 title;\n bytes32 note;\n}\n\naddress public patient;\nuint private doctorId;\nbytes32[] public doctorsNames;\nNote[] notes;\nmapping (address => Doctor) private doctors;\n\nmodifier onlypatient {\n require(msg.sender == patient);\n _;\n}\n\nmodifier isCurrentDoctor {\n require(!(doctors[msg.sender].id Can anyone tell me how I can improve this?\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.17;\n\n\ncontract MedicalRecord {\nstruct Doctor {\n    bytes32 name;\n    uint id;\n}\n\nstruct Note {\n    bytes32 title;\n    bytes32 note;\n}\n\naddress public patient;\nuint private doctorId;\nbytes32[] public doctorsNames;\nNote[] notes;\nmapping (address => Doctor) private doctors;\n\nmodifier onlypatient {\n    require(msg.sender == patient);\n    _;\n}\n\nmodifier isCurrentDoctor {\n    require(!(doctors[msg.sender].id < doctorId));\n    _;\n}\n\nfunction MedicalRecord() public {\n    patient = msg.sender;\n    doctorId = 0;\n}\n\nfunction giveDoctorAccess(address drAddress, bytes32 name)\npublic\nonlypatient\nreturns (bytes32)\n{\n    doctors[drAddress] = Doctor (name, doctorId);\n    doctorId++;\n    doctorsNames.push(name);\n    return (name);\n}\n\nfunction getNotes()\n    view\n    public\n    isCurrentDoctor\n    returns (bytes32[], bytes32[])\n{\n    bytes32[] memory titles = new bytes32[](notes.length);\n    bytes32[] memory noteTexts = new bytes32[](notes.length);\n    \n    for (uint i = 0; i < notes.length; i++) {\n        Note storage snote = notes[i];\n        titles[i] = snote.title;\n        noteTexts[i] = snote.note;\n    }\n    \n    return (titles, noteTexts);\n}\n\nfunction getDoctorsNames() view public returns (bytes32[]) {\n    return doctorsNames;\n}\n\nfunction addNote(bytes32 title, bytes32 note) public isCurrentDoctor \n{\n    notes.push(Note({title: title, note:note}));\n}\n}\n```\n\n```text\ndoctorNames\n```\n\n```text\nDoctor\n```\n\n```text\ngetNotes()\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":133,"estimatedTokens":628}}16{"id":"stack-71730554","source":"stackoverflow","questionId":71730554,"title":"Solidity \"Function needs to specify overridden contract\" question","tags":["inheritance","blockchain","ethereum","solidity","smartcontracts"],"text":"Title: Solidity \"Function needs to specify overridden contract\" question\nTags: inheritance, blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI'm a newbie in Solidity, and I have a question about multiple inheritances.\n\nSo if I have some contracts like:\n\n```\ncontract A {\n\n function foo() public virtual {\n console.log(\"A\");\n }\n}\n\ncontract B is A {\n function foo() public virtual override {\n console.log(\"B\");\n }\n}\n\ncontract C is A, B {\n function foo() public override(A, B) {\n super.foo();\n }\n}\n```\n\nThe `foo` function of contract C must be `override(A, B)` insdead `override(B)`\n\nor it'd throw an error like `Function needs to specify overridden contract \"A\".`\n\nSo here's the question, The function must specify the full inheritance parents.\n\nWhy can't it know the information by `contract C is A, B`,\n\nI mean, what's the point? The `overrider(A,B)` part is unnecessary.\n\nOr there are some tricks I don't know?\n\nPlease give me an answer, so curious and can't find some useful information by docs.\n\n========================================\n\nTop Answer:\noverriding implies that you're reimplementing a method you inherited!. So when you call this function inside child class, this reimplemented version of function will be called.\n\nIf you were just calling that function without reimplementing inside child class, you could call it because of this code:\n\n```\ncontract B is A {}\n```\n\nIf you call a method that is not defined in B, compiler will check contract A and it finds it will call it.\n\n========================================\n\nCode:\n```text\ncontract A {\n\n    function foo() public virtual {\n        console.log(\"A\");\n    }\n}\n\ncontract B is A {\n    function foo() public virtual override {\n        console.log(\"B\");\n    }\n}\n\ncontract C is A, B {\n    function foo() public override(A, B) {\n        super.foo();\n    }\n}\n```\n\n```text\nfoo\n```\n\n```text\noverride(A, B)\n```\n\n```text\noverride(B)\n```\n\n```text\nFunction needs to specify overridden contract \"A\".\n```\n\n```text\ncontract C is A, B\n```\n\n```text\noverrider(A,B)\n```\n\n```text\noverride\n```\n\n```text\noverride\n```\n\n```text\ncontract B is A {}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":116,"estimatedTokens":532}}17{"id":"stack-43857452","source":"stackoverflow","questionId":43857452,"title":"Truffle console variable declaration","tags":["ethereum","solidity","truffle"],"text":"Title: Truffle console variable declaration\nTags: ethereum, solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nI'm currently following this tutorial (https://medium.com/zeppelin-blog/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05) as I try to get into ethereum programming.\nStep 3 is interacting with the deployed contract.\n\nWhen I enter\n\n```\ntruffle(default)> var poe = ProofOfExistence1.deployed()\n```\n\nI get \"undefined\" as a result and cannot interact with the following commands as well. I definitely deployed the contract, because\n\n```\ntruffle(development)> ProofOfExistence1.deployed()\n```\n\ngets me output and lists me all functions inside the contract etc.\ntried it with testrpc and geth testnet so I guess it's got something to do with truffle?\n\n========================================\n\nTop Answer:\nTo interact with the deployed contracts, you have to type in truffle console:\n\n```\ntruffle ProofOfExistence1.at(\"copy its address after the migration\").function name();\n```\n\n========================================\n\nCode:\n```text\ntruffle(default)> var poe = ProofOfExistence1.deployed()\n```\n\n```text\ntruffle(development)> ProofOfExistence1.deployed()\n```\n\n```text\ntruffle(development)> ProofOfExistence1.deployed().then(function(a) { poe = a; })\n...\ntruffle(development)> poe.address\n```\n\n```text\n.deployed()\n```\n\n```text\nPromise\n```\n\n```text\ntruffle<development)> ProofOfExistence1.at(\"copy its address after the migration\").function name();\n```\n\n```text\ntruffle(development)> poe = ProofOfExistence1.at(ProofOfExistence1.address)\n```\n\n========================================\n\nComments:\n- A lot of tutorials around the web are still showing how to get the instance for the truffle version 2. This was updated with version 3. For the MetaCoin example, you can use: var meta;MetaCoin.deployed().then(a => { meta = a; })","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":69,"estimatedTokens":462}}18{"id":"stack-51757569","source":"stackoverflow","questionId":51757569,"title":"How solidity make function signature with tuple(nested abi)?","tags":["solidity","abi"],"text":"Title: How solidity make function signature with tuple(nested abi)?\nTags: solidity, abi\nSource: Stack Overflow\n\nQuestion:\n```\nstruct Test {\n uint ui;\n string s;\n}\nfunction test(Test t) public {\n emit Log(t.ui, t.s);\n}\n```\n\nI have some knowledge about ABI. I made this contract with experimental ABIEncoderV2 option. In conclusion, this function's signature is 0x6056f4cc, I found this value in opcode. I tried some case test(uint256,string), test(tuple(uint256,string)), test(tuple), test(tuple[uint256,string])) with sha3... but no one make correct signature. How solidity make function signature with tuple?\n\n========================================\n\nCode:\n```text\nstruct Test {\n  uint ui;\n  string s;\n}\nfunction test(Test t) public {\n  emit Log(t.ui, t.s);\n}\n```\n\n```text\nbytes4(keccak256(\"test((uint256,string))\"): 6056f4cc\n```\n\n```text\ntest((uint256,string))\n```\n\n========================================\n\nComments:\n- Here's the online encoder if you need one: piyolab.github.io/playground/ethereum/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":42,"estimatedTokens":253}}19{"id":"stack-49937566","source":"stackoverflow","questionId":49937566,"title":"Filter out empty address in web3.js","tags":["ethereum","solidity","web3js"],"text":"Title: Filter out empty address in web3.js\nTags: ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nHow to detect empty address that has initial value of `0x0000000000000000000000000000000000000000` in web3.js?\n\nWhat I'm doing now is:\n\n```\nif (address !== '0x0000000000000000000000000000000000000000') {\n ...\n}\n```\n\nIs there any simpler way to filter out empty addresses or a helper method in web3 that can create this value(like `address(0)` in Solidity)? It's quite bothering to count(or type) exact number of all that `0`s.\n\n========================================\n\nTop Answer:\nYou could also use OpenZeppelin's Test Helpers.\n\nThey have a constant called `ZERO_ADDRESS` which equals to zero address you mentioned.\n\nMore Info Here\n\n**Usage**\n\nFirst, you need to install:\n\n```\nnpm install @openzeppelin/test-helpers\n```\n\nIn JS file:\n\n```\nconst constants = require('@openzeppelin/test-helpers');\n\nconsole.log(constants.ZERO_ADDRESS);\n```\n\n========================================\n\nCode:\n```text\nif (address !== '0x0000000000000000000000000000000000000000') {\n   ...\n}\n```\n\n```text\n0x0000000000000000000000000000000000000000\n```\n\n```text\naddress(0)\n```\n\n```text\n0\n```\n\n```javascript\nconst emptyAddress = /^0x0+$/.test(address);\n```\n\n```text\nweb3.toBigNumber(address).isZero()\n```\n\n```sh\nnpm install @openzeppelin/test-helpers\n```\n\n```js\nconst constants = require('@openzeppelin/test-helpers');\n\nconsole.log(constants.ZERO_ADDRESS);\n```\n\n```text\nZERO_ADDRESS\n```\n\n========================================\n\nComments:\n- Maybe `web3.toBigNumber(address).isZero()`?\n- @smarx Really nice to know that web3 depends on BigNumber library. Why couldn't I think this way.. brilliant.\n- You could post it as an answer and I can mark it accepted. Seems like your suggestion is the best I can think of so far.\n- Nice one! I think `&#47;^0x0{40}$&#47;` may be clearer since an address in ethereum is 20 bytes 😎\n- Yeah I know, but if you use: `web3.toHex(0)` it will only give you `0x0`, who knows, if ethereum increase the address length, this code will still work ;)\n- Good catch. That would be a case where you generate an empty address in web3 side. Thanks.\n- Shouldn't it be `const {constants} = require('@openzeppelin&#47;test-helpers');`?","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":95,"estimatedTokens":560}}20{"id":"stack-71946498","source":"stackoverflow","questionId":71946498,"title":"How to get the returned data from a smart contract function using ethers.js?","tags":["reactjs","solidity","web3js","ethers.js","decentralized-applications"],"text":"Title: How to get the returned data from a smart contract function using ethers.js?\nTags: reactjs, solidity, web3js, ethers.js, decentralized-applications\nSource: Stack Overflow\n\nQuestion:\nI'm trying to consume a function from a smart contract using ethers.js. The function retrieve the info of a user logged before (with the help of other function). This is the function snippet.\n\n```\nfunction getUser(address _userAddress)\n public\n onlyAuthCaller\n returns (\n string memory name,\n string memory info,\n string memory role,\n )\n {\n User memory tmpData = userDetails[_userAddress];\n return (\n tmpData.name,\n tmpData.info,\n tmpData.role\n );\n }\n```\n\nWith React, I'm rendering a button to get user info, as :\n\n```\nconst GetUser = () => {\n const askUser = async () => {\n const provider = new ethers.providers.Web3Provider(window.ethereum);\n const account = await window.ethereum.request({\n method: \"eth_requestAccounts\",\n });\n const signer = provider.getSigner();\n const erc20 = new ethers.Contract(\n ContractAddress,\n ContractABI.abi,\n signer\n );\n\n try {\n const user = await erc20.getUser(account[0]);\n console.log(user);\n } catch (error) {\n console.log(\"ERROR AT GETTING USER: \", error);\n }\n };\n return (\n \n \n GET USER\n \n \n );\n};\n```\n\nI wonder why I'm not getting the return result of the smart contract `getUser` function, I expected that info at `const user` after awaiting the function. Instead on `const user`, I'm having the transaction metadata, as :\n\n```\n{hash: '0x24818569ec29d328b66f58736750a420a5a3bd8e28a72a6a0f72fd8ba5e088d8', type: 2, accessList: null, blockHash: null, blockNumber: null, …}\naccessList: null\nblockHash: null\nblockNumber: null\nchainId: 0\nconfirmations: 0\ncreates: null\ndata: \"0x6f77926b00000000000000000000000086b2b772014a87730928c7e54f4762d2c09ea4e5\"\nfrom: \"0x86b2b772014A87730928c7e54F4762d2c09eA4e5\"\ngasLimit: BigNumber {_hex: '0xd15f', _isBigNumber: true}\ngasPrice: BigNumber {_hex: '0x73a20d0c', _isBigNumber: true}\nhash: \"0x24818569ec29d328b66f58736750a420a5a3bd8e28a72a6a0f72fd8ba5e088d8\"\nmaxFeePerGas: BigNumber {_hex: '0x73a20d0c', _isBigNumber: true}\nmaxPriorityFeePerGas: BigNumber {_hex: '0x73a20d00', _isBigNumber: true}\nnonce: 5\nr: \"0x6a8fed76397e03a2fc564d18e1ec12abdf39a38fbe825df990f744bb50fc4a8b\"\ns: \"0x66e9b4513047b65aac724dc6fb07d069967f6ca6fd8cd5fe85f6dbe495864765\"\nto: \"0x9719E9dC77A7eDD3825844c77a68c896d4a7BB2b\"\ntransactionIndex: null\ntype: 2\nv: 0\nvalue: BigNumber {_hex: '0x00', _isBigNumber: true}\nwait: confirmations => {…}\nlength: 1\nname: \"\"\narguments: (…)\ncaller: (…)\n[[FunctionLocation]]: index.ts:336\n[[Prototype]]: ƒ ()\n[[Scopes]]: Scopes[4]\n[[Prototype]]: Object\n```\n\nWhen I tried my contract's functions on Remix IDE, all worked as expected. For instance, at Remix I get this answer, in which the data retrieved by the function is on `decoded output`.\n\n```\nstatus true Transaction mined and execution succeed\ntransaction hash 0x206af46a0f8e6bcc04ae632c85da005c901d8fc82f650e8d40a445f6988adcc2\nfrom 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4\nto SupplychainUser.getUser(address) 0xD7ACd2a9FD159E69Bb102A1ca21C9a3e3A5F771B\ngas 61639 gas\ntransaction cost 53599 gas \nexecution cost 53599 gas \ninput 0x6f7...35cb2\ndecoded input {\n \"address _userAddress\": \"0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2\"\n}\ndecoded output {\n \"0\": \"string: name Carl Bertz\",\n \"1\": \"string: info 0987654321\",\n \"2\": \"string: role processor\",\n}\nlogs []\nval 0 wei\n```\n\nI would like the same but with React, so how can I have the returned data from the contract `getUser` function?\n\n========================================\n\nTop Answer:\nyou want to be using callStatic on your contract, something like\n\n```\nawait erc20.callStatic.getUser(account[0])\n```\n\nso that you `call` the function, instead of running a `send` which executes the transaction (costing gas)\n\n========================================\n\nCode:\n```text\nfunction getUser(address _userAddress)\n        public\n        onlyAuthCaller\n        returns (\n            string memory name,\n            string memory info,\n            string memory role,\n        )\n    {\n        User memory tmpData = userDetails[_userAddress];\n        return (\n            tmpData.name,\n            tmpData.info,\n            tmpData.role\n        );\n    }\n```\n\n```text\nconst GetUser = () => {\n    const askUser = async () => {\n        const provider = new ethers.providers.Web3Provider(window.ethereum);\n        const account = await window.ethereum.request({\n            method: \"eth_requestAccounts\",\n        });\n        const signer = provider.getSigner();\n        const erc20 = new ethers.Contract(\n            ContractAddress,\n            ContractABI.abi,\n            signer\n        );\n\n        try {\n            const user = await erc20.getUser(account[0]);\n            console.log(user);\n        } catch (error) {\n            console.log(\"ERROR AT GETTING USER: \", error);\n        }\n    };\n    return (\n        <div>\n            <Button type=\"submit\" variant=\"contained\" onClick={askUser}>\n                GET USER\n            </Button>\n        </div>\n    );\n};\n```\n\n```text\n{hash: '0x24818569ec29d328b66f58736750a420a5a3bd8e28a72a6a0f72fd8ba5e088d8', type: 2, accessList: null, blockHash: null, blockNumber: null, …}\naccessList: null\nblockHash: null\nblockNumber: null\nchainId: 0\nconfirmations: 0\ncreates: null\ndata: \"0x6f77926b00000000000000000000000086b2b772014a87730928c7e54f4762d2c09ea4e5\"\nfrom: \"0x86b2b772014A87730928c7e54F4762d2c09eA4e5\"\ngasLimit: BigNumber {_hex: '0xd15f', _isBigNumber: true}\ngasPrice: BigNumber {_hex: '0x73a20d0c', _isBigNumber: true}\nhash: \"0x24818569ec29d328b66f58736750a420a5a3bd8e28a72a6a0f72fd8ba5e088d8\"\nmaxFeePerGas: BigNumber {_hex: '0x73a20d0c', _isBigNumber: true}\nmaxPriorityFeePerGas: BigNumber {_hex: '0x73a20d00', _isBigNumber: true}\nnonce: 5\nr: \"0x6a8fed76397e03a2fc564d18e1ec12abdf39a38fbe825df990f744bb50fc4a8b\"\ns: \"0x66e9b4513047b65aac724dc6fb07d069967f6ca6fd8cd5fe85f6dbe495864765\"\nto: \"0x9719E9dC77A7eDD3825844c77a68c896d4a7BB2b\"\ntransactionIndex: null\ntype: 2\nv: 0\nvalue: BigNumber {_hex: '0x00', _isBigNumber: true}\nwait: confirmations => {…}\nlength: 1\nname: \"\"\narguments: (…)\ncaller: (…)\n[[FunctionLocation]]: index.ts:336\n[[Prototype]]: ƒ ()\n[[Scopes]]: Scopes[4]\n[[Prototype]]: Object\n```\n\n```text\nstatus  true Transaction mined and execution succeed\ntransaction hash    0x206af46a0f8e6bcc04ae632c85da005c901d8fc82f650e8d40a445f6988adcc2\nfrom    0x5B38Da6a701c568545dCfcB03FcB875f56beddC4\nto  SupplychainUser.getUser(address) 0xD7ACd2a9FD159E69Bb102A1ca21C9a3e3A5F771B\ngas 61639 gas\ntransaction cost    53599 gas \nexecution cost  53599 gas \ninput   0x6f7...35cb2\ndecoded input   {\n    \"address _userAddress\": \"0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2\"\n}\ndecoded output  {\n    \"0\": \"string: name Carl Bertz\",\n    \"1\": \"string: info 0987654321\",\n    \"2\": \"string: role processor\",\n}\nlogs    []\nval 0 wei\n```\n\n```text\ngetUser\n```\n\n```text\nconst user\n```\n\n```text\nconst user\n```\n\n```text\ndecoded output\n```\n\n```text\ngetUser\n```\n\n```text\nfunction getUser(address _userAddress)\n        public\n        view\n        onlyAuthCaller\n        returns (\n            string memory name,\n            string memory info,\n            string memory role,\n        )\n    {\n        User memory tmpData = userDetails[_userAddress];\n        return (\n            tmpData.name,\n            tmpData.info,\n            tmpData.role\n        );\n    }\n```\n\n```text\ngetUser\n```\n\n```text\ngetUser\n```\n\n```text\nview\n```\n\n```text\nview\n```\n\n```text\ngetUser\n```\n\n```text\ngetUser\n```\n\n```text\nview\n```\n\n```text\nawait erc20.callStatic.getUser(account[0])\n```\n\n```text\ncall\n```\n\n```text\nsend\n```\n\n```text\ncall(g, a, v, in, insize, out, outsize)\n\ncall contract at address a with input mem[in…(in+insize)) providing g gas and v wei and output area mem[out…(out+outsize)) returning 0 on error (eg. out of gas) and 1 on success See more\n\n\ncallcode(g, a, v, in, insize, out, outsize)\n\nidentical to call but only use the code from a and stay in the context of the current contract otherwise See more\n\n\ndelegatecall(g, a, in, insize, out, outsize)\n\nidentical to callcode but also keep caller and callvalue See more\n\n\nstaticcall(g, a, in, insize, out, outsize)\n\nidentical to call(g, a, 0, in, insize, out, outsize) but do not allow state modifications See more\n```\n\n========================================\n\nComments:\n- Can I use `callStatic` with a no-view function?\n- Because my function is not declared as view, it can't be declared as such since it seems to be writing on `userDetails` (it's a mapping), otherwise, if I try to declare as view, I get an error on Remix related to this.\n- And I have another question, does `.callStatic` from ethers.js , does the same as `.call` from web3.js?","metadata":{"transformedAt":"2026-08-18T18:33:36.113Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":346,"estimatedTokens":2167}}21{"id":"stack-48603051","source":"stackoverflow","questionId":48603051,"title":"How to save and retrieve data on Ethereum blockchain with Solidity and Web.js","tags":["ethereum","solidity","web3js"],"text":"Title: How to save and retrieve data on Ethereum blockchain with Solidity and Web.js\nTags: ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nThe below code only returns a receipt but I want it to return a tuple of data, like in the contract below. How do I get it to return the data? I can't find a good tutorial on how to save and retrieve data. I know this is an expensive use case, I'm just trying to do a basic proof of concept and learn at the same time.\n\nI'm using web3@1.0.0-beta.29\n\n```\nexport class AppComponent {\n title = 'app';\n dappUrl: string = 'http://myapp.com';\n web3: any;\n contractHash: string = '0x3b8a60616bde6f6d251e807695900f31ab12ce1a';\n MyContract: any;\n contract: any;\n ABI: any = [{\"constant\":true,\"inputs\":[{\"name\":\"idx\",\"type\":\"uint256\"}],\"name\":\"getLocationHistory\",\"outputs\":[{\"name\":\"delegate\",\"type\":\"address\"},{\"name\":\"longitude\",\"type\":\"uint128\"},{\"name\":\"latitude\",\"type\":\"uint128\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"recentLocation\",\"outputs\":[{\"name\":\"delegate\",\"type\":\"address\"},{\"name\":\"longitude\",\"type\":\"uint128\"},{\"name\":\"latitude\",\"type\":\"uint128\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"longitude\",\"type\":\"uint128\"},{\"name\":\"latitude\",\"type\":\"uint128\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"name\":\"saveLocation\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"getLastLocation\",\"outputs\":[{\"components\":[{\"name\":\"delegate\",\"type\":\"address\"},{\"name\":\"longitude\",\"type\":\"uint128\"},{\"name\":\"latitude\",\"type\":\"uint128\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"name\":\"recentLocation\",\"type\":\"tuple\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"locations\",\"outputs\":[{\"name\":\"delegate\",\"type\":\"address\"},{\"name\":\"longitude\",\"type\":\"uint128\"},{\"name\":\"latitude\",\"type\":\"uint128\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"item\",\"outputs\":[{\"name\":\"id\",\"type\":\"bytes32\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"id\",\"type\":\"bytes32\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}];\n\n constructor(private route: ActivatedRoute) { }\n\n @HostListener('window:load')\n windowLoaded() {\n this.checkAndInstantiateWeb3();\n this.getLocation();\n }\n\n getLocationHistory() {\n this.MyContract.methods\n .getLocationHistory(0).send({\n 'from': '0x902D578B7E7866FaE71b3AB0354C9606631bCe03',\n 'gas': '44000'\n }).then((result) => {\n this.MyContract.methods.getLocationHistory(0).call()\n .then(hello => {console.log('hello', hello)});\n });\n }\n\n private checkAndInstantiateWeb3 = () => {\n if (typeof window.web3 !== 'undefined') {\n console.warn('Using web3 detected from external source.');\n // Use Mist/MetaMask's provider\n this.web3 = new Web3(window.web3.currentProvider);\n } else {\n console.warn(`No web3 detected. Falling back to http://localhost:8545.`);\n this.web3 = new Web3(\n new Web3.providers.HttpProvider('http://localhost:8545')\n );\n }\n\n this.MyContract = new this.web3.eth.Contract(this.ABI, this.contractHash);\n }\n\n private getLocation(): void {\n let query = this.route.snapshot.queryParams;\n\n if (query.action && query.action === 'setLocation') {\n this.setLocation();\n }\n\n }\n\n private setLocation(): void {\n navigator.geolocation.getCurrentPosition((position) => {\n\n this.MyContract.methods.saveLocation(\n position.coords.longitude, position.coords.latitude, window.web3.fromAscii(\"test\")\n ).send({'from': '0x902D578B7E7866FaE71b3AB0354C9606631bCe03'}\n ).then((result) => {\n console.log('saveLocation')\n console.log(result)\n });\n\n this.getLocationHistory();\n\n });\n } \n\n}\n```\n\nSolidity Contract\n\n```\npragma solidity ^0.4.11;\n/// @title QRCodeTracking with delegation.\ncontract QRCodeTracking {\n struct Location {\n address delegate;\n uint128 longitude;\n uint128 latitude; \n bytes32 name;\n }\n\n struct Item {\n bytes32 id; \n bytes32 name; \n }\n\n Item public item;\n\n Location[] public locations;\n Location public recentLocation;\n\n function QRCodeTracking(bytes32 id, bytes32 name) public {\n // Limit gas\n locations.length = 100;\n item = Item({id: id, name: name});\n }\n\n function saveLocation (\n uint128 longitude,\n uint128 latitude,\n bytes32 name\n ) public constant {\n\n locations.push(Location({\n delegate: msg.sender,\n longitude: longitude,\n latitude: latitude,\n name: name\n }));\n\n }\n\n function getLocationHistory(uint idx) constant\n returns (address delegate, uint128 longitude, uint128 latitude, bytes32 name) {\n\n Location storage loc = locations[idx];\n\n return (loc.delegate, loc.longitude, loc.latitude, loc.name);\n }\n\n function getLastLocation() public\n returns (Location recentLocation) {\n recentLocation = locations[locations.length - 1];\n\n return recentLocation;\n }\n}\n```\n\n========================================\n\nCode:\n```text\nexport class AppComponent {\n  title = 'app';\n  dappUrl: string = 'http://myapp.com';\n  web3: any;\n  contractHash: string = '0x3b8a60616bde6f6d251e807695900f31ab12ce1a';\n  MyContract: any;\n  contract: any;\n  ABI: any = [{\"constant\":true,\"inputs\":[{\"name\":\"idx\",\"type\":\"uint256\"}],\"name\":\"getLocationHistory\",\"outputs\":[{\"name\":\"delegate\",\"type\":\"address\"},{\"name\":\"longitude\",\"type\":\"uint128\"},{\"name\":\"latitude\",\"type\":\"uint128\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"recentLocation\",\"outputs\":[{\"name\":\"delegate\",\"type\":\"address\"},{\"name\":\"longitude\",\"type\":\"uint128\"},{\"name\":\"latitude\",\"type\":\"uint128\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"longitude\",\"type\":\"uint128\"},{\"name\":\"latitude\",\"type\":\"uint128\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"name\":\"saveLocation\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"getLastLocation\",\"outputs\":[{\"components\":[{\"name\":\"delegate\",\"type\":\"address\"},{\"name\":\"longitude\",\"type\":\"uint128\"},{\"name\":\"latitude\",\"type\":\"uint128\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"name\":\"recentLocation\",\"type\":\"tuple\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"locations\",\"outputs\":[{\"name\":\"delegate\",\"type\":\"address\"},{\"name\":\"longitude\",\"type\":\"uint128\"},{\"name\":\"latitude\",\"type\":\"uint128\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"item\",\"outputs\":[{\"name\":\"id\",\"type\":\"bytes32\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"id\",\"type\":\"bytes32\"},{\"name\":\"name\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}];\n\n\n  constructor(private route: ActivatedRoute) { }\n\n  @HostListener('window:load')\n  windowLoaded() {\n    this.checkAndInstantiateWeb3();\n    this.getLocation();\n  }\n\n  getLocationHistory() {\n    this.MyContract.methods\n      .getLocationHistory(0).send({\n      'from': '0x902D578B7E7866FaE71b3AB0354C9606631bCe03',\n      'gas': '44000'\n    }).then((result) => {\n      this.MyContract.methods.getLocationHistory(0).call()\n        .then(hello => {console.log('hello', hello)});\n    });\n  }\n\n  private checkAndInstantiateWeb3 = () => {\n    if (typeof window.web3 !== 'undefined') {\n      console.warn('Using web3 detected from external source.');\n      // Use Mist/MetaMask's provider\n      this.web3 = new Web3(window.web3.currentProvider);\n    } else {\n      console.warn(`No web3 detected. Falling back to http://localhost:8545.`);\n      this.web3 = new Web3(\n        new Web3.providers.HttpProvider('http://localhost:8545')\n      );\n    }\n\n    this.MyContract = new this.web3.eth.Contract(this.ABI, this.contractHash);\n  }\n\n  private getLocation(): void {\n    let query = this.route.snapshot.queryParams;\n\n    if (query.action && query.action === 'setLocation') {\n      this.setLocation();\n    }\n\n  }\n\n  private setLocation(): void {\n    navigator.geolocation.getCurrentPosition((position) => {\n\n      this.MyContract.methods.saveLocation(\n        position.coords.longitude, position.coords.latitude, window.web3.fromAscii(\"test\")\n      ).send({'from': '0x902D578B7E7866FaE71b3AB0354C9606631bCe03'}\n      ).then((result) => {\n        console.log('saveLocation')\n        console.log(result)\n      });\n\n      this.getLocationHistory();\n\n    });\n  }    \n\n}\n```\n\n```text\npragma solidity ^0.4.11;\n/// @title QRCodeTracking with delegation.\ncontract QRCodeTracking {\n    struct Location {\n        address delegate;\n        uint128 longitude;\n        uint128 latitude; \n        bytes32 name;\n    }\n\n    struct Item {\n        bytes32 id;   \n        bytes32 name; \n    }\n\n    Item public item;\n\n    Location[] public locations;\n    Location public recentLocation;\n\n    function QRCodeTracking(bytes32 id, bytes32 name) public {\n        // Limit gas\n        locations.length = 100;\n        item = Item({id: id, name: name});\n    }\n\n    function saveLocation (\n        uint128 longitude,\n        uint128 latitude,\n        bytes32 name\n    ) public constant {\n\n        locations.push(Location({\n            delegate: msg.sender,\n            longitude: longitude,\n            latitude: latitude,\n            name: name\n        }));\n\n    }\n\n    function getLocationHistory(uint idx) constant\n        returns (address delegate, uint128 longitude, uint128 latitude, bytes32 name) {\n\n        Location storage loc = locations[idx];\n\n        return (loc.delegate, loc.longitude, loc.latitude, loc.name);\n    }\n\n    function getLastLocation() public\n        returns (Location recentLocation) {\n        recentLocation = locations[locations.length - 1];\n\n        return recentLocation;\n    }\n}\n```\n\n```text\nconst Web3 = require('web3');\nconst solc = require('solc');\nconst fs = require('fs');\n\nconst provider = new Web3.providers.HttpProvider(\"http://localhost:8545\")\nconst web3 = new Web3(provider);\n\nweb3.eth.getAccounts().then((accounts) => {\n  const code = fs.readFileSync('./QRCodeTracking.sol').toString();\n  const compiledCode = solc.compile(code);\n\n  const byteCode = compiledCode.contracts[':QRCodeTracking'].bytecode;\n  // console.log('byteCode', byteCode);\n  const abiDefinition = JSON.parse(compiledCode.contracts[':QRCodeTracking'].interface);\n\n  const deployTransactionObject = {\n    data: byteCode,\n    from: accounts[0],\n    gas: 4700000\n  };\n\n  let deployedContract;\n\n  const MyContract = new web3.eth.Contract(abiDefinition, deployTransactionObject);\n\n  MyContract.deploy({arguments: [web3.utils.asciiToHex(\"someId\"), web3.utils.asciiToHex(\"someName\")]}).send((err, hash) => {\n    if (err)\n      console.log(\"Error: \" + err);\n    else\n      console.log(\"TX Hash: \" + hash);\n  }).then(result => {\n    deployedContract = result;\n    deployedContract.setProvider(provider);\n\n    return deployedContract.methods.saveLocation(123456789, 987654321, web3.utils.asciiToHex(\"newLocationName\")).send();\n  }).then(saveResult => {\n    return deployedContract.methods.getLocationHistory(0).call();\n  }).then(locationResult => {\n    console.log(locationResult);\n  })\n});\n```\n\n```text\nconstant\n```\n\n```text\nsend\n```\n\n```text\ncall\n```\n\n```text\nconstant\n```\n\n```text\nview\n```\n\n```text\nconstant\n```\n\n```text\nsaveLocation\n```\n\n```text\nconstant\n```\n\n```text\ngetLastLocation\n```\n\n```text\ngetLocationHistory\n```\n\n```text\nconstant\n```\n\n```text\nsend\n```\n\n```text\ncall\n```\n\n```text\nthis.MyContract.methods.getLocationHistory(0).send()\n```\n\n```text\n.then\n```\n\n```text\nreturns\n```\n\n```text\nconstant\n```\n\n```text\nthis.MyContract.methods.getLocationHistory(0).call()\n```\n\n```text\nsend\n```\n\n```text\ncall\n```\n\n========================================\n\nComments:\n- Problem occur when you call `this.MyContract.methods.saveLocation`?\n- Are you saying .call() will return the data? .call() only returns locally, it doesn't access the blockchain. –\n- That's not correct. It doesn't publish to the blockchain, but it executes within the EVM and does indeed read from it. If you're running a local node, then the invocation runs locally and you don't pay for the gas used.\n- Ok, but it still doesn't return my data, which is my original question.\n- Just noticed the other bug you have: `locations.length = 100;` is creating 100 elements in your `locations` array all initialized with fields set to 0. When you call `saveLocation`, you're adding an element to your array at index 100. When you retrieve the element at index 0, you're getting an all 0 location object. Remove that line. After making that change (plus the others I mentioned), I tested the contract and it ran. I updated the answer with my own version of the client that's a little more straightforward.\n- Ok, great thanks. I initially put that in because Remix IDE wouldn't compile and found a stackoverflow post that said to set the length to avoid the infinite recursion error that Remix was throwing. Glad I lost three days of work over a Remix IDE bug. Now it works in Remix no problem. Ugh..","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":410,"estimatedTokens":3330}}22{"id":"stack-71360830","source":"stackoverflow","questionId":71360830,"title":"Member \"push\" is not available in bool[] memory outside of storage","tags":["solidity"],"text":"Title: Member \"push\" is not available in bool[] memory outside of storage\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI was trying a simple push operation within solidity.\nAs shown in the code below with function isArrayEven():\n\n```\npragma solidity ^0.8.12;\n\ncontract Test {\n uint[] public arr = [uint(1), 2, 3, 4, 5, 6, 7, 8 ,9];\n\n function isArrayEven() public view returns(bool[] memory) {\n bool[] memory ret;\n\n for (uint i = 0; i But the following error is thrown:\n\nMember \"push\" is not available in bool[] memory outside of storage.\n\nI have figured out how to fix this by using below:\n\n```\npragma solidity ^0.8.12;\n\ncontract Test {\n uint[] public arr = [uint(1), 2, 3, 4, 5, 6, 7, 8 ,9];\n\n function isArrayEven() public view returns(bool[] memory) {\n bool[] memory ret = new bool[](arr.length);\n\n for (uint i = 0; i But I don't understand this behavior, why is 'push' not allowed for memory arrays?\n\n========================================\n\nTop Answer:\nA simple solution is to use the new keyword while initializing array and instead of pushing it to the array we can initialize it on its position as we have the index in coming from the for loop.\n\npragma solidity ^0.8.12;\n\ncontract Test {\nuint[] public arr = [uint(1), 2, 3, 4, 5, 6, 7, 8 ,9];\n\n```\nfunction isArrayEven() public view returns(bool[] memory) {\n bool[] memory ret = new bool[](arr.length);\n\n for (uint i = 0; i }\n\n========================================\n\nCode:\n```text\npragma solidity ^0.8.12;\n\ncontract Test {\n    uint[] public arr = [uint(1), 2, 3, 4, 5, 6, 7, 8 ,9];\n\n    function isArrayEven() public view returns(bool[] memory) {\n        bool[] memory ret;\n\n        for (uint i = 0; i < arr.length; i++) {\n            ret.push((arr[i]%2 == 0));\n        }\n\n        return ret;\n    }\n}\n```\n\n```text\npragma solidity ^0.8.12;\n\ncontract Test {\n    uint[] public arr = [uint(1), 2, 3, 4, 5, 6, 7, 8 ,9];\n\n    function isArrayEven() public view returns(bool[] memory) {\n        bool[] memory ret = new bool[](arr.length);\n\n        for (uint i = 0; i < arr.length; i++) {\n            ret[i] = (arr[i]%2 == 0);\n        }\n\n        return ret;\n    }\n}\n```\n\n```text\nfunction isArrayEven() public view returns(bool[] memory) {\n    bool[] memory ret = new bool[](arr.length);\n\n    for (uint i = 0; i < arr.length; i++) {\n        ret[i] = bool((arr[i]%2 == 0));\n    }\n\n    return ret;\n}\n```\n\n========================================\n\nComments:\n- Does this answer your question? Solidity: Returns filtered array of structs without 'push'","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":105,"estimatedTokens":626}}23{"id":"stack-71343598","source":"stackoverflow","questionId":71343598,"title":"ProviderError: transaction underpriced on Mumbai Testnet","tags":["solidity","nft"],"text":"Title: ProviderError: transaction underpriced on Mumbai Testnet\nTags: solidity, nft\nSource: Stack Overflow\n\nQuestion:\nI am building an NFT Market on the Polygon network.\n\nI am able to deploy my code on localhost and everything works fine.\n\nBut when I try to it deploy to the mumbai testnet using the command\n**npx hardhat run scripts/deploy.js --network mumbai**\n\nI run into this error.\n**ProviderError: transaction underpriced**\n\n========================================\n\nTop Answer:\nIn my case, I was using the wrong RPC node, sharing just in case someone made the same mistake as I did\n\n**How did I fix it?**\n\n- Removed Matic chain from Metamask networks\n\n- Added it again from https://umbria.network/connect/matic-testnet-mumbai\n\n========================================\n\nCode:\n```text\nmumbai: {\n      // Infura\n      url: `https://polygon-mumbai.infura.io/v3/${INFURA_API_KEY}`,\n      accounts: [privateKey1],\n      gasPrice: 35000000000,\n      saveDeployments: true,\n    },\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":38,"estimatedTokens":246}}24{"id":"stack-61897419","source":"stackoverflow","questionId":61897419,"title":"why this view function is not free ether function?","tags":["view","ethereum","solidity","smartcontracts","remix"],"text":"Title: why this view function is not free ether function?\nTags: view, ethereum, solidity, smartcontracts, remix\nSource: Stack Overflow\n\nQuestion:\nShow Image\n\nas you can see the image above, the function 'custLogIn' is view type (free on ether)\nbut after deploy the contract trhough Remix, it changed into non-free function.\n\nI want to know about it and change into ether free function. please give your ideas. thank you.","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":11,"estimatedTokens":105}}25{"id":"stack-67169900","source":"stackoverflow","questionId":67169900,"title":"eth_sendTransaction does not exist/is not available","tags":["ethereum","solidity","web3js"],"text":"Title: eth_sendTransaction does not exist/is not available\nTags: ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI'm currently using ERC721PresetMinterPauserAutoId for a smart contract and the Web3.js library in the Node.js backend server. When I try to call the mint function using this Web3 API:\n\n```\nvar myContract = new web3.eth.Contract(ERC721PresetMinterPauserAutoIdABI, ERC721PresetMinterPauserAutoIdContractAddress, {\n from: from, \n gasPrice: gasPrice\n });\n\n let result;\n try {\n result = await myContract.methods.mint(receipientAddress).send();\n res.status(201).send(result)\n } catch (error) {\n res.status(201).send(error)\n }\n```\n\nI get the following error:\n\nReturned error: The method eth_sendTransaction does not exist/is not available\n\nI'm communicating to the Rinkeby blockchain through the Infura gateway and according to this post, Infura supports only `eth_sendRawTransaction`, not `eth_sendTransaction`.\n\nI was able to successfully send Ether using a signed transaction:\n\n```\nconst gasPrice = await web3.eth.getGasPrice()\n const txCount = await web3.eth.getTransactionCount(from, 'pending')\n var rawTx = {\n nonce: txCount,\n gasPrice:\"0x\" + gasPrice,\n gasLimit: '0x200000',\n to: to,\n value: \"0x1000000000000000\",\n data: \"0x\",\n chainId: 4\n };\n\n var privateKey = new Buffer.from(pk, \"hex\")\n var tx = new Tx(rawTx, {\"chain\": \"rinkeby\"});\n tx.sign(privateKey);\n\n var serializedTx = tx.serialize();\n const signedTx = await web3.eth.sendSignedTransaction(\"0x\" + serializedTx.toString(\"hex\"));\n```\n\nHowever, I'm unable to call the `mint` method on the smart contract using the raw transaction. I've tried:\n\n```\nawait myContract.methods.mint(receipientAddress).sendSignedTransaction(\"0x\" + serializedTx.toString(\"hex\"));\n```\n\nor\n\n```\nawait myContract.methods.mint(receipientAddress).sendRawTransaction(\"0x\" + serializedTx.toString(\"hex\"));\n```\n\nBut, I still get the error message `eth_sendTransaction does not exist/is not available`.\n\n**Update**\n\nI tried using signing the transaction using a Truffle's library on the advise of @MikkoOhtamaa:\n\n```\nconst HDWalletProvider = require(\"@truffle/hdwallet-provider\");\nconst privateKeys = process.env.PRIVATE_KEYS || \"\"\nconst walletAPIUrl = `https://rinkeby.infura.io/v3/${process.env.INFURA_API_KEY}`\nconst provider = new HDWalletProvider(\n privateKeys.split(','),\n walletAPIUrl\n);\nconst web3 = new Web3API(provider)\n```\n\n========================================\n\nCode:\n```js\nvar myContract = new web3.eth.Contract(ERC721PresetMinterPauserAutoIdABI, ERC721PresetMinterPauserAutoIdContractAddress, {\n    from: from, \n    gasPrice: gasPrice\n  });\n\n  let result;\n  try {\n    result = await myContract.methods.mint(receipientAddress).send();\n    res.status(201).send(result)\n  } catch (error) {\n    res.status(201).send(error)\n  }\n```\n\n```js\nconst gasPrice = await web3.eth.getGasPrice()\n  const txCount = await web3.eth.getTransactionCount(from, 'pending')\n  var rawTx = {\n      nonce: txCount,\n      gasPrice:\"0x\" + gasPrice,\n      gasLimit: '0x200000',\n      to: to,\n      value: \"0x1000000000000000\",\n      data: \"0x\",\n      chainId: 4\n  };\n\n  var privateKey = new Buffer.from(pk, \"hex\")\n  var tx = new Tx(rawTx, {\"chain\": \"rinkeby\"});\n  tx.sign(privateKey);\n\n  var serializedTx = tx.serialize();\n  const signedTx = await web3.eth.sendSignedTransaction(\"0x\" + serializedTx.toString(\"hex\"));\n```\n\n```js\nawait myContract.methods.mint(receipientAddress).sendSignedTransaction(\"0x\" + serializedTx.toString(\"hex\"));\n```\n\n```js\nawait myContract.methods.mint(receipientAddress).sendRawTransaction(\"0x\" + serializedTx.toString(\"hex\"));\n```\n\n```js\nconst HDWalletProvider = require(\"@truffle/hdwallet-provider\");\nconst privateKeys = process.env.PRIVATE_KEYS || \"\"\nconst walletAPIUrl = `https://rinkeby.infura.io/v3/${process.env.INFURA_API_KEY}`\nconst provider = new HDWalletProvider(\n  privateKeys.split(','),\n  walletAPIUrl\n);\nconst web3 = new Web3API(provider)\n```\n\n```text\neth_sendRawTransaction\n```\n\n```text\neth_sendTransaction\n```\n\n```text\nmint\n```\n\n```text\neth_sendTransaction does not exist/is not available\n```\n\n========================================\n\nComments:\n- I updated the question, but what I'm confused about is, am I getting the private key dynamically from the user to configure the `HDWallet`? Also, should I be using the JSON-RPC method alongside with `HDWallet` because there are some Web3 functionalities like creating a wallet that you have to use without a private key? I believe there is not way to configure `HDWallet` without a private key or mnemonic.\n- `dynamically from the user to configure` you don't. You never import user keys to the server-side. If you get private key from the user then effectively you become a hacker and all blockchain security guarantees are lost.\n- just to clarify, does this mean signing the transaction always has to be done in the front end and never on the server? The reason I'm asking is I would like to use the web3.js library, but I'm not using Javascript on the front end so I'm unable to do so.\n- `just to clarify, does this mean signing the transaction always has to be done in the front end` -> Yes\n- Do you guys know if there is a way to do it through a mobile app?\n- Here ethereum.stackexchange.com/questions/82531/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":163,"estimatedTokens":1313}}26{"id":"stack-61761251","source":"stackoverflow","questionId":61761251,"title":"\"Invalid input source specified\" - Remix Solidity IDE error","tags":["solidity","remix"],"text":"Title: \"Invalid input source specified\" - Remix Solidity IDE error\nTags: solidity, remix\nSource: Stack Overflow\n\nQuestion:\nI have removed everything from my remix IDE, except the following:\n\n```\npragma solidity ^0.6.6;\n\ncontract daily_unlimited_deFitasy{\n}\n```\n\nAnd yet I am still getting the following error when attempting to compile:\n\n`Invalid input source specified`\n\nWhy am I getting this error?\n\n========================================\n\nTop Answer:\nFor Me, it occured in my test scripts and what I did to resolve it, was to comment out this line:\nimport \"remix_accounts.sol\";\n\n========================================\n\nCode:\n```text\npragma solidity ^0.6.6;\n\ncontract daily_unlimited_deFitasy{\n}\n```\n\n```text\nInvalid input source specified\n```\n\n```text\nimport\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.6.12;\nimport 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.3/contracts/math/SafeMath.sol';\ncontract A{\n    .... smart contract code ....\n    .... smart contract code ....\n```\n\n```text\n0.6.12\n```\n\n========================================\n\nComments:\n- A simple refresh works like amazing.","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":61,"estimatedTokens":286}}27{"id":"stack-70257820","source":"stackoverflow","questionId":70257820,"title":"MetaMask - RPC Error: execution reverted {code: -32000, message: 'execution reverted'} while trying to connect to smart contract","tags":["ethereum","solidity","ethers.js"],"text":"Title: MetaMask - RPC Error: execution reverted {code: -32000, message: 'execution reverted'} while trying to connect to smart contract\nTags: ethereum, solidity, ethers.js\nSource: Stack Overflow\n\nQuestion:\nI have deployed a smart contract on a public testnet and now I am trying to connect to it from the front end using ethers js. But when I try to fetch the value it gives the following errors in the console:\n\nhttps://i.sstatic.net/y5Dnh.png\n\n**I am using Angular for the front end and here's the code I wrote:**\n\n```\ndeclare let window: any;\nimport { Component, OnInit } from '@angular/core';\nimport { ethers } from 'ethers';\nimport addresses from '../../environment/contract-address.json'\nimport Election from '../../blockchain/artifacts/blockchain/contracts/Election.sol/Election.json'\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent implements OnInit {\n title = 'angvote';\n public signer: any;\n public electionContract: any;\n public candidate : any;\n public candidatesList:string[] | undefined;\n constructor(){}\n\n async ngOnInit(){\n const provider = new ethers.providers.Web3Provider(window.ethereum);\n window.ethereum.enable()\n \n provider.on(\"network\",(newNetwork: any, oldNetwork: any)=>{\n if (oldNetwork){\n window.location.reload();\n }\n });\n\n this.signer = provider.getSigner();\n\n if(await this.signer.getChainId() !== 4){\n alert(\"Please change your network to Rinkeby!\")\n }\n\n this.electionContract = new ethers.Contract(addresses.electioncontract,Election.abi,this.signer);\n this.candidate = await this.electionContract.candidatesCount();\n } \n}\n```\n\n========================================\n\nTop Answer:\nI met the same problem, check that:\n\n- the contract address is correct\n\n- the method you call is correct\n\n- the parameter is correct\n\nin my case, I called an non-exist method.\n\n========================================\n\nCode:\n```text\ndeclare let window: any;\nimport { Component, OnInit } from '@angular/core';\nimport { ethers } from 'ethers';\nimport addresses from '../../environment/contract-address.json'\nimport Election from '../../blockchain/artifacts/blockchain/contracts/Election.sol/Election.json'\n\n@Component({\n  selector: 'app-root',\n  templateUrl: './app.component.html',\n  styleUrls: ['./app.component.css']\n})\nexport class AppComponent implements OnInit {\n  title = 'angvote';\n  public signer: any;\n  public electionContract: any;\n  public candidate : any;\n  public candidatesList:string[] | undefined;\n  constructor(){}\n\n  async ngOnInit(){\n    const provider = new ethers.providers.Web3Provider(window.ethereum);\n    window.ethereum.enable()\n    \n    provider.on(\"network\",(newNetwork: any, oldNetwork: any)=>{\n      if (oldNetwork){\n        window.location.reload();\n      }\n    });\n\n    this.signer = provider.getSigner();\n\n    if(await this.signer.getChainId() !== 4){\n      alert(\"Please change your network to Rinkeby!\")\n    }\n\n    this.electionContract = new ethers.Contract(addresses.electioncontract,Election.abi,this.signer);\n    this.candidate = await this.electionContract.candidatesCount();\n  }  \n}\n```\n\n========================================\n\nComments:\n- Please edit the question and the values of `addresses.electioncontract` and `Election.abi`. It's possible that you're either accessing an incorrect contract (e.g. on a different network or under a different address) or using an ABI that doesn't correspond with the function invoked from the JS code.\n- Yes you are correct, there was something wrong with the smart contract I deployed. Noticed it when tried to redeploy\n- You are getting a \"unpredictable gas limit\" error here. This may happen if your solidity code runs into an infinite loop or recursive function call... you may also possibly be able to get around it by explicitly specifying a gas limit.\n- How do we get the correct contract address? I'm using truffle, I use `truffle migrate --network rinkeby --reset` and the transfer() function is transferring from `msg.sender`.\n- `truffle migrate` output would give you the contract address.\n- Yeah the address I've used is definitely correct, but I'm still getting this error.\n- try to switch to another network, e.g. ganache, or goerli , or fuji ... sometimes the network has bugs.","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":121,"estimatedTokens":1070}}28{"id":"stack-77149484","source":"stackoverflow","questionId":77149484,"title":"How can I generate the ABI of my smart contract locally with foundry/forge?","tags":["solidity","smartcontracts","abi","foundry-forge"],"text":"Title: How can I generate the ABI of my smart contract locally with foundry/forge?\nTags: solidity, smartcontracts, abi, foundry-forge\nSource: Stack Overflow\n\nQuestion:\nI have a project with multiple smart contracts locally and I want to generate the ABI of my `sc.sol` smart contract. I do wish to perform this locally using `forge` or `foundry`.\nI know it is possible to do it on Remix or to use solc but I do not have these and wishes to use foundry/forge only.\n\n========================================\n\nTop Answer:\nYou can use\n\n```\nforge inspect abi\n```\n\nand if you want to generate a file with it use\n\n```\nforge inspect > \n```\n\nfor example\n\n```\nforge inspect src/MyContract.sol:MyContract > myContractAbi.json\n```\n\nAnd if you add the flag --pretty and the output is a .sol file it will write you the contract interface. Like\n\n```\nforge inspect src/MyContract.sol:MyContract --pretty > MyContractInterface.sol\n```\n\n========================================\n\nCode:\n```text\nsc.sol\n```\n\n```text\nforge\n```\n\n```text\nfoundry\n```\n\n```text\nforge build --silent && jq '.abi' ./out/MyContract.sol/MyContract.json\n```\n\n```text\npragma solidity ^0.8.21;\n\ncontract MyContract {\n    function foo() external {}\n}\n```\n\n```text\n[\n  {\n    \"inputs\": [],\n    \"name\": \"foo\",\n    \"outputs\": [],\n    \"stateMutability\": \"nonpayable\",\n    \"type\": \"function\"\n  }\n]\n```\n\n```text\nforge build\n```\n\n```text\nout\n```\n\n```text\nabi\n```\n\n```text\njq\n```\n\n```bash\nforge inspect <YOUR_CONTRACT> abi\n```\n\n```bash\nforge inspect <YOUR_CONTRACT> > <OUTPUT_FILE>\n```\n\n```bash\nforge inspect src/MyContract.sol:MyContract > myContractAbi.json\n```\n\n```bash\nforge inspect src/MyContract.sol:MyContract --pretty > MyContractInterface.sol\n```\n\n```text\nforge inspect <CONTRACT> abi --json > <OUTPUT_FILE>\n```\n\n```markdown\n└── out\n    └── YourContract.sol\n        ├── YourContract.json\n        └── YourContract.abi.json\n```\n\n```text\nforge compile --extra-output-files abi\n```\n\n```text\nout/\n```\n\n========================================\n\nComments:\n- Okay. But those files have lots of other data within them...but no deployed addresses\n- @Russo `forge build` only compiles the contract, i.e. translates the human-readable Solidity code into machine-readable bytecode (and generates the ABI as a side-step to that). But it doesn't deploy the contract... In order to deploy a contract to a new address, you can use the forge create command. What it does in the background, it sends a transaction from your deployer address (signed by the deployer private key), containing the bytecode. And then the EVM node that produces a new blocks stores the contract bytecode and assigns it a new address.\n- Thank you. I will trim those file down to only ABIs and add deployment addresses.. for frontend usage\n- you could also use a compiler option to create separate abi files and skip the `jq` part: `--extra-output-files abi`\n- you missed `abi` before `>` in your example :)","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":133,"estimatedTokens":729}}29{"id":"stack-66602944","source":"stackoverflow","questionId":66602944,"title":"OpenSea IPFS Metadata","tags":["solidity","web3js","ipfs","opensea"],"text":"Title: OpenSea IPFS Metadata\nTags: solidity, web3js, ipfs, opensea\nSource: Stack Overflow\n\nQuestion:\nI have been testing my erc-721 contract with a link to my ipfs hash `ipfs://QmeB87321i121xN88bXZzmjSUXqS46B8bU3H9ocyTb8tJf` as the base token URI. The contracts are deployed and the items have been minted by me, but OpenSea can't read that metadata uri as expected. The documentation on OpenSea suggests that it should be sufficient.\n\n**My Contract**\n\n```\npragma solidity ^0.5.0;\n\nimport \"./ERC721Tradable.sol\";\nimport \"openzeppelin-solidity/contracts/ownership/Ownable.sol\";\n\ncontract Creature is ERC721Tradable {\n constructor(address _proxyRegistryAddress)\n public\n ERC721Tradable(\"StygianCoins\", \"STG\", _proxyRegistryAddress)\n {}\n\n function baseTokenURI() public pure returns (string memory) {\n return \"https://ipfs.io/ipfs/QmeB87321i121xN88bXZzmjSUXqS46B8bU3H9ocyTb8tJf\";\n }\n\n function contractURI() public pure returns (string memory) {\n return \"https://contract-abis.herokuapp.com/api/contract/stygian-coins\";\n }\n}\n```\n\n========================================\n\nTop Answer:\nas of my understanding (still haven't done it), the tokenURI has to return an URL that points yo uto the metadata, that metadata containing the actual IPFS url. Take this with a grain of salt\n\n========================================\n\nCode:\n```text\npragma solidity ^0.5.0;\n\nimport \"./ERC721Tradable.sol\";\nimport \"openzeppelin-solidity/contracts/ownership/Ownable.sol\";\n\ncontract Creature is ERC721Tradable {\n    constructor(address _proxyRegistryAddress)\n        public\n        ERC721Tradable(\"StygianCoins\", \"STG\", _proxyRegistryAddress)\n    {}\n\n    function baseTokenURI() public pure returns (string memory) {\n        return \"https://ipfs.io/ipfs/QmeB87321i121xN88bXZzmjSUXqS46B8bU3H9ocyTb8tJf\";\n    }\n\n    function contractURI() public pure returns (string memory) {\n        return \"https://contract-abis.herokuapp.com/api/contract/stygian-coins\";\n    }\n}\n```\n\n```text\nipfs://QmeB87321i121xN88bXZzmjSUXqS46B8bU3H9ocyTb8tJf\n```\n\n```js\n{\n    \"name\": \"You NFT token name\",\n    \"description\": \"Something Cool here\",\n    \"image\": \"ipfs://QmTgqnhFBMkfT9s8PHKcdXBn1f5bG3Q5hmBaR4U6hoTvb1?filename=Chainlink_Elf.png\",\n    \"attributes\": []\n}\n```\n\n```text\n_setTokenURI(tokenId, _tokenURI);\n```\n\n```text\njson\n```\n\n```text\nimage\n```\n\n```text\n_setTokenURI(tokenId, _tokenURI);\n```\n\n```text\n_tokenURI\n```\n\n========================================\n\nComments:\n- _setTokenUri uses tokenId, not hash. Is there a recommended way to set the token URI using the hash?\n- What do you mean? TokenURI is based on the TokenID. What do you mean tokenhash?\n- The URI for IPFS ends with the hash. _setTokenURI uses token ID. How is the token ID mapped to the hash? Do we override _setTokenURI in our token's contract, and maintain a mapping there?\n- You don’t use the hash, you use the URI of the hash. For example: ipfs.io/ipfs/&hellip;\n- Dont know if standard is bad or can we do it otherwise, but this will imply we need to set URI for each NFT, which will cost a lot and we would like to set it once and then just use token id for each, but your example doesn't offer that as files are stored with name on the ipfs\n- You don't need to store the files with a name on IPFS. But you could also just override each NFTs tokenURI function to point to the same function, so you could set it and forget it.\n- Do you know whether Opensea also supports ipfs:// type URLs?\n- They do support those\n- Might I ask you how did you implement such rich storefront presentation on opensea with all those social button-links at the top?\n- Oh, that's just something opensea offers on their UI. You don't do that in the solidity code","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":107,"estimatedTokens":918}}30{"id":"stack-68049580","source":"stackoverflow","questionId":68049580,"title":"How to invoke a payable solidity function using HardHat?","tags":["blockchain","solidity","truffle","web3js","hardhat"],"text":"Title: How to invoke a payable solidity function using HardHat?\nTags: blockchain, solidity, truffle, web3js, hardhat\nSource: Stack Overflow\n\nQuestion:\nI have a solidity function called adopt a dog as below which is bascically a payable function in the contract.\n\n**// THIS IS FAILING AS I DONT KNOW HOW TO PASS ETHERS IN HARDHAT/ETHER.JS**\n\n### Hardhart\n\n```\nconst Adopt = await ethers.getContractFactory(\"Adopt\");\n const adopt = await Adopt.deploy();\n await adopt.deployed();\n await adopt.adopt(\"Hachiko\");\n```\n\n### Contract\n\n```\nfunction adopt(string calldata dog_breed) external payable {\n require(msg.value >= 1 ether ,\"Min 1 ether needs to be transfered\");\n require(user_list[msg.sender].user_allowed_to_adopt,\"User not \n allowed to participate for adoption\");\n require(!user_list[msg.sender].adopted,\"User has already \n adopted the dog\");\n \n User memory user=user_list[msg.sender];\n user.adopted=true;\n user_list[msg.sender]=user;\n }\n```\n\n========================================\n\nCode:\n```text\nconst Adopt = await ethers.getContractFactory(\"Adopt\");\n    const adopt = await Adopt.deploy();\n    await adopt.deployed();\n    await adopt.adopt(\"Hachiko\");\n```\n\n```text\nfunction adopt(string calldata dog_breed) external payable {\n             require(msg.value >= 1 ether ,\"Min 1 ether needs to be transfered\");\n            require(user_list[msg.sender].user_allowed_to_adopt,\"User not \n            allowed to participate for adoption\");\n            require(!user_list[msg.sender].adopted,\"User has already \n            adopted the dog\");\n            \n        User memory user=user_list[msg.sender];\n        user.adopted=true;\n        user_list[msg.sender]=user;\n    }\n```\n\n```text\nawait adopt.adopt(\"Hachiko\", {\n    value: ethers.utils.parseEther(\"1.0\")\n});\n```\n\n```text\noverrides\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":67,"estimatedTokens":447}}31{"id":"stack-66290040","source":"stackoverflow","questionId":66290040,"title":"How do I deploy to Ethereum mainnet from Hardhat?","tags":["ethereum","solidity"],"text":"Title: How do I deploy to Ethereum mainnet from Hardhat?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nSo I have followed multiple tutorials on getting started with smart contract development in Ethereum and have read many, many pages on security and development in OpenZeppelin. How exactly do I go about actually deploying my project to the Ethereum mainnet using Hardhat though? I can only find info on deploying to test networks!\n\n========================================\n\nTop Answer:\nIn the context of hardhat, mainnet, testnet or any other network work in the same way. These are just the tags. you can define multiple networks in hardhat config\n\n```\nmodule.exports = {\n solidity: \"0.8.9\",\n defaultNetwork: \"hardhat\",\n networks: {\n hardhat: {},\n rinkeby: {\n url: RAPI_URL,\n accounts: [RINKEBY_WALLET_ADDRESS_PRIVATE_KEY]\n },\n mainnet: {\n url: ETH_MAINNET_RPC_URL,\n accounts: [MAINNET_WALLET_ADDRESS_PRIVATE_KEY]\n },\n },\n}\n```\n\nthen for deploy use the command like this\n\n```\nnpx hardhat run scripts/deploy.js --network rinkeby\n```\n\nor\n\n```\nnpx hardhat run scripts/deploy.js --network mainnet\n```\n\n========================================\n\nCode:\n```text\nmainnet: {\n    url: \"https://mainnet.infura.io/v3/<your_infura_key>\", // or any other JSON-RPC provider\n    accounts: [<your_private_key>]\n}\n```\n\n```text\nnetworks\n```\n\n```text\nmnemonic\n```\n\n```text\nmodule.exports = {\n    solidity: \"0.8.9\",\n    defaultNetwork: \"hardhat\",\n    networks: {\n        hardhat: {},\n        rinkeby: {\n            url: RAPI_URL,\n            accounts: [RINKEBY_WALLET_ADDRESS_PRIVATE_KEY]\n        },\n        mainnet: {\n            url: ETH_MAINNET_RPC_URL,\n            accounts: [MAINNET_WALLET_ADDRESS_PRIVATE_KEY]\n        },\n    },\n}\n```\n\n```text\nnpx hardhat run scripts/deploy.js --network rinkeby\n```\n\n```text\nnpx hardhat run scripts/deploy.js --network mainnet\n```\n\n========================================\n\nComments:\n- How trustworthy does the JSON-RPC provider need to be?\n- Is there no way for Hardhat to send the transaction to the blockchain directly?\n- @LukeHutchison You don't need to trust the provider, as the transaction is signed in your app (using the private key) and the actual private key is never sent to the provider (assuming that you trust/verify Hardhat and all other dependencies that they don't send the private key elsewhere)... This is the most direct way of sending a transaction, as it needs to be broadcasted from one of the nodes of the P2P (Ethereum) network to the rest of the network. If you're not willing/able to rely on a third-party node, you can also run your own node.","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":92,"estimatedTokens":652}}32{"id":"stack-48351077","source":"stackoverflow","questionId":48351077,"title":"accepting ether in smart contract","tags":["solidity","smartcontracts","ether"],"text":"Title: accepting ether in smart contract\nTags: solidity, smartcontracts, ether\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a simple smart contract to learn solidity and how ethereum works.\n\nFrom what I understand, using the modify payable on a method will make it accept a value. We then deduct from the sender and add that somewhere else, in this code I'm trying to send it to the owner of the contract.\n\n```\ncontract AcceptEth {\n address public owner;\n uint public bal;\n uint public price;\n mapping (address => uint) balance;\n\n function AcceptEth() {\n // set owner as the address of the one who created the contract\n owner = msg.sender;\n // set the price to 2 ether\n price = 2 ether;\n }\n\n function accept() payable returns(bool success) {\n // deduct 2 ether from the one person who executed the contract\n balance[msg.sender] -= price;\n // send 2 ether to the owner of this contract\n balance[owner] += price;\n return true;\n }\n}\n```\n\nWhen I interact with this contract through remix, I get an error of \"VM Exception while processing transaction: out of gas\" it creates a transaction and the gas price was 21000000000 and the value was 0.00 ETH when I'm trying to get 2 ether from anyone who executes this method. \n\nWhat's wrong with the code? Alternatively I can add a a variable for one to input the value they want to send, along with a withdraw method, right? but for the sake of learning, I wanted to keep it simple. but even this code feels a bit simple and feels like something is missing.\n\n========================================\n\nCode:\n```text\ncontract  AcceptEth {\n    address public owner;\n    uint public bal;\n    uint public price;\n    mapping (address => uint) balance;\n\n    function AcceptEth() {\n        // set owner as the address of the one who created the contract\n        owner = msg.sender;\n        // set the price to 2 ether\n        price = 2 ether;\n    }\n\n    function accept() payable returns(bool success) {\n        // deduct 2 ether from the one person who executed the contract\n        balance[msg.sender] -= price;\n        // send 2 ether to the owner of this contract\n        balance[owner] += price;\n        return true;\n    }\n}\n```\n\n```text\ncontract  AcceptEth {\n    address public owner;\n    uint public price;\n    mapping (address => uint) balance;\n\n    function AcceptEth() {\n        // set owner as the address of the one who created the contract\n        owner = msg.sender;\n        // set the price to 2 ether\n        price = 2 ether;\n    }\n\n    function accept() payable {\n        // Error out if anything other than 2 ether is sent\n        require(msg.value == price);\n\n        // Track that calling account deposited ether\n        balance[msg.sender] += msg.value;\n    }\n}\n```\n\n```text\nfunction refund(uint amountRequested) public {\n  require(amountRequested > 0 && amountRequested <= balance[msg.sender]);\n\n  balance[msg.sender] -= amountRequested;\n\n  msg.sender.transfer(amountRequested); // contract transfers ether to msg.sender's address\n}\n```\n\n```text\naccept()\n```\n\n```text\nprice\n```\n\n```text\naccept()\n```\n\n```text\naccept()\n```\n\n```text\nbalance\n```\n\n```text\nrefund()\n```\n\n========================================\n\nComments:\n- thanks for your answer, this really helped understand it all better. how and where can I find the right tutorial to go about creating a withdrawal / transfer of the contract's funds to and limited to just the contract owner's address?\n- when I interact with this in remix, there's no field to specify a value when executing the accept method?\n- The Solidity documentation has it all. solidity.readthedocs.io/en/develop\n- Run tab, top right. Value field. Drop down let’s you specify which type to send (ether, wei, etc)\n- How to store balance so that it can be converted into real Ether at production level?","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":129,"estimatedTokens":948}}33{"id":"stack-70936795","source":"stackoverflow","questionId":70936795,"title":"How to set msg.value in Remix IDE","tags":["solidity","remix","ether"],"text":"Title: How to set msg.value in Remix IDE\nTags: solidity, remix, ether\nSource: Stack Overflow\n\nQuestion:\nThis is probably an easy error I'm missing, but I cannot for the life of me figure out how to set the msg.value variable in this contract. I've read online that this value is the amount of wei associated with the transaction, but how do I, as a caller of the contract, specifically set that value. Here's the contract I'm struggling with.\n\npragma solidity 0.8.7;\n\ncontract VendingMachine {\n\n```\n// Declare state variables of the contract\naddress public owner;\nmapping (address => uint) public cupcakeBalances;\n\n// When 'VendingMachine' contract is deployed:\n// 1. set the deploying address as the owner of the contract\n// 2. set the deployed smart contract's cupcake balance to 100\nconstructor() {\n owner = msg.sender;\n cupcakeBalances[address(this)] = 100;\n}\n\n// Allow the owner to increase the smart contract's cupcake balance\nfunction refill(uint amount) public {\n require(msg.sender == owner, \"Only the owner can refill.\");\n cupcakeBalances[address(this)] += amount;\n}\n\n// Allow anyone to purchase cupcakes\nfunction purchase(uint amount) public payable {\n require(msg.value >= amount * 1 ether, \"You must pay at least 1 ETH per cupcake\");\n require(cupcakeBalances[address(this)] >= amount, \"Not enough cupcakes in stock to complete this purchase\");\n cupcakeBalances[address(this)] -= amount;\n cupcakeBalances[msg.sender] += amount;\n}\n```\n\n}\n\nEvery time I enter an amount, I'm getting thrown the error that says \"You must pay at least 1 ETH per cupcake\"\n\nThere's nowhere for me to specifically enter in a value for how much I'm going to pay for this, any help would be great\n\nhere's what I'm able to input when I deploy the contract on Remix\n\n========================================\n\nCode:\n```text\n// Declare state variables of the contract\naddress public owner;\nmapping (address => uint) public cupcakeBalances;\n\n// When 'VendingMachine' contract is deployed:\n// 1. set the deploying address as the owner of the contract\n// 2. set the deployed smart contract's cupcake balance to 100\nconstructor() {\n    owner = msg.sender;\n    cupcakeBalances[address(this)] = 100;\n}\n\n// Allow the owner to increase the smart contract's cupcake balance\nfunction refill(uint amount) public {\n    require(msg.sender == owner, \"Only the owner can refill.\");\n    cupcakeBalances[address(this)] += amount;\n}\n\n// Allow anyone to purchase cupcakes\nfunction purchase(uint amount) public payable {\n    require(msg.value >= amount * 1 ether, \"You must pay at least 1 ETH per cupcake\");\n    require(cupcakeBalances[address(this)] >= amount, \"Not enough cupcakes in stock to complete this purchase\");\n    cupcakeBalances[address(this)] -= amount;\n    cupcakeBalances[msg.sender] += amount;\n}\n```\n\n```text\npurchase\n```\n\n```text\nEther\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":85,"estimatedTokens":705}}34{"id":"stack-53447586","source":"stackoverflow","questionId":53447586,"title":"Return string in solidity 0.5.0. Data location must be \"memory\" for return parameter in function","tags":["ethereum","solidity","smartcontracts"],"text":"Title: Return string in solidity 0.5.0. Data location must be \"memory\" for return parameter in function\nTags: ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nHow to return string in 0.5.0 solidity compiler version?\n\n```\ncontract Test {\n string public text = 'show me';\n function test() public view returns (string) {\n return text;\n }\n}\n```\n\nI got error message:\n\n```\nTypeError: Data location must be \"memory\" for return parameter in function, but none was given.\n```\n\n========================================\n\nTop Answer:\n```\n//The version I have used is 0.5.2\n\npragma solidity ^0.5.2;\n\ncontract Inbox{\n\nstring public message;\n\n//**Constructor** must be defined using “constructor” keyword\n\n//**In version 0.5.0 or above** it is **mandatory to use “memory” keyword** so as to \n//**explicitly mention the data location**\n\n//you are free to remove the keyword and try for yourself\n\n constructor (string memory initialMessage) public{\n message=initialMessage;\n }\n\n function setMessage(string memory newMessage)public{\n message=newMessage;\n\n }\n\n function getMessage()public view returns(string memory){\n return message;\n }}\n```\n\n========================================\n\nCode:\n```text\ncontract Test {\n    string public text = 'show me';\n    function  test() public view returns (string) {\n        return text;\n    }\n}\n```\n\n```text\nTypeError: Data location must be \"memory\" for return parameter in function, but none was given.\n```\n\n```text\nfunction test() public view returns (string memory) {\n```\n\n```text\nmemory\n```\n\n```text\nstring\n```\n\n```text\n//The version I have used is 0.5.2\n\npragma solidity ^0.5.2;\n\ncontract Inbox{\n\n\nstring public message;\n\n//**Constructor** must be defined using “constructor” keyword\n\n//**In version 0.5.0 or above** it is **mandatory to use “memory” keyword** so as to \n//**explicitly mention the data location**\n\n//you are free to remove the keyword and try for yourself\n\n constructor (string memory initialMessage) public{\n message=initialMessage;\n }\n\n function setMessage(string memory newMessage)public{\n message=newMessage;\n\n }\n\n function getMessage()public view returns(string memory){\n return message;\n }}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":113,"estimatedTokens":541}}35{"id":"stack-49409209","source":"stackoverflow","questionId":49409209,"title":"What are limitations of Event arguments?","tags":["arguments","ethereum","solidity"],"text":"Title: What are limitations of Event arguments?\nTags: arguments, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nAre there any limitation on the amount of arguments that can be send in an event?\n\nI have a function in which I want to trigger event that has 12 arguments of which 6 arguments are arrays. I get Stack too deep, try using less variables. Without the event the function works normally.\n\nI am guessing event arguments have some limitations or count towards max arguments in a solidity function but I cannot find any documentation around it.\n\nCan anyone clarify this?\n\nEdit: \n\nThe contract looks something like this: \nI'm using safe math and the _getAddressSubArrayTo is an internal pure function that gets a sub array from index to index.\n\n```\nevent LogTemp(address a,\n address b,\n address[] c,\n uint256[] d,\n address[] e,\n uint256[] f,\n address[] g,\n uint256[] h,\n uint256 i,\n uint256 j,\n uint256 k,\n bytes32 l);\n\nfunction test(address[] _addresses,\n uint256[] _uints,\n uint8 _v,\n bytes32 _r,\n bytes32 _s,\n bool test)\n public\n returns (bool)\n{\n\nTemp memory temp = Temp({\n a: _addresses[0],\n b: _addresses[1],\n c: _getAddressSubArrayTo(_addresses, 2, _uints[3].add(2)),\n d: _getUintSubArrayTo(_uints, 5, _uints[3].add(5)),\n e: _getAddressSubArrayTo(_addresses, _uints[3].add(2), (_uints[3].add(2)).add(_uints[4])),\n f: _getUintSubArrayTo(_uints, _uints[3].add(5), (_uints[3].add(5)).add(_uints[4])),\n g: _getAddressSubArrayTo(_addresses, (_uints[3].add(2)).add(_uints[4]), _addresses.length),\n h: _getUintSubArrayTo(_uints,(_uints[3].add(5)).add(_uints[4]), _uints.length),\n i: _uints[0],\n j: _uints[1],\n k: _uints[2],\n l: hash(\n _addresses,\n _uints\n )\n});\n\nLogTemp(\n temp.a,\n temp.b,\n temp.c,\n temp.d,\n temp.e,\n temp.f,\n temp.g,\n temp.h,\n temp.i,\n temp.j,\n temp.k,\n temp.l\n);\n}\n```\n\n========================================\n\nTop Answer:\nYes, there are limits. You can have up to three indexed arguments in your event. Non-indexed arguments are less restrictive as it’s not limited by the event data structure itself, but is limited by the block gas size for storage (at a cost of 8 gas per byte of data stored in the log).\n\nSolidity event documentation\n\n========================================\n\nCode:\n```text\nevent LogTemp(address a,\n             address b,\n             address[] c,\n             uint256[] d,\n             address[] e,\n             uint256[] f,\n             address[] g,\n             uint256[] h,\n             uint256 i,\n             uint256 j,\n             uint256 k,\n             bytes32 l);\n\nfunction test(address[] _addresses,\n           uint256[] _uints,\n           uint8 _v,\n           bytes32 _r,\n           bytes32 _s,\n           bool test)\n  public\n  returns (bool)\n{\n\nTemp memory temp = Temp({\n  a: _addresses[0],\n  b: _addresses[1],\n  c: _getAddressSubArrayTo(_addresses, 2, _uints[3].add(2)),\n  d: _getUintSubArrayTo(_uints, 5, _uints[3].add(5)),\n  e: _getAddressSubArrayTo(_addresses, _uints[3].add(2), (_uints[3].add(2)).add(_uints[4])),\n  f: _getUintSubArrayTo(_uints, _uints[3].add(5), (_uints[3].add(5)).add(_uints[4])),\n  g: _getAddressSubArrayTo(_addresses, (_uints[3].add(2)).add(_uints[4]), _addresses.length),\n  h: _getUintSubArrayTo(_uints,(_uints[3].add(5)).add(_uints[4]), _uints.length),\n  i: _uints[0],\n  j: _uints[1],\n  k: _uints[2],\n  l: hash(\n    _addresses,\n    _uints\n  )\n});\n\n\nLogTemp(\n  temp.a,\n  temp.b,\n  temp.c,\n  temp.d,\n  temp.e,\n  temp.f,\n  temp.g,\n  temp.h,\n  temp.i,\n  temp.j,\n  temp.k,\n  temp.l\n);\n}\n```\n\n```text\nif (stackLayout.size() > 17)           \n  BOOST_THROW_EXCEPTION(   \n        CompilerError() <<     \n    errinfo_sourceLocation(_function.location()) <<     \n    errinfo_comment(\"Stack too deep, try removing local variables.\")     \n);\n```\n\n```none\nevent LogTemp(Temp tmp);\n```\n\n```none\nLogTemp(temp);\n```\n\n========================================\n\nComments:\n- I know about the indexed arguments but I'm getting Stack too deep even when I comment out all the major processing in the function. I added a code sample above of my problematic event.\n- That has nothing to do with events. There is a limit to the number of local variables you can have in a function (see github.com/ethereum/solidity/issues/2693). If you remove the `Temp` structure from you function and just send the same data to your event directly, you won't hit that error.\n- I don't think that is the problem. Because I otherwise have about 80 lines of code that operates with structured data and calls other functions and everything works fine if I comment out the event... But if I only leave the event and the structure it still fails..","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":170,"estimatedTokens":1149}}36{"id":"stack-70441441","source":"stackoverflow","questionId":70441441,"title":"How to fix 'TransferHelper: ETH_TRANSFER_FAILED' when interacting with Uni V2","tags":["ethereum","solidity","smartcontracts","uniswap"],"text":"Title: How to fix 'TransferHelper: ETH_TRANSFER_FAILED' when interacting with Uni V2\nTags: ethereum, solidity, smartcontracts, uniswap\nSource: Stack Overflow\n\nQuestion:\nI'm dealing with a strange issue with the `safeTransferETH` helper function in Uniswap V2's router contract.\n\nI'm trying to swap tokens held by the contract to Uniswap for Ether, using the `swapExactTokensForETH` function provided by the Uniswap V2 router. (The function code is present on Uniswap's github in router1). The function being called is:\n\n```\nfunction swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n external\n override\n ensure(deadline)\n returns (uint[] memory amounts)\n {\n require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');\n amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');\n TransferHelper.safeTransferFrom(path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]);\n _swap(amounts, path, address(this));\n IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n }\n```\n\nThe only part of this code that is throwing an error is the `TransferHelper.safeTransferETH` function, which is:\n\n```\nfunction safeTransferETH(address to, uint value) internal {\n (bool success,) = to.call{value:value}(new bytes(0));\n require(success, 'TransferHelper: ETH_TRANSFER_FAILED');\n}\n```\n\nMy code is:\n\n```\nfunction uniV2ReceiveETH(address _token0, uint _amount0) public payable returns (uint[] memory amountsReceived) {\n require(_amount0 > 0, \"Must provide tokens if we want tokens in return!\");\n address[] memory path = new address[](2);\n path[0] = _token0;\n path[1] = WETH;\n\n IERC20 token;\n token = IERC20(_token0);\n\n if (token.balanceOf(address(this)) > 0) {\n _amount0 = token.balanceOf(address(this));\n }\n\n require(token.approve(address(uniV2Router), _amount0 + 10000), \"approval failed\");\n\n // Swap logic\n uint amountOutMin = UniswapV2Library.getAmountsOut(address(uniV2Factory), _amount0, path)[1];\n amountsReceived = uniV2Router.swapExactTokensForETH(_amount0, amountOutMin, path, address(this), deadline);\n uint endBalance = address(this).balance;\n\n // Let everyone know we're done!\n emit Swap(msg.sender, _amount0, endBalance);\n}\n```\n\nA few other notes are:\n\n- The contract does receive ETH from other addresses without issue.\n\n- I am using hardhat, and a forked version of the mainnet to test.\n\n- The contract also works with the Uniswap router's other swap functions, including `SwapExactETHForTokens` and `SwapExactTokensForTokens`.\n\n========================================\n\nTop Answer:\nI solved this issue by having a payable receive() function because the contract isn't be able to receive ether without this function:\n\nreceive() external payable {}\n\n\"If you are using Solidity 0.6.0 or later, it is recommended to use the receive() function to explicitly handle plain Ether transfers. If you are working with an older version of Solidity, you can use the fallback() function to handle both Ether transfers and calls with data.\"\n\nfallback() external payable {}\n\n========================================\n\nCode:\n```text\nfunction swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        override\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');\n        amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n        require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');\n        TransferHelper.safeTransferFrom(path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]);\n        _swap(amounts, path, address(this));\n        IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n    }\n```\n\n```text\nfunction safeTransferETH(address to, uint value) internal {\n    (bool success,) = to.call{value:value}(new bytes(0));\n    require(success, 'TransferHelper: ETH_TRANSFER_FAILED');\n}\n```\n\n```text\nfunction uniV2ReceiveETH(address _token0, uint _amount0) public payable returns (uint[] memory amountsReceived) {\n        require(_amount0 > 0, \"Must provide tokens if we want tokens in return!\");\n        address[] memory path = new address[](2);\n        path[0] = _token0;\n        path[1] = WETH;\n\n        IERC20 token;\n        token = IERC20(_token0);\n\n        if (token.balanceOf(address(this)) > 0) {\n            _amount0 = token.balanceOf(address(this));\n        }\n\n        require(token.approve(address(uniV2Router), _amount0 + 10000), \"approval failed\");\n\n        // Swap logic\n        uint amountOutMin = UniswapV2Library.getAmountsOut(address(uniV2Factory), _amount0, path)[1];\n        amountsReceived = uniV2Router.swapExactTokensForETH(_amount0, amountOutMin, path, address(this), deadline);\n        uint endBalance = address(this).balance;\n\n        // Let everyone know we're done!\n        emit Swap(msg.sender, _amount0, endBalance);\n}\n```\n\n```text\nsafeTransferETH\n```\n\n```text\nswapExactTokensForETH\n```\n\n```text\nTransferHelper.safeTransferETH\n```\n\n```text\nSwapExactETHForTokens\n```\n\n```text\nSwapExactTokensForTokens\n```\n\n```text\nfallback() external payable { }\n```\n\n```text\npayable\n```\n\n```text\nfallback\n```\n\n```text\nreceive() external payable {}\nfallback() external payable {}\n```\n\n========================================\n\nComments:\n- why on the line when you call swapExactTokensForETH you write amountOutMin fixed to 1? you calculated it just before, use it. it can give error if the actual amountOut is less than 1\n- Apologies, it is supposed to be AmountOutMin, I was just testing to see if that had anything to do with it. I've updated it in the provided code.\n- By the way, it's probably easier to get answers to questions like these on Ethereum.","metadata":{"transformedAt":"2026-08-18T18:33:36.114Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":178,"estimatedTokens":1515}}37{"id":"stack-57027386","source":"stackoverflow","questionId":57027386,"title":"How to get all events for a transaction (not contract)?","tags":["ethereum","solidity"],"text":"Title: How to get all events for a transaction (not contract)?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI want to get all events emitted by a Solidity contract using web3, however the .getPastEvents() method is for a contract.\n\nThis returns all events for contractInstance, however, my contract calls other contracts which also emit events.\n\n```\nawait contractInstance.getPastEvents(\"allEvents\", {fromBlock: bn, toBlock: bn});\n```\n\nI want to get all the events from a transaction, not from a contract.\n\nOr as an alternative, even all events from a block, which I could then filter down using the transaction hash, to get what I want. Is there a function that returns all events in a block? I've looked but I cannot find one. Must I know every contract in the chain and get the events separately? Perhaps.\n\nI have made a really simple example to illustrate.\n\nThe solidity code:\n\n```\npragma solidity 0.5.8;\n\ncontract contractA {\n event eventA();\n function methodA( address b ) public {\n emit eventA();\n contractB instanceB = contractB( b );\n instanceB.methodB();\n }\n}\n\ncontract contractB {\n event eventB();\n function methodB() public {\n emit eventB();\n }\n}\n```\n\nI am using Truffle to make it simple. Here is the migration file:\n\n```\nvar contractA = artifacts.require(\"contractA\");\nvar contractB = artifacts.require(\"contractB\");\n\nmodule.exports = function(deployer) {\n deployer.deploy(contractA);\n deployer.deploy(contractB);\n```\n\nHere is the truffle javascript code that calls the contractA methodA which emits eventA, and calls contractB methodB which emits eventB:\n\n```\nconst contractA = artifacts.require(\"contractA\");\nconst contractB = artifacts.require(\"contractB\");\n\ncontract(\"contractA\", async accounts => {\n\n thisAccount = accounts[0];\n\n it( \"Simple test\", async () => {\n\n const instanceA = await contractA.deployed();\n const instanceB = await contractB.deployed();\n\n const transaction = await instanceA.methodA( instanceB.address, { from: thisAccount } );\n\n const bn = transaction.receipt.blockNumber, txHash = transaction.tx;\n\n const allEventsA = await instanceA.getPastEvents(\"allEvents\", {fromBlock: bn, toBlock: bn});\n const allEventsB = await instanceB.getPastEvents(\"allEvents\", {fromBlock: bn, toBlock: bn});\n\n console.log(\"A\");\n console.log( allEventsA );\n\n console.log(\"B\");\n console.log( allEventsB );\n\n });\n\n});\n```\n\nAnd here is the output:\n\n```\n$ truffle test test.js\nUsing network 'development'.\n\nCompiling your contracts...\n===========================\n> Everything is up to date, there is nothing to compile.\n Contract: contractA\nA\n[\n {\n logIndex: 0,\n transactionIndex: 0,\n transactionHash: '0xe99db12863e5c0a0ae2c9c603d9d29f46a74d45ee9bf9f56d15f6f7bd1888058',\n blockHash: '0xfa65496b8cb6ecf5b729892836adf80aa883e6823bbdb2d1b8cdfe61b5c97256',\n blockNumber: 1573,\n address: '0x97519Ada953F882d61625125D5D68E7932250E9F',\n type: 'mined',\n id: 'log_d28138a2',\n returnValues: Result {},\n event: 'eventA',\n signature: '0x72f2637d8047e961ba6b558fdf63d428e9734bdf7ee2fb2b114f3b1aa65335c7',\n raw: { data: '0x', topics: [Array] },\n args: Result { __length__: 0 }\n }\n]\nB\n[\n {\n logIndex: 1,\n transactionIndex: 0,\n transactionHash: '0xe99db12863e5c0a0ae2c9c603d9d29f46a74d45ee9bf9f56d15f6f7bd1888058',\n blockHash: '0xfa65496b8cb6ecf5b729892836adf80aa883e6823bbdb2d1b8cdfe61b5c97256',\n blockNumber: 1573,\n address: '0x00108B6A5572d95Da87e8b4bbF1A3DcA2a565ff7',\n type: 'mined',\n id: 'log_da38637d',\n returnValues: Result {},\n event: 'eventB',\n signature: '0x34a286cd617cdbf745989ac7e8dab3f95e8bb2501bcc48d9b6534b73d055a89c',\n raw: { data: '0x', topics: [Array] },\n args: Result { __length__: 0 }\n }\n]\n ✓ Simple test (76ms)\n```\n\nAs you can see I have to call for every contract independently. I wondered if perhaps there was a \"transaction object\" method to get both of these events in one call - as they, after all, are from the same transaction.\n\nYou can imagine a situation where events were emitted from many contracts in the same transaction.\n\nPerhaps it just isn't possible, but I thought I would ask anyway.\n\n========================================\n\nCode:\n```text\nawait contractInstance.getPastEvents(\"allEvents\", {fromBlock: bn, toBlock: bn});\n```\n\n```text\npragma solidity 0.5.8;\n\ncontract contractA {\n    event eventA();\n    function methodA( address b ) public {\n        emit eventA();\n        contractB instanceB = contractB( b );\n        instanceB.methodB();\n    }\n}\n\ncontract contractB {\n    event eventB();\n    function methodB() public {\n        emit eventB();\n    }\n}\n```\n\n```text\nvar contractA = artifacts.require(\"contractA\");\nvar contractB = artifacts.require(\"contractB\");\n\nmodule.exports = function(deployer) {\n  deployer.deploy(contractA);\n  deployer.deploy(contractB);\n```\n\n```text\nconst contractA = artifacts.require(\"contractA\");\nconst contractB = artifacts.require(\"contractB\");\n\ncontract(\"contractA\", async accounts => {\n\n  thisAccount = accounts[0];\n\n  it( \"Simple test\", async () => {\n\n    const instanceA = await contractA.deployed();\n    const instanceB = await contractB.deployed();\n\n    const transaction = await instanceA.methodA( instanceB.address, { from: thisAccount } );\n\n    const bn = transaction.receipt.blockNumber, txHash = transaction.tx;\n\n    const allEventsA = await instanceA.getPastEvents(\"allEvents\", {fromBlock: bn, toBlock: bn});\n    const allEventsB = await instanceB.getPastEvents(\"allEvents\", {fromBlock: bn, toBlock: bn});\n\n    console.log(\"A\");\n    console.log( allEventsA );\n\n    console.log(\"B\");\n    console.log( allEventsB );\n\n  });\n\n});\n```\n\n```text\n$ truffle test test.js\nUsing network 'development'.\n\n\nCompiling your contracts...\n===========================\n> Everything is up to date, there is nothing to compile.\n  Contract: contractA\nA\n[\n  {\n    logIndex: 0,\n    transactionIndex: 0,\n    transactionHash: '0xe99db12863e5c0a0ae2c9c603d9d29f46a74d45ee9bf9f56d15f6f7bd1888058',\n    blockHash: '0xfa65496b8cb6ecf5b729892836adf80aa883e6823bbdb2d1b8cdfe61b5c97256',\n    blockNumber: 1573,\n    address: '0x97519Ada953F882d61625125D5D68E7932250E9F',\n    type: 'mined',\n    id: 'log_d28138a2',\n    returnValues: Result {},\n    event: 'eventA',\n    signature: '0x72f2637d8047e961ba6b558fdf63d428e9734bdf7ee2fb2b114f3b1aa65335c7',\n    raw: { data: '0x', topics: [Array] },\n    args: Result { __length__: 0 }\n  }\n]\nB\n[\n  {\n    logIndex: 1,\n    transactionIndex: 0,\n    transactionHash: '0xe99db12863e5c0a0ae2c9c603d9d29f46a74d45ee9bf9f56d15f6f7bd1888058',\n    blockHash: '0xfa65496b8cb6ecf5b729892836adf80aa883e6823bbdb2d1b8cdfe61b5c97256',\n    blockNumber: 1573,\n    address: '0x00108B6A5572d95Da87e8b4bbF1A3DcA2a565ff7',\n    type: 'mined',\n    id: 'log_da38637d',\n    returnValues: Result {},\n    event: 'eventB',\n    signature: '0x34a286cd617cdbf745989ac7e8dab3f95e8bb2501bcc48d9b6534b73d055a89c',\n    raw: { data: '0x', topics: [Array] },\n    args: Result { __length__: 0 }\n  }\n]\n    ✓ Simple test (76ms)\n```\n\n```text\ninstanceA.methodA()\n```\n\n```text\nweb3.eth.getTransactionReceipt()\n```\n\n```text\naddress\n```\n\n```text\ndata\n```\n\n```text\ntopics\n```\n\n```text\naddress\n```\n\n```text\ndata\n```\n\n```text\ntopics\n```\n\n```text\naddress\n```\n\n```text\ntopics\n```\n\n```text\nweb3.eth.abi.encodeEventSignature()\n```\n\n```text\nweb3.eth.abi.decodeLog(inputs, hexString, topics)\n```\n\n```text\nweb3.eth.abi.decodeLog([{\n    type: 'string',\n    name: 'myString'\n},{\n    type: 'uint256',\n    name: 'myNumber',\n    indexed: true\n},{\n    type: 'uint8',\n    name: 'mySmallNumber',\n    indexed: true\n}],\n'0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000748656c6c6f252100000000000000000000000000000000000000000000000000',\n['0x000000000000000000000000000000000000000000000000000000000000f310', '0x0000000000000000000000000000000000000000000000000000000000000010']);\n```\n\n========================================\n\nComments:\n- Can you please clarify? Do you want all events from all contracts in a block?\n- Really I would like all the events emitted due to a transaction, but I'd settle for all the events in a block - because then I could filter them based on the event's transaction id - which would accomplish what I want. I have amended the question to reflect this possibility.\n- All events originating from a specific contract?\n- So I call (make transaction) to contractA method, that method emits an event, it also calls contractB method, this method also emits an event. I want to get both events, i.e. all events for my transaction... I feel this is simple, but perhaps I need to explain better.\n- I now give full code example\n- I am going to look into it as soon as I'm available.\n- There is no rush, it is more a curiosity really, as I attempt to improve my solidity skills.","metadata":{"transformedAt":"2026-08-18T18:33:36.115Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":330,"estimatedTokens":2179}}38{"id":"stack-50282211","source":"stackoverflow","questionId":50282211,"title":"Solidity Remix: passing multiple bytes32 type arguments","tags":["arguments","ethereum","solidity","remix"],"text":"Title: Solidity Remix: passing multiple bytes32 type arguments\nTags: arguments, ethereum, solidity, remix\nSource: Stack Overflow\n\nQuestion:\nHow to pass multiple arguments in Remix? No matter which way I pass the arguments to the `setOrder` function, I get different errors:\n\n SyntaxError: Unexpected token in JSON at position 1\n\n \n Error: invalid bytes32 value (arg=undefined, type=\"string\",\n value=\"abc\")\n\nThis is the code:\n\n```\npragma solidity ^0.4.11;\n\ncontract MyContract {\n bytes32 public customer;\n bytes32 public location;\n bytes32 public product;\n bytes32 public reorderAmount;\n bytes32 public usdLitrePrice;\n bytes32 public usdTotalPrice;\n bytes32 public timestamp;\n\n function setOrder(bytes32 _customer, bytes32 _location, bytes32 _product, bytes32 _reorderAmount, \n bytes32 _usdLitrePrice, bytes32 _usdTotalPrice, bytes32 _timestamp) public {\n\n customer = _customer;\n location = _location;\n product = _product;\n reorderAmount = _reorderAmount;\n usdLitrePrice = _usdLitrePrice;\n usdTotalPrice = _usdTotalPrice;\n timestamp = _timestamp;\n }\n\n function getOrder() public constant returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) {\n return (customer, location, product, reorderAmount, usdLitrePrice, usdTotalPrice, timestamp);\n }\n}\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.11;\n\ncontract MyContract {\n    bytes32 public customer;\n    bytes32 public location;\n    bytes32 public product;\n    bytes32 public reorderAmount;\n    bytes32 public usdLitrePrice;\n    bytes32 public usdTotalPrice;\n    bytes32 public timestamp;\n\n    function setOrder(bytes32 _customer, bytes32 _location, bytes32 _product, bytes32 _reorderAmount, \n                    bytes32 _usdLitrePrice, bytes32 _usdTotalPrice, bytes32 _timestamp) public {\n\n        customer = _customer;\n        location = _location;\n        product = _product;\n        reorderAmount = _reorderAmount;\n        usdLitrePrice = _usdLitrePrice;\n        usdTotalPrice = _usdTotalPrice;\n        timestamp = _timestamp;\n    }\n\n    function getOrder() public constant returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) {\n        return (customer, location, product, reorderAmount, usdLitrePrice, usdTotalPrice, timestamp);\n    }\n}\n```\n\n```text\nsetOrder\n```\n\n```text\n'\n```\n\n```text\n\"\n```\n\n```text\n0x...\n```\n\n```text\n\"0x123\",\"0x123\",\"0x123\",\"0x123\",\"0x123\",\"0x123\",\"0x123\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.115Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":97,"estimatedTokens":601}}39{"id":"stack-76680532","source":"stackoverflow","questionId":76680532,"title":"How to convert a Hedera native address into a non-long-zero EVM address?","tags":["javascript","solidity","hedera-hashgraph"],"text":"Title: How to convert a Hedera native address into a non-long-zero EVM address?\nTags: javascript, solidity, hedera-hashgraph\nSource: Stack Overflow\n\nQuestion:\nUsing Hedera SDK JS, I can convert an Account ID to \"long-zero\" format EVM address.\ne.g. `0.0.3996280` --> `0x00000000000000000000000000000000003cfa78`\n\n(See related question: \"How to convert a Hedera native address into an EVM address?\".)\n\nHow do I convert to the \"non-long-zero\" format EVM address?\ne.g. `0.0.3996280` --> `0x7394111093687e9710b7a7aeba3ba0f417c54474`\n\n(See `0.0.3996280` on Hashscan.)\n\nI need this because when you send `ContractCallQuery` via Hedera SDKs, the value of `msg.sender` as visible within any smart contract functions invoked is the \"non-long-zero\" format EVM address.\n\nWhat I'm doing currently:\n\n```\nconst operatorId = AccountId.fromString(process.env.OPERATOR_ID);\nconst operatorEvmAddress = operatorId.toSolidityAddress();\n```\n\nHowever, `operatorEvmAddress` is in the \"long-zero\" format,\nand I therefore cannot use that in my subsequent smart contract interactions.\n\n========================================\n\nTop Answer:\nAs mentioned in Ashe's answer, and requested in David's comment:\n\nIf you do not have access to the account's public key\n...\nYou will need to query the network state, for example through a Hedera mirror node query.​\n\nHere is one way to do it, via the mirror node:\n\n```\ncurl \\\n --silent \\\n -X 'GET' \\\n -H 'accept: application/json' \\\n 'https://testnet.mirrornode.hedera.com/api/v1/accounts/0.0.3996280?limit=1' \\\n | jq --raw-output \".evm_address\"\n```\n\nThis will output:\n\n```\n0x7394111093687e9710b7a7aeba3ba0f417c54474\n```\n\nwhich is indeed the non-long-zero EVM address that corresponds to this account.\n\nRef: Mirror Node Swagger for the above API:\nhttps://testnet.mirrornode.hedera.com/api/v1/docs/#/accounts/getAccountByIdOrAliasOrEvmAddress\n\n========================================\n\nCode:\n```js\nconst operatorId = AccountId.fromString(process.env.OPERATOR_ID);\nconst operatorEvmAddress = operatorId.toSolidityAddress();\n```\n\n```text\n0.0.3996280\n```\n\n```text\n0x00000000000000000000000000000000003cfa78\n```\n\n```text\n0.0.3996280\n```\n\n```text\n0x7394111093687e9710b7a7aeba3ba0f417c54474\n```\n\n```text\n0.0.3996280\n```\n\n```text\nContractCallQuery\n```\n\n```text\nmsg.sender\n```\n\n```text\noperatorEvmAddress\n```\n\n```js\nconst operatorId = AccountId.fromString(process.env.OPERATOR_ID);\nconst operatorPrivateKey = PrivateKey.fromString(process.env.OPERATOR_KEY);\nconst operatorPublicKey = operatorPrivateKey.publicKey;\n​\n// AccountId.toSolidityAddress --> long-zero\nconst operatorEvmAddressLongZero = operatorId.toSolidityAddress();\n​\n// PublicKey.toEvmAddress --> non-long-zero\nconst operatorEvmAddressNonLongZero = operatorPublicKey.toEvmAddress();\n```\n\n```bash\ncurl \\\n  --silent \\\n  -X 'GET' \\\n  -H 'accept: application/json' \\\n  'https://testnet.mirrornode.hedera.com/api/v1/accounts/0.0.3996280?limit=1' \\\n  | jq --raw-output \".evm_address\"\n```\n\n```text\n0x7394111093687e9710b7a7aeba3ba0f417c54474\n```\n\n========================================\n\nComments:\n- Good answer! Welcome to SO. (And ... this answer could be improved if you add the REST call to the mirror node you allude to for the no-public-key case...)","metadata":{"transformedAt":"2026-08-18T18:33:36.115Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":127,"estimatedTokens":804}}40{"id":"stack-48898355","source":"stackoverflow","questionId":48898355,"title":"Soldity: Iterate through address mapping","tags":["blockchain","ethereum","solidity","smartcontracts","ether"],"text":"Title: Soldity: Iterate through address mapping\nTags: blockchain, ethereum, solidity, smartcontracts, ether\nSource: Stack Overflow\n\nQuestion:\nI am looking for a way to iterate through a mapping in Solidity. For example I have this mapping:\n\n`mapping (address => uint) private shares;`\n\nAnd I want to iterate in a function through all addresses and send them ether according to their shares.\n\nSomething like:\n\n```\nfunction giveOutEth() onlyOwner returns (bool success){\nfor(uint i=0; i }\n\nHow can I achieve this?\n\nThanks\n\n========================================\n\nTop Answer:\nIf you want something more general, you can use a library. I've included one I'm using below. It could probably use some improvements (ie, `Element` should be changed to an interface) and it may be overkill (plus, TBH I haven't done any gas consumption comparisons yet). Coming from a more object-oriented background, I prefer using reusable libraries like this, but this is the best I could come up with given Solidity's limitations.\n\nFeel free to use it and/or improve on it.\n\n```\npragma solidity ^0.4.19;\npragma experimental \"ABIEncoderV2\";\n// experimental encoder needed due to https://github.com/ethereum/solidity/issues/3069\n\nlibrary SetLib {\n using SetLib for Set;\n\n struct Set {\n mapping(address => IndexData) _dataMap;\n uint16 _size;\n IndexData[] _dataIndex;\n }\n\n struct IndexData {\n uint16 _index;\n bool _isDeleted;\n Element _element;\n }\n\n struct Element {\n address _value;\n uint8 _status;\n }\n\n function add(Set storage self, Element element) internal returns (bool) {\n if (element._value == 0x0 || self.contains(element)) {\n return false;\n }\n\n IndexData memory data;\n\n data._index = uint16(self._dataIndex.length);\n data._element = element;\n\n self._dataMap[element._value] = data;\n self._dataIndex.push(data);\n self._size++;\n\n return true;\n }\n\n function update(Set storage self, Element element) internal {\n if (element._value != 0x0) {\n IndexData storage data = self._dataMap[element._value];\n\n if (data._element._value == element._value && !data._isDeleted && element._status != data._element._status)\n data._element._status = element._status;\n }\n }\n\n function getByIndex(Set storage self, uint16 index) internal constant returns (Element) {\n IndexData storage data = self._dataIndex[index];\n\n if (!data._isDeleted) {\n return data._element;\n }\n }\n\n function get(Set storage self, address addr) internal constant returns (Element) {\n IndexData storage data = self._dataMap[addr];\n\n if (!data._isDeleted) {\n return data._element;\n }\n }\n\n function contains(Set storage self, Element element) internal constant returns (bool) {\n return self.contains(element._value);\n }\n\n function contains(Set storage self, address addr) internal constant returns (bool) {\n if (addr != 0x0) {\n IndexData storage data = self._dataMap[addr];\n\n return data._index > 0 && !data._isDeleted;\n }\n\n return false;\n }\n\n function remove(Set storage self, uint16 index) internal returns (Element) {\n IndexData storage data = self._dataIndex[index];\n\n if (data._element._value != 0x0 && !data._isDeleted) {\n data._isDeleted = true;\n self._size--;\n return data._element;\n }\n }\n\n function remove(Set storage self, address addr) internal returns (Element) {\n if (addr != 0x0) {\n IndexData storage data = self._dataMap[addr];\n\n if (data._element._value != 0x0 && !data._isDeleted) {\n data._isDeleted = true;\n self._size--;\n return data._element;\n }\n }\n }\n\n function size(Set storage self) internal constant returns (uint16) {\n return self._size;\n }\n}\n\nlibrary IteratorLib {\n using SetLib for SetLib.Set;\n\n struct Iterator {\n bool _started; // using bool instead of making _curIndex int32 for initial state.\n uint16 _curIndex;\n uint16 _size;\n }\n\n function iterator(SetLib.Set storage set) internal constant returns (IteratorLib.Iterator) {\n return IteratorLib.Iterator(false, 0, set.size());\n }\n\n function hasNext(Iterator self, SetLib.Set storage set) internal constant returns (bool) {\n uint16 testIndex = self._curIndex;\n\n while (testIndex < self._size) {\n if (set._dataIndex[testIndex]._element._value != 0x0 && !set._dataIndex[testIndex]._isDeleted)\n return true;\n\n testIndex++;\n }\n\n return false;\n }\n\n function next(Iterator self, SetLib.Set storage set) internal constant returns (SetLib.Element) {\n SetLib.Element memory element;\n\n do {\n if (self._started) {\n self._curIndex++;\n }\n else {\n self._started = true;\n }\n\n element = set.getByIndex(self._curIndex);\n }\n while (element._value != 0x0 && self._curIndex < self._size);\n\n return element;\n }\n}\n```\n\n========================================\n\nCode:\n```text\nfunction giveOutEth() onlyOwner returns (bool success){\nfor(uint i=0; i < shares.length ; i++){\n//get the address and send a value\n}\n```\n\n```text\nmapping (address => uint) private shares;\n```\n\n```text\ncontract  Holders{\n\nuint _totalHolders; // you should initialize this to 0 in the constructor\nmapping (uint=> address ) private holders;\nmapping (address => uint) private shares;\n\nfunction GetShares(uint shares) public {\n    ... \n    holders[_totalHolders] = msg.sender;\n    shares[msg.sender] = shares; \n    _totalHolders++;\n    ...\n} \n\nfunction PayOut() public {\n    ...\n    uint shares;\n    for(uint i = 0 ; i<_totalHolders; i++) {\n        shares = shares[holders[i]];\n        ...\n    }\n    ... \n}\n```\n\n```text\npragma solidity ^0.4.19;\npragma experimental \"ABIEncoderV2\";\n// experimental encoder needed due to https://github.com/ethereum/solidity/issues/3069\n\nlibrary SetLib {\n  using SetLib for Set;\n\n  struct Set {\n    mapping(address => IndexData) _dataMap;\n    uint16 _size;\n    IndexData[] _dataIndex;\n  }\n\n  struct IndexData {\n    uint16 _index;\n    bool _isDeleted;\n    Element _element;\n  }\n\n  struct Element {\n    address _value;\n    uint8 _status;\n  }\n\n  function add(Set storage self, Element element) internal returns (bool) {\n    if (element._value == 0x0 || self.contains(element)) {\n      return false;\n    }\n\n    IndexData memory data;\n\n    data._index = uint16(self._dataIndex.length);\n    data._element = element;\n\n    self._dataMap[element._value] = data;\n    self._dataIndex.push(data);\n    self._size++;\n\n    return true;\n  }\n\n  function update(Set storage self, Element element) internal {\n    if (element._value != 0x0) {\n      IndexData storage data = self._dataMap[element._value];\n\n      if (data._element._value == element._value && !data._isDeleted && element._status != data._element._status)\n        data._element._status = element._status;\n    }\n  }\n\n  function getByIndex(Set storage self, uint16 index) internal constant returns (Element) {\n    IndexData storage data = self._dataIndex[index];\n\n    if (!data._isDeleted) {\n      return data._element;\n    }\n  }\n\n  function get(Set storage self, address addr) internal constant returns (Element) {\n    IndexData storage data = self._dataMap[addr];\n\n    if (!data._isDeleted) {\n      return data._element;\n    }\n  }\n\n  function contains(Set storage self, Element element) internal constant returns (bool) {\n    return self.contains(element._value);\n  }\n\n  function contains(Set storage self, address addr) internal constant returns (bool) {\n    if (addr != 0x0) {\n      IndexData storage data = self._dataMap[addr];\n\n      return data._index > 0 && !data._isDeleted;\n    }\n\n    return false;\n  }\n\n  function remove(Set storage self, uint16 index) internal returns (Element) {\n    IndexData storage data = self._dataIndex[index];\n\n    if (data._element._value != 0x0 && !data._isDeleted) {\n      data._isDeleted = true;\n      self._size--;\n      return data._element;\n    }\n  }\n\n  function remove(Set storage self, address addr) internal returns (Element) {\n    if (addr != 0x0) {\n      IndexData storage data = self._dataMap[addr];\n\n      if (data._element._value != 0x0 && !data._isDeleted) {\n        data._isDeleted = true;\n        self._size--;\n        return data._element;\n      }\n    }\n  }\n\n  function size(Set storage self) internal constant returns (uint16) {\n    return self._size;\n  }\n}\n\nlibrary IteratorLib {\n  using SetLib for SetLib.Set;\n\n  struct Iterator {\n    bool _started; // using bool instead of making _curIndex int32 for initial state.\n    uint16 _curIndex;\n    uint16 _size;\n  }\n\n  function iterator(SetLib.Set storage set) internal constant returns (IteratorLib.Iterator) {\n    return IteratorLib.Iterator(false, 0, set.size());\n  }\n\n  function hasNext(Iterator self, SetLib.Set storage set) internal constant returns (bool) {\n    uint16 testIndex = self._curIndex;\n\n    while (testIndex < self._size) {\n      if (set._dataIndex[testIndex]._element._value != 0x0 && !set._dataIndex[testIndex]._isDeleted)\n        return true;\n\n      testIndex++;\n    }\n\n    return false;\n  }\n\n  function next(Iterator self, SetLib.Set storage set) internal constant returns (SetLib.Element) {\n    SetLib.Element memory element;\n\n    do {\n      if (self._started) {\n        self._curIndex++;\n      }\n      else {\n        self._started = true;\n      }\n\n      element = set.getByIndex(self._curIndex);\n    }\n    while (element._value != 0x0 && self._curIndex < self._size);\n\n    return element;\n  }\n}\n```\n\n```text\nElement\n```\n\n```text\n//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n\nstruct IndexValue {\n    uint256 keyIndex;\n    uint256 value;\n}\n\nstruct KeyFlag {\n    address key;\n    bool deleted;\n}\n\nstruct ItMap {\n    mapping(address => IndexValue) data;\n    KeyFlag[] keys;\n    uint256 size;\n}\n\nlibrary IterableMapping {\n    function insert(\n        ItMap storage self,\n        address key,\n        uint256 value\n    ) internal returns (bool replaced) {\n        uint256 keyIndex = self.data[key].keyIndex;\n        self.data[key].value = value;\n        if (keyIndex > 0) return true;\n        else {\n            keyIndex = self.keys.length;\n            self.keys.push();\n            self.data[key].keyIndex = keyIndex + 1;\n            self.keys[keyIndex].key = key;\n            self.size++;\n            return false;\n        }\n    }\n\n    function remove(ItMap storage self, address key)\n        internal\n        returns (bool success)\n    {\n        uint256 keyIndex = self.data[key].keyIndex;\n        if (keyIndex == 0) return false;\n        delete self.data[key];\n        self.keys[keyIndex - 1].deleted = true;\n        self.size--;\n    }\n\n    function contains(ItMap storage self, address key)\n        internal\n        view\n        returns (bool)\n    {\n        return self.data[key].keyIndex > 0;\n    }\n\n    function start(ItMap storage self)\n        internal\n        view\n        returns (uint256 keyIndex)\n    {\n        uint256 index = next(self, type(uint256).min);\n        return index - 1;\n    }\n\n    function valid(ItMap storage self, uint256 keyIndex)\n        internal\n        view\n        returns (bool)\n    {\n        return keyIndex < self.keys.length;\n    }\n\n    function next(ItMap storage self, uint256 keyIndex)\n        internal\n        view\n        returns (uint256)\n    {\n        keyIndex++;\n        while (keyIndex < self.keys.length && self.keys[keyIndex].deleted)\n            keyIndex++;\n        return keyIndex;\n    }\n\n    function get(ItMap storage self, uint256 keyIndex)\n        internal\n        view\n        returns (address key, uint256 value)\n    {\n        key = self.keys[keyIndex].key;\n        value = self.data[key].value;\n    }\n}\n\ncontract Demo {\n    using IterableMapping for ItMap;\n    ItMap shares;\n\n    function test() public payable {\n        for (uint256 i = shares.start(); shares.valid(i); i = shares.next(i)) {\n            (address k, uint256 v) = shares.get(i);\n            // get the address and send a value\n        }\n    }\n}\n```\n\n========================================\n\nComments:\n- elaborate why your answer is better or an improvement over others posted by updating your answer. Now its just a code dump.","metadata":{"transformedAt":"2026-08-18T18:33:36.115Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":493,"estimatedTokens":2931}}41{"id":"stack-72584559","source":"stackoverflow","questionId":72584559,"title":"How to test the Solidity fallback() function via Hardhat?","tags":["solidity","ethers.js","hardhat","rsk"],"text":"Title: How to test the Solidity fallback() function via Hardhat?\nTags: solidity, ethers.js, hardhat, rsk\nSource: Stack Overflow\n\nQuestion:\nI have a Solidity smart contract `Demo` which I am developing in Hardhat and testing on the RSK Testnet.\n\n```\n//SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\ncontract Demo {\n event Error(string);\n fallback() external {\n emit Error(\"call of a non-existent function\");\n }\n}\n```\n\nI want to make sure that the `fallback` function is called and the event `Error` is emitted. To this end, I am trying to call a `nonExistentFunction` on the smart contract:\n\n```\nconst { expect } = require('chai');\nconst { ethers } = require('hardhat');\n\ndescribe('Demo', () => {\n let deployer;\n let demoContract;\n \n before(async () => {\n [deployer] = await ethers.getSigners();\n const factory = await ethers.getContractFactory('Demo');\n demoContract = await factory.deploy().then((res) => res.deployed());\n });\n \n it('should invoke the fallback function', async () => {\n const tx = demoContract.nonExistentFunction();\n await expect(tx)\n .to.emit(demoContract, 'Error')\n .withArgs('call of a non-existent function');\n });\n});\n```\n\nHowever Hardhat throws a `TypeError` even before it actually connects to the smart contract on RSK:\n\n```\nDemo\n 1) should invoke the fallback function\n\n 0 passing (555ms)\n 1 failing\n\n 1) Demo\n should invoke the fallback function:\n TypeError: demoContract.nonExistentFunction is not a function\n at Context. (test/Demo.js:13:29)\n at processImmediate (internal/timers.js:461:21)\n```\n\nHow can I outsmart Hardhat/Ethers.js and finally be able to call non-existent function thus invoking the `fallback` function in the smart contract?\n\nFor reference, this is my `hardhat.config.js`\n\n```\nrequire('@nomiclabs/hardhat-waffle');\nconst { mnemonic } = require('./.secret.json');\n\nmodule.exports = {\n solidity: '0.8.4',\n networks: {\n hardhat: {},\n rsktestnet: {\n chainId: 31,\n url: 'https://public-node.testnet.rsk.co/',\n accounts: {\n mnemonic,\n path: \"m/44'/60'/0'/0\",\n },\n },\n },\n mocha: {\n timeout: 600000,\n },\n};\n```\n\n========================================\n\nTop Answer:\nA transaction executing a function contains the function selector following its (ABI-encoded) input params in the `data` field.\n\nThe `fallback()` function gets executed when the transaction `data` field starts with a selector that does not match any existing function. For example an empty selector.\n\nSo you can generate a transaction `to` the contract address, with empty `data` field, which invokes the `fallback()` function.\n\n```\nit('should invoke the fallback function', async () => {\n const tx = deployer.sendTransaction({\n to: demoContract.address,\n data: \"0x\",\n });\n await expect(tx)\n .to.emit(demoContract, 'Error')\n .withArgs('call of a non-existent function');\n});\n```\n\n*Note: If you also declared the receive() function, it takes precedence over `fallback()` in case of empty data field. However, `fallback()` still gets executed for every non-empty mismatching selector, while `receive()` is only invoked when the selector is empty.*\n\n========================================\n\nCode:\n```text\n//SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\ncontract Demo {\n    event Error(string);\n    fallback() external {\n      emit Error(\"call of a non-existent function\");\n    }\n}\n```\n\n```js\nconst { expect } = require('chai');\nconst { ethers } = require('hardhat');\n\ndescribe('Demo', () => {\n  let deployer;\n  let demoContract;\n    \n  before(async () => {\n    [deployer] = await ethers.getSigners();\n    const factory = await ethers.getContractFactory('Demo');\n    demoContract = await factory.deploy().then((res) => res.deployed());\n  });\n    \n  it('should invoke the fallback function', async () => {\n    const tx = demoContract.nonExistentFunction();\n    await expect(tx)\n      .to.emit(demoContract, 'Error')\n      .withArgs('call of a non-existent function');\n  });\n});\n```\n\n```text\nDemo\n    1) should invoke the fallback function\n\n\n  0 passing (555ms)\n  1 failing\n\n  1) Demo\n       should invoke the fallback function:\n     TypeError: demoContract.nonExistentFunction is not a function\n      at Context.<anonymous> (test/Demo.js:13:29)\n      at processImmediate (internal/timers.js:461:21)\n```\n\n```js\nrequire('@nomiclabs/hardhat-waffle');\nconst { mnemonic } = require('./.secret.json');\n\nmodule.exports = {\n  solidity: '0.8.4',\n  networks: {\n    hardhat: {},\n    rsktestnet: {\n      chainId: 31,\n      url: 'https://public-node.testnet.rsk.co/',\n      accounts: {\n        mnemonic,\n        path: \"m/44'/60'/0'/0\",\n      },\n    },\n  },\n  mocha: {\n    timeout: 600000,\n  },\n};\n```\n\n```text\nDemo\n```\n\n```text\nfallback\n```\n\n```text\nError\n```\n\n```text\nnonExistentFunction\n```\n\n```text\nTypeError\n```\n\n```text\nfallback\n```\n\n```text\nhardhat.config.js\n```\n\n```js\nconst nonExistentFuncSignature =\n  'nonExistentFunction(uint256,uint256)';\n```\n\n```js\nconst fakeDemoContract = new ethers.Contract(\n  demoContract.address,\n  [\n    ...demoContract.interface.fragments,\n    `function ${nonExistentFuncSignature}`,\n  ],\n  deployer,\n);\n```\n\n```js\nconst tx = fakeDemoContract[nonExistentFuncSignature](8, 9);\nawait expect(tx)\n  .to.emit(demoContract, 'Error')\n  .withArgs('call of a non-existent function');\n```\n\n```js\nit('should invoke the fallback function', async () => {\n    const nonExistentFuncSignature = 'nonExistentFunc(uint256,uint256)';\n    const fakeDemoContract = new ethers.Contract(\n      demoContract.address,\n      [\n        ...demoContract.interface.fragments,\n        `function ${nonExistentFuncSignature}`,\n      ],\n      deployer,\n    );\n    const tx = fakeDemoContract[nonExistentFuncSignature](8, 9);\n    await expect(tx)\n      .to.emit(demoContract, 'Error')\n      .withArgs('call of a non-existent function');\n });\n```\n\n```text\nDemo\n    ✔ should invoke the fallback function (77933ms)\n\n\n  1 passing (2m)\n```\n\n```text\nethers.Contract\n```\n\n```text\nnonExistentFunction\n```\n\n```text\nDemo\n```\n\n```text\nit('should invoke the fallback function', async () => {\n    const tx = deployer.sendTransaction({\n        to: demoContract.address,\n        data: \"0x\",\n    });\n    await expect(tx)\n        .to.emit(demoContract, 'Error')\n        .withArgs('call of a non-existent function');\n});\n```\n\n```text\ndata\n```\n\n```text\nfallback()\n```\n\n```text\ndata\n```\n\n```text\nto\n```\n\n```text\ndata\n```\n\n```text\nfallback()\n```\n\n```text\nfallback()\n```\n\n```text\nfallback()\n```\n\n```text\nreceive()\n```\n\n========================================\n\nComments:\n- Initialise an `ethers.Contract` instance with a modified ABI that includes a function signature that does not exist in the actual contract. With thatyou should be able to write this test.\n- Thanks, I tried your idea, but indeed, If I add the `receive` function to the s/c, it intercepts the `fallback` call. I would like to have a better solution\n- @AleksShenshin If you want to invoke the `fallback()` function while having both `fallback()` and `receive()` declared in the contract, you can pass a non-empty `data` value that does not translate to any function selector. For example: `0x1234`.","metadata":{"transformedAt":"2026-08-18T18:33:36.115Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":29,"totalLines":329,"estimatedTokens":1768}}42{"id":"stack-68773420","source":"stackoverflow","questionId":68773420,"title":"Is there a way for smart contract on RSK to fetch on-chain data from Bitcoin network without using oracles?","tags":["javascript","solidity","bitcoin","rsk"],"text":"Title: Is there a way for smart contract on RSK to fetch on-chain data from Bitcoin network without using oracles?\nTags: javascript, solidity, bitcoin, rsk\nSource: Stack Overflow\n\nQuestion:\nIs there a way for smart contract on RSK to fetch on-chain data on Bitcoin not depending on trusted oracles?\n\nI just found a proposal called Open Bitcoin blockchain oracle (RSKIP220) which will be implemented from the IRIS upgrade but couldn't find any resources on it. Does anybody know where I can find it?\n\nBlog post mentioning RSKIP220: https://blog.rsk.co/noticia/iris-v3-0-0-is-here-what-you-need-to-know-about-rsk-upcoming-network-upgrade/\n\n========================================\n\nTop Answer:\nRSKIP220 has indeed been been included in the IRIS 3.0.0 release of RSKj,\nand you can see part of the implementation:\n\nHere in `RepositoryBtcBlockStoreWithCache`\n\n```\npublic StoredBlock getStoredBlockAtMainChainHeight(int height) throws BlockStoreException {\n```\n\n... and here in `BridgeMethods`\n\n```\nGET_BTC_BLOCKCHAIN_PARENT_BLOCK_HEADER_BY_HASH(\n CallTransaction.Function.fromSignature(\n \"getBtcBlockchainParentBlockHeaderByHash\",\n new String[]{\"bytes32\"},\n new String[]{\"bytes\"}\n```\n\nNote that these methods are **not** exposed externally through a special RPC or something similar to that. Instead they are available on the RSK Bridge, via precompiled functions. Precompiled functions are functions that are included within the implementation of the RSK node itself, but exposed as if they were a smart contract.\n\nThis means that you can interact with them both\n\n- off-chain, for example in a DApp, using web3.js, ethers.js, etc\n\n- on-chain, for example within your own smart contract\n\nTo do so, you can use the ABI for the RSK Bridge:\n\n```\n{\n \"name\": \"getBtcBlockchainParentBlockHeaderByHash\",\n \"type\": \"function\",\n \"constant\": true,\n \"inputs\": [\n {\n \"name\": \"btcBlockHash\", \n \"type\": \"bytes32\" \n }\n ],\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"bytes\"\n }\n ]\n },\n```\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.0 <0.9.0;\n\ninterface Bridge {\n  function getBtcBlockchainBestChainHeight (  ) external view returns ( int );\n  function getStateForBtcReleaseClient (  ) external view returns ( bytes memory);\n  function getStateForDebugging (  ) external view returns ( bytes memory  );\n  function getBtcBlockchainInitialBlockHeight (  ) external view returns ( int );\n  function getBtcBlockchainBlockHashAtDepth ( int256 depth ) external view returns ( bytes memory );\n  function getBtcTxHashProcessedHeight ( string calldata hash ) external view returns ( int64 );\n  function isBtcTxHashAlreadyProcessed ( string calldata hash ) external view returns ( bool );\n  function getFederationAddress (  ) external view returns ( string memory );\n  function registerBtcTransaction ( bytes calldata atx, int256 height, bytes calldata pmt ) external;\n  function addSignature ( bytes calldata pubkey, bytes[] calldata signatures, bytes calldata txhash ) external;\n  function receiveHeaders ( bytes[] calldata blocks ) external;\n  function receiveHeader ( bytes calldata ablock ) external returns ( int256 );\n  function getFederationSize (  ) external view returns ( int256 );\n  function getFederationThreshold (  ) external view returns ( int256 );\n  function getFederatorPublicKey ( int256 index ) external view returns ( bytes memory);\n  function getFederatorPublicKeyOfType ( int256 index, string calldata atype ) external returns ( bytes memory);\n  function getFederationCreationTime (  ) external view returns ( int256 );\n  function getFederationCreationBlockNumber (  ) external view returns ( int256 );\n  function getRetiringFederationAddress (  ) external view returns ( string memory );\n  function getRetiringFederationSize (  ) external view returns ( int256 );\n  function getRetiringFederationThreshold (  ) external view returns ( int256 );\n  function getRetiringFederatorPublicKey ( int256 index ) external view returns ( bytes memory);\n  function getRetiringFederatorPublicKeyOfType ( int256 index,string calldata atype ) external view returns ( bytes memory);\n  function getRetiringFederationCreationTime (  ) external view returns ( int256 );\n  function getRetiringFederationCreationBlockNumber (  ) external view returns ( int256 );\n  function createFederation (  ) external returns ( int256 );\n  function addFederatorPublicKey ( bytes calldata  key ) external returns ( int256 );\n  function addFederatorPublicKeyMultikey ( bytes calldata btcKey, bytes calldata rskKey, bytes calldata mstKey ) external returns ( int256 );\n  function commitFederation ( bytes calldata hash ) external returns ( int256 );\n  function rollbackFederation (  ) external returns ( int256 );\n  function getPendingFederationHash (  ) external view returns ( bytes memory);\n  function getPendingFederationSize (  ) external view  returns ( int256 );\n  function getPendingFederatorPublicKey ( int256 index ) external view returns ( bytes memory);\n  function getPendingFederatorPublicKeyOfType ( int256 index, string calldata atype ) external view returns ( bytes memory);\n  function getLockWhitelistSize (  ) external view returns ( int256 );\n  function getLockWhitelistAddress ( int256 index ) external view returns ( string memory);\n  function getLockWhitelistEntryByAddress ( string calldata aaddress ) external view  returns ( int256 );\n  function addLockWhitelistAddress ( string calldata aaddress, int256 maxTransferValue ) external returns ( int256 );\n  function addOneOffLockWhitelistAddress ( string calldata aaddress, int256 maxTransferValue ) external returns ( int256 );\n  function addUnlimitedLockWhitelistAddress ( string calldata aaddress ) external returns ( int256 ); \n  function removeLockWhitelistAddress ( string calldata aaddress ) external returns ( int256 );\n  function setLockWhitelistDisableBlockDelay ( int256 disableDelay ) external returns ( int256 );\n  function getFeePerKb (  ) external view returns ( int256 );\n  function voteFeePerKbChange ( int256 feePerKb ) external returns ( int256 );\n  function updateCollections (  ) external;\n  function getMinimumLockTxValue (  ) external view returns ( int256 );\n  function getBtcTransactionConfirmations ( bytes32  txHash, bytes32 blockHash, uint256 merkleBranchPath, bytes32[] calldata merkleBranchHashes ) external view returns ( int256 );\n  function getLockingCap (  ) external view returns ( int256 );\n  function increaseLockingCap ( int256 newLockingCap ) external returns ( bool );\n  function registerBtcCoinbaseTransaction ( bytes calldata btcTxSerialized, bytes32 blockHash, bytes calldata pmtSerialized, bytes32 witnessMerkleRoot, bytes32 witnessReservedValue ) external;\n  function hasBtcBlockCoinbaseTransactionInformation ( bytes32 blockHash ) external returns ( bool );\n  function registerFastBridgeBtcTransaction ( bytes calldata btcTxSerialized, uint256 height, bytes calldata pmtSerialized, bytes32 derivationArgumentsHash, bytes calldata userRefundBtcAddress, address liquidityBridgeContractAddress, bytes calldata liquidityProviderBtcAddress, bool shouldTransferToContract ) external returns ( int256 );\n  function getActiveFederationCreationBlockHeight (  ) external view  returns ( uint256 );\n  function getBtcBlockchainBestBlockHeader (  ) external view  returns ( bytes memory );\n  function getBtcBlockchainBlockHeaderByHash ( bytes32 btcBlockHash ) external view returns ( bytes memory );\n  function getBtcBlockchainBlockHeaderByHeight ( uint256 btcBlockHeight ) external view  returns ( bytes memory );\n  function getBtcBlockchainParentBlockHeaderByHash ( bytes32 btcBlockHash ) external view  returns ( bytes memory);\n}\n```\n\n```text\n// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.0 <0.9.0;\n\nimport \"./Bridge.sol\";\n\ncontract QueryDemo {\n    int public bestChainHeight;\n    bytes public returned;\n    bytes32 public headerHash;\n    \n    function reverse(uint256 input) internal pure returns (uint256 v) {\n        v = input;\n    \n        // swap bytes\n        v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8) |\n            ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);\n    \n        // swap 2-byte long pairs\n        v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16) |\n            ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);\n    \n        // swap 4-byte long pairs\n        v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32) |\n            ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);\n    \n        // swap 8-byte long pairs\n        v = ((v & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64) |\n            ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);\n    \n        // swap 16-byte long pairs\n        v = (v >> 128) | (v << 128);\n    }\n\n    function clear() public   {\n        headerHash =0;\n        returned = \"\";\n    } \n    \n    function getBridge() private pure returns (Bridge) {\n        return Bridge(address(0x01000006));\n    }\n    \n    function getBtcBlockchainBestChainHeight() public {\n        bestChainHeight = getBridge().getBtcBlockchainBestChainHeight();\n    }\n    \n    // getBtcBlockchainBlockHashAtDepth:\n    // This method throws an OOG because getBtcBlockchainBlockHashAtDepth() cannot be called\n    // from a contract. Use getBtcBlockchainBestChainHeigh() and getBtcBlockchainBlockHeaderByHeight()\n    // \n    function storeBtcBlockchainBlockHashAtDepth(int256 depth) public  {\n      returned  = getBridge().getBtcBlockchainBlockHashAtDepth(depth); \n    }\n    \n    function getHeaderHash(bytes memory x) private pure returns(bytes32) {\n        bytes32 h = sha256(x);\n        bytes32 h2 = sha256(abi.encodePacked(h));\n        return bytes32(reverse(uint256(h2))); // to show it like Bitcoin does on the debugger \n    }\n    \n    function computeHeaderHash() private {\n        headerHash = getHeaderHash(returned);\n    }\n    \n    function storeBtcBlockchainBestBlockHeader (  ) external {\n        returned = getBridge().getBtcBlockchainBestBlockHeader();\n        computeHeaderHash();\n    }\n    \n    function getBtcBlockchainBestBlockHeader (  ) external view returns (bytes memory) {\n        return getBridge().getBtcBlockchainBestBlockHeader();\n   \n    }\n    \n    function storeBtcBlockchainBlockHeaderByHash ( bytes32 btcBlockHash ) external {\n        returned = getBridge().getBtcBlockchainBlockHeaderByHash ( btcBlockHash );\n        computeHeaderHash();\n    }\n    \n    function getBtcBlockchainBlockHeaderByHash ( bytes32 btcBlockHash ) external view returns (bytes memory) {\n        return  getBridge().getBtcBlockchainBlockHeaderByHash ( btcBlockHash );\n    }\n    \n    function storeBtcBlockchainBlockHeaderByHeight ( uint256 btcBlockHeight ) external {\n        returned = getBridge().getBtcBlockchainBlockHeaderByHeight (btcBlockHeight);\n        computeHeaderHash();\n    }\n    \n    function getBtcBlockchainBlockHeaderByHeight ( uint256 btcBlockHeight ) external view returns(bytes memory ret) {\n        return getBridge().getBtcBlockchainBlockHeaderByHeight (btcBlockHeight);\n    }\n    \n    function storeBtcBlockchainParentBlockHeaderByHash ( bytes32 btcBlockHash ) external {\n        returned = getBridge().getBtcBlockchainParentBlockHeaderByHash ( btcBlockHash);\n        computeHeaderHash();\n    }\n    \n    function getBtcBlockchainParentBlockHeaderByHash ( bytes32 btcBlockHash ) external view returns(bytes memory ret) {\n        return  getBridge().getBtcBlockchainParentBlockHeaderByHash ( btcBlockHash);\n    }\n    \n    function testGetParentParentHeader() public view returns(bytes memory ret) {\n        bytes memory x = getBridge().getBtcBlockchainBlockHeaderByHeight (2064695);\n        bytes32  h =getHeaderHash(x);    \n        \n        // now the has has been computed. Use the has to get the parent block header\n        ret=getBridge().getBtcBlockchainParentBlockHeaderByHash ( h);\n    }\n    \n    function testStoreGetParentHeader() public {\n        returned = getBridge().getBtcBlockchainBlockHeaderByHeight (2064695);\n        computeHeaderHash();    \n        \n        // now the has has been computed. Use the has to get the parent block header\n        returned = getBridge().getBtcBlockchainParentBlockHeaderByHash ( headerHash);\n        computeHeaderHash();\n    }\n}\n```\n\n```java\npublic StoredBlock getStoredBlockAtMainChainHeight(int height) throws BlockStoreException {\n```\n\n```java\nGET_BTC_BLOCKCHAIN_PARENT_BLOCK_HEADER_BY_HASH(\n            CallTransaction.Function.fromSignature(\n                    \"getBtcBlockchainParentBlockHeaderByHash\",\n                    new String[]{\"bytes32\"},\n                    new String[]{\"bytes\"}\n```\n\n```json\n{\n    \"name\": \"getBtcBlockchainParentBlockHeaderByHash\",\n    \"type\": \"function\",\n    \"constant\": true,\n    \"inputs\": [\n      {\n        \"name\": \"btcBlockHash\", \n        \"type\": \"bytes32\" \n      }\n    ],\n    \"outputs\": [\n      {\n        \"name\": \"\",\n        \"type\": \"bytes\"\n      }\n    ]\n  },\n```\n\n```text\nRepositoryBtcBlockStoreWithCache\n```\n\n```text\nBridgeMethods\n```\n\n========================================\n\nComments:\n- Thanks. Do you know if a contract importing Bridge contract interface can extract a couple of data such as difficulty, number of txs, and timestamp from the latest bitcoin block?\n- Difficulty yes. Timestamp yes. Number of Txs requires that you show a Merkle path with a leaf node that is bigger than 64 bytes. That will provide the Merkle tree depth, and from that you can infer the number of transactions (bounded by a power of 2). There are other ways to obtain the exact number, by showing the depth and two right-most elements with the same hash.","metadata":{"transformedAt":"2026-08-18T18:33:36.115Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":297,"estimatedTokens":3444}}43{"id":"stack-43016011","source":"stackoverflow","questionId":43016011,"title":"Getting the length of public array variable (getter)","tags":["ethereum","contract","solidity"],"text":"Title: Getting the length of public array variable (getter)\nTags: ethereum, contract, solidity\nSource: Stack Overflow\n\nQuestion:\nI am trying to get the length of array from another contact. How?\n\n```\ncontract Lottery {\n unint[] public bets;\n}\n\ncontract CheckLottery {\n function CheckLottery() {\n Lottery.bets.length;\n }\n}\n```\n\n========================================\n\nCode:\n```text\ncontract Lottery {\n    unint[] public bets;\n}\n\ncontract CheckLottery {\n    function CheckLottery() {\n        Lottery.bets.length;\n    }\n}\n```\n\n```text\npragma solidity ^0.4.8;\n\ncontract Lottery {\n\n    uint[] public bets;\n\n    function getBetCount()\n        public \n        constant\n        returns(uint betCount)\n    {\n        return bets.length;\n    }\n}\n\ncontract CheckLottery {\n\n    Lottery l;\n\n    function CheckLottery(address lottery) {\n        l = Lottery(lottery);\n    }\n\n    function checkLottery() \n        public\n        constant\n        returns(uint count) \n    {\n        return l.getBetCount();\n    }\n}\n```\n\n========================================\n\nComments:\n- Yes it seems that, that property (method) is not exposed by default.\n- Just wondering why the `getBetCount()` has 6 lines? I don't have VR 360 space dome code environment, I much prefer preserve screen real estate...\n- Do we know why we have to use a `getter` for arrays but for primatives like `uint256` we can just call them like in this: ethereum.stackexchange.com/questions/38317/&hellip;\n- If I understand the question ... You can use the \"free\" getter for `public` array *element* but there is no \"free\" getter for the `length` *property* of the array or the entire array. Passing entire arrays around should be avoided unless you really understand the implications.","metadata":{"transformedAt":"2026-08-18T18:33:36.115Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":75,"estimatedTokens":432}}44{"id":"stack-70974677","source":"stackoverflow","questionId":70974677,"title":"Warning: Unused local variable. (bool sent, bytes memory data) = _charity.call{value: msg.value}(\"\");","tags":["solidity"],"text":"Title: Warning: Unused local variable. (bool sent, bytes memory data) = _charity.call{value: msg.value}(\"\");\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\n```\ncontracts/Test.sol:128:21: Warning: Unused local variable.\n(bool sent, bytes memory data) = _charity.call{value: msg.value}(\"\");\n^---------------^\n```\n\n```\n(bool sent, bytes memory data) = _charity.call{value: msg.value}(\"\");\n require(sent, \"DONATION_FAILED\");\n```\n\n========================================\n\nCode:\n```text\ncontracts/Test.sol:128:21: Warning: Unused local variable.\n(bool sent, bytes memory data) = _charity.call{value: msg.value}(\"\");\n^---------------^\n```\n\n```text\n(bool sent, bytes memory data) = _charity.call{value: msg.value}(\"\");\n        require(sent, \"DONATION_FAILED\");\n```\n\n```text\n// removed the declaration of `data`\n(bool sent,) = _charity.call{value: msg.value}(\"\");\nrequire(sent, \"DONATION_FAILED\");\n```\n\n```text\nsent\n```\n\n```text\ndata\n```\n\n========================================\n\nComments:\n- What is your question exactly?\n- Thank you so much. It's worked","metadata":{"transformedAt":"2026-08-18T18:33:36.115Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":49,"estimatedTokens":263}}45{"id":"stack-57464939","source":"stackoverflow","questionId":57464939,"title":"Solidity: How to compile multiple smart contracts in compile.js file?","tags":["javascript","ethereum","solidity","web3js"],"text":"Title: Solidity: How to compile multiple smart contracts in compile.js file?\nTags: javascript, ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI would like to compile multiple contracts in one compile.js file but I'm not sure how to do it.\n\nMy compile.js file with a single contract looks like this:\n\n```\nconst path = require('path');\nconst fs = require('fs');\nconst solc = require('solc');\n\nconst lotteryPath = path.resolve(__dirname, 'contracts', 'Lottery.sol');\n\nconst source = fs.readFileSync(lotteryPath, 'utf8');\n\nmodule.exports = solc.compile(source, 1);\n```\n\nHow can I add more contracts to the compile.js file? I understand that the 1 must be changed to the number of contracts, but not sure what else is required?\n\n========================================\n\nTop Answer:\nThe approved solution does not work for **solidity** `>0.6.0` and `For the mentioned versions, I solved it as follows:\n\n```\nconst path = require(\"path\");\nconst fs = require(\"fs-extra\");\nconst solc = require(\"solc\");\n\nconst buildPath = path.resolve(__dirname, \"build\");\nfs.removeSync(buildPath);\n\nconst contractPath = path.resolve(__dirname, \"contracts\");\nconst fileNames = fs.readdirSync(contractPath);\n\nconst compilerInput = {\n language: \"Solidity\",\n sources: fileNames.reduce((input, fileName) => {\n const filePath = path.resolve(contractPath, fileName);\n const source = fs.readFileSync(filePath, \"utf8\");\n return { ...input, [fileName]: { content: source } };\n }, {}),\n settings: {\n outputSelection: {\n \"*\": {\n \"*\": [\"abi\", \"evm.bytecode.object\"],\n },\n },\n },\n};\n\n// Compile All contracts\nconst compiled = JSON.parse(solc.compile(JSON.stringify(compilerInput)));\n\nfs.ensureDirSync(buildPath);\n\nfileNames.map((fileName) => {\n const contracts = Object.keys(compiled.contracts[fileName]);\n contracts.map((contract) => {\n fs.outputJsonSync(\n path.resolve(buildPath, contract + \".json\"),\n compiled.contracts[fileName][contract]\n );\n });\n});\n```\n\nbe sure to check that your `pragma solidity x.x.x` matches with the version specified in your `package.json`. For example, if I'm using `solidity 0.6.12` my solidity compiles would be:\n\n```\n\"dependencies\": {\n ...\n \"solc\": \"^0.6.12\",\n ...\n }\n```\n\n========================================\n\nCode:\n```js\nconst path = require('path');\nconst fs = require('fs');\nconst solc = require('solc');\n\nconst lotteryPath = path.resolve(__dirname, 'contracts', 'Lottery.sol');\n\nconst source = fs.readFileSync(lotteryPath, 'utf8');\n\nmodule.exports = solc.compile(source, 1);\n```\n\n```text\nconst path = require(\"path\"); //nodejs ’path’ module\n    const solc = require(\"solc\"); //solidity compiler module\n    const fs = require(\"fs-extra\"); //file system module\n\n    // Feth path of build\n    const buildPath = path.resolve(__dirname, \"build\");\n    const contractspath = path.resolve(__dirname, \"contracts\");\n\n    // Removes folder build and every file in it\n    fs.removeSync(buildPath);\n\n    // Fetch all Contract files in Contracts folder\n    const fileNames = fs.readdirSync(contractspath);\n\n    // Gets ABI of all contracts into variable input\n    const input = fileNames.reduce(\n      (input, fileName) => {\n        const filePath = path.resolve(__dirname, \"contracts\", fileName);\n        const source = fs.readFileSync(filePath, \"utf8\");\n        return { sources: { ...input.sources, [fileName]: source } };\n      },\n      { sources: {} }\n    );\n\n    // Compile all contracts\n    const output = solc.compile(input, 1).contracts;\n\n    // Re-Create build folder for output files from each contract\n    fs.ensureDirSync(buildPath);\n\n    // Output contains all objects from all contracts\n    // Write the contents of each to different files\n    for (let contract in output) {\n      fs.outputJsonSync(\n        path.resolve(buildPath, contract.split(\":\")[1] + \".json\"),\n        output[contract]\n      );\n    }\n```\n\n```text\n// Feth path of build\n        const buildPath = path.resolve(__dirname, \"build\");\n        const contractspath = path.resolve(__dirname, \"contracts\");\n```\n\n```js\nconst path = require(\"path\");\nconst fs = require(\"fs-extra\");\nconst solc = require(\"solc\");\n\nconst buildPath = path.resolve(__dirname, \"build\");\nfs.removeSync(buildPath);\n\nconst contractPath = path.resolve(__dirname, \"contracts\");\nconst fileNames = fs.readdirSync(contractPath);\n\nconst compilerInput = {\n  language: \"Solidity\",\n  sources: fileNames.reduce((input, fileName) => {\n    const filePath = path.resolve(contractPath, fileName);\n    const source = fs.readFileSync(filePath, \"utf8\");\n    return { ...input, [fileName]: { content: source } };\n  }, {}),\n  settings: {\n    outputSelection: {\n      \"*\": {\n        \"*\": [\"abi\", \"evm.bytecode.object\"],\n      },\n    },\n  },\n};\n\n// Compile All contracts\nconst compiled = JSON.parse(solc.compile(JSON.stringify(compilerInput)));\n\nfs.ensureDirSync(buildPath);\n\nfileNames.map((fileName) => {\n  const contracts = Object.keys(compiled.contracts[fileName]);\n  contracts.map((contract) => {\n    fs.outputJsonSync(\n      path.resolve(buildPath, contract + \".json\"),\n      compiled.contracts[fileName][contract]\n    );\n  });\n});\n```\n\n```js\n\"dependencies\": {\n    ...\n    \"solc\": \"^0.6.12\",\n    ...\n  }\n```\n\n```text\n>0.6.0\n```\n\n```text\n<=0.8.1\n```\n\n```text\npragma solidity x.x.x\n```\n\n```text\npackage.json\n```\n\n```text\nsolidity 0.6.12\n```\n\n```text\nconst path= require('path');\nconst solc = require('solc');\nconst fs = require('fs-extra');\n\nconst builtPath = path.resolve(__dirname, 'build');\n//remove file in build module\nfs.removeSync(builtPath);\nconst healthPath = path.resolve(__dirname, 'contract','health.sol');\n//read  content present in file\nconsole.log(healthPath);\nconst source = fs.readFileSync(healthPath,'utf8');\n//compile contract\nconst output = solc.compile(source,1).contracts;\n//create build folder\n\nfs.ensureDirSync(builtPath);\nconsole.log(output);\n\n\nfor(let contract in output)\n{\n    fs.outputJsonSync(\n      path.resolve(buildPath, contract.replace(':','')+ '.json'),\n      output[contract]\n  );\n}\n```\n\n========================================\n\nComments:\n- It does not seems like for solidity version but for npm solc changes","metadata":{"transformedAt":"2026-08-18T18:33:36.115Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":247,"estimatedTokens":1521}}46{"id":"stack-45539031","source":"stackoverflow","questionId":45539031,"title":"VM Exception while processing transaction: out of gas","tags":["ethereum","solidity","smartcontracts","web3js"],"text":"Title: VM Exception while processing transaction: out of gas\nTags: ethereum, solidity, smartcontracts, web3js\nSource: Stack Overflow\n\nQuestion:\nI am using testrpc, web3 1.0 and solidity to build a simple Dapp, but I'm always getting this error and I can't find what is wrong. Please help.\n\nMy javascript file:\n\n```\nconst Web3 = require('web3');\nconst fs = require('fs');\n\nconst web3 = new Web3(new Web3.providers.HttpProvider(\"http://localhost:8545\"));\n\nconst code = fs.readFileSync('Voting.sol').toString();\nconst solc = require('solc');\nconst compiledCode = solc.compile(code);\n\n// deploy contract\nconst abiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface);\nconst VotingContract = new web3.eth.Contract(abiDefinition);\nconst byteCode = compiledCode.contracts[':Voting'].bytecode;\nconst deployedContract = VotingContract\n.deploy({data: byteCode, arguments: [['a','b','c']]})\n.send({\n from: '0x386fd5fbe3804f24b35477f06aa78a178ce021bd',\n gas: 4700000,\n gasPrice: '2000000000'\n}, function(error, transactionHash) {})\n.on('error', function(error){})\n.on('transactionHash', function(transactionHash){})\n.on('receipt', function(receipt){\n console.log(receipt.contractAddress);\n})\n.then(function(newContractInstance) {\n newContractInstance.methods.getList().call({from: '0x386fd5fbe3804f24b35477f06aa78a178ce021bd'}).then(console.log);\n});\n```\n\nMy contract file:\n\n```\npragma solidity ^0.4.11;\n// We have to specify what version of compiler this code will compile with\n\ncontract Voting {\n /* mapping field below is equivalent to an associative array or hash.\n The key of the mapping is candidate name stored as type bytes32 and value is\n an unsigned integer to store the vote count\n */\n\n mapping (bytes32 => uint8) public votesReceived;\n\n /* Solidity doesn't let you pass in an array of strings in the constructor (yet).\n We will use an array of bytes32 instead to store the list of candidates\n */\n\n bytes32[] public candidateList;\n\n /* This is the constructor which will be called once when you\n deploy the contract to the blockchain. When we deploy the contract,\n we will pass an array of candidates who will be contesting in the election\n */\n function Voting(bytes32[] candidateNames) {\n candidateList = candidateNames;\n }\n\n function getList() returns (bytes32[]) {\n return candidateList;\n }\n\n // This function returns the total votes a candidate has received so far\n function totalVotesFor(bytes32 candidate) returns (uint8) {\n require(validCandidate(candidate) == false);\n return votesReceived[candidate];\n }\n\n // This function increments the vote count for the specified candidate. This\n // is equivalent to casting a vote\n function voteForCandidate(bytes32 candidate) {\n require(validCandidate(candidate) == false);\n votesReceived[candidate] += 1;\n }\n\n function validCandidate(bytes32 candidate) returns (bool) {\n for(uint i = 0; i Also, I'm starting the testrpc using the following command:\n\ntestrpc --account=\"0xce2ddf7d4509856c2b7256d002c004db6e34eeb19b37cee04f7b493d2b89306d, 2000000000000000000000000000000\"\n\nAny help would be appreciated.\n\n========================================\n\nCode:\n```text\nconst Web3 = require('web3');\nconst fs = require('fs');\n\nconst web3 = new Web3(new Web3.providers.HttpProvider(\"http://localhost:8545\"));\n\nconst code = fs.readFileSync('Voting.sol').toString();\nconst solc = require('solc');\nconst compiledCode = solc.compile(code);\n\n// deploy contract\nconst abiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface);\nconst VotingContract = new web3.eth.Contract(abiDefinition);\nconst byteCode = compiledCode.contracts[':Voting'].bytecode;\nconst deployedContract = VotingContract\n.deploy({data: byteCode, arguments: [['a','b','c']]})\n.send({\n  from: '0x386fd5fbe3804f24b35477f06aa78a178ce021bd',\n  gas: 4700000,\n  gasPrice: '2000000000'\n}, function(error, transactionHash) {})\n.on('error', function(error){})\n.on('transactionHash', function(transactionHash){})\n.on('receipt', function(receipt){\n   console.log(receipt.contractAddress);\n})\n.then(function(newContractInstance) {\n  newContractInstance.methods.getList().call({from: '0x386fd5fbe3804f24b35477f06aa78a178ce021bd'}).then(console.log);\n});\n```\n\n```text\npragma solidity ^0.4.11;\n// We have to specify what version of compiler this code will compile with\n\ncontract Voting {\n  /* mapping field below is equivalent to an associative array or hash.\n  The key of the mapping is candidate name stored as type bytes32 and value is\n  an unsigned integer to store the vote count\n  */\n\n  mapping (bytes32 => uint8) public votesReceived;\n\n  /* Solidity doesn't let you pass in an array of strings in the constructor (yet).\n  We will use an array of bytes32 instead to store the list of candidates\n  */\n\n  bytes32[] public candidateList;\n\n  /* This is the constructor which will be called once when you\n  deploy the contract to the blockchain. When we deploy the contract,\n  we will pass an array of candidates who will be contesting in the election\n  */\n  function Voting(bytes32[] candidateNames) {\n    candidateList = candidateNames;\n  }\n\n  function getList() returns (bytes32[]) {\n    return candidateList;\n  }\n\n  // This function returns the total votes a candidate has received so far\n  function totalVotesFor(bytes32 candidate) returns (uint8) {\n    require(validCandidate(candidate) == false);\n    return votesReceived[candidate];\n  }\n\n  // This function increments the vote count for the specified candidate. This\n  // is equivalent to casting a vote\n  function voteForCandidate(bytes32 candidate) {\n    require(validCandidate(candidate) == false);\n    votesReceived[candidate] += 1;\n  }\n\n  function validCandidate(bytes32 candidate) returns (bool) {\n    for(uint i = 0; i < candidateList.length; i++) {\n      if (candidateList[i] == candidate) {\n        return true;\n      }\n    }\n    return false;\n  }\n}\n```\n\n```text\nfunction getList() constant returns (bytes32[]) {\n  return candidateList;\n}\n```\n\n```text\npragma solidity ^0.4.11;\n// We have to specify what version of compiler this code will compile with\n\ncontract Voting {\n  /* mapping field below is equivalent to an associative array or hash.\n  The key of the mapping is candidate name stored as type bytes32 and value is\n  an unsigned integer to store the vote count\n  */\n\n  mapping (bytes32 => uint8) public votesReceived;\n  mapping (bytes32 => bool) public validCandidates;\n\n  /* This is the constructor which will be called once when you\n  deploy the contract to the blockchain. When we deploy the contract,\n  we will pass an array of candidates who will be contesting in the election\n  */\n  function Voting(bytes32[] candidateList) {\n    for (uint i = 0; i < candidateList.length; i++) {\n      validCandidates[candidateList[i]] = true;\n    }\n  }\n\n  // This function returns the total votes a candidate has received so far\n  function totalVotesFor(bytes32 candidate) constant returns (uint8) {\n    return votesReceived[candidate];\n  }\n\n  // This function increments the vote count for the specified candidate. This\n  // is equivalent to casting a vote\n  function voteForCandidate(bytes32 candidate) onlyForValidCandidate(candidate) {\n    votesReceived[candidate] += 1;\n  }\n\n  function isValidCandidate(bytes32 candidate) constant returns (bool)  {\n    return validCandidates[candidate];\n  }\n\n  modifier onlyForValidCandidate(bytes32 candidate) {\n    require(isValidCandidate(candidate));\n    _;\n  }\n}\n```\n\n```text\nconstant\n```\n\n```text\ncandidateList\n```\n\n```text\nnewContractInstance.candidateList()\n```\n\n```text\nmapping(bytes32 => bool) public validCandidates\n```\n\n========================================\n\nComments:\n- I know it took me a while :D why is a loop in the constructor better than in another function?\n- In this particular contract you have to have the loop in the constructor. If it was in another function, anyone could call it unless you implemented permissions. Loops aren't bad, per se but you have to be aware about the gas cost","metadata":{"transformedAt":"2026-08-18T18:33:36.115Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":252,"estimatedTokens":1983}}47{"id":"stack-58047855","source":"stackoverflow","questionId":58047855,"title":"\"Web3ProviderEngine does not support synchronous requests\" when running truffle migrate","tags":["ethereum","solidity","web3js","truffle"],"text":"Title: \"Web3ProviderEngine does not support synchronous requests\" when running truffle migrate\nTags: ethereum, solidity, web3js, truffle\nSource: Stack Overflow\n\nQuestion:\nI wanted to config my truffle-config.js with provider. When I run command \"truffle migrate --network ropsten\", it throws this error:\n\nError: Web3ProviderEngine does not support synchronous requests.\n\nAnd the error details told\n\n`at Object.run (C:\\Users\\Bruce\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\packages\\truffle-migrate\\index.js:92:1)`\n\nI have no idea about this. I look for the file\n**\"C:\\Users\\Bruce\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\packages\\truffle-migrate\\index.js:92:1\"**, but I cannot find the path `webpack` under the `\"build/\"`. Is it somethind wrong? I install truffle with global and it runs well with default network ganache.\n\n```\nropsten: {\n provider: () => new HDWalletProvider(\n privateKeys.split(','),\n `https://ropsten.infura.io/v3/${process.env.INFURA_API_KEY}`\n ),\n network_id: 3, // Ropsten's id, mainnet is 1\n gas: 5500000, // Ropsten has a lower block limit than mainnet\n gasPrice: 2500000000, //2.5 gwei\n confirmations: 2, // # of confs to wait between deployments. (default: 0)\n timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)\n skipDryRun: true // Skip dry run before migrations? (default: false for public nets )\n },\n```\n\nMy HDWalletProvider dependency version:\n\n```\n\"dependencies\": {\n \"chai\": \"^4.2.0\",\n \"chai-as-promised\": \"^7.1.1\",\n \"dotenv\": \"^8.1.0\",\n \"eslint\": \"^6.4.0\",\n \"openzeppelin-solidity\": \"^2.3.0\",\n \"truffle-hdwallet-provider\": \"^1.0.17\",\n \"truffle-hdwallet-provider-privkey\": \"^0.3.0\",\n \"web3\": \"^1.2.1\"\n },\n```\n\nAnd the migrations:\n\n**1_initial_migration.js**\n\n```\nconst Migrations = artifacts.require(\"Migrations\");\n\nmodule.exports = function(deployer) {\n deployer.deploy(Migrations);\n};\n```\n\n**2_deploy_contract.js**\n\n```\nconst Token = artifacts.require(\"TokenInstance\");\nconst DeleToken = artifacts.require(\"DelegateToken\")\nmodule.exports = async function(deployer) {\n \n deployer.deploy(Token);\n deployer.deploy(DeleToken);\n\n};\n```\n\nIt just cannot compile successfully. But I use the default network with ganache is OK!\n\n========================================\n\nCode:\n```js\nropsten: {\n      provider: () => new HDWalletProvider(\n        privateKeys.split(','),\n        `https://ropsten.infura.io/v3/${process.env.INFURA_API_KEY}`\n      ),\n      network_id: 3,       // Ropsten's id, mainnet is 1\n      gas: 5500000,        // Ropsten has a lower block limit than mainnet\n      gasPrice: 2500000000, //2.5 gwei\n      confirmations: 2,    // # of confs to wait between deployments. (default: 0)\n      timeoutBlocks: 200,  // # of blocks before a deployment times out  (minimum/default: 50)\n      skipDryRun: true     // Skip dry run before migrations? (default: false for public nets )\n    },\n```\n\n```js\n\"dependencies\": {\n    \"chai\": \"^4.2.0\",\n    \"chai-as-promised\": \"^7.1.1\",\n    \"dotenv\": \"^8.1.0\",\n    \"eslint\": \"^6.4.0\",\n    \"openzeppelin-solidity\": \"^2.3.0\",\n    \"truffle-hdwallet-provider\": \"^1.0.17\",\n    \"truffle-hdwallet-provider-privkey\": \"^0.3.0\",\n    \"web3\": \"^1.2.1\"\n  },\n```\n\n```js\nconst Migrations = artifacts.require(\"Migrations\");\n\nmodule.exports = function(deployer) {\n  deployer.deploy(Migrations);\n};\n```\n\n```js\nconst Token = artifacts.require(\"TokenInstance\");\nconst DeleToken = artifacts.require(\"DelegateToken\")\nmodule.exports = async function(deployer) {\n  \n  deployer.deploy(Token);\n  deployer.deploy(DeleToken);\n\n};\n```\n\n```text\nat Object.run (C:\\Users\\Bruce\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\packages\\truffle-migrate\\index.js:92:1)\n```\n\n```text\nwebpack\n```\n\n```text\n\"build/\"\n```\n\n```text\nnpm install @truffle/hdwallet-provider\n```\n\n```text\nconst HDWalletProvider = require(\"@truffle/hdwallet-provider\");\n```\n\n```text\ntruffle-hdwallet-provider-privkey\n```\n\n========================================\n\nComments:\n- What version of HDWalletProvider fo you use? And can you show your migration files?\n- I have added some details for the problem. Thank you!\n- Great! And must the Migrations.sol contract be deployed everytime I deploy a contract?\n- You can read more about how the migration works there medium.com/@blockchain101/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:36.115Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":154,"estimatedTokens":1069}}48{"id":"stack-42061479","source":"stackoverflow","questionId":42061479,"title":"Solidity undefined","tags":["ethereum","solidity"],"text":"Title: Solidity undefined\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI have a question when I use solidity to compile a simple contract.\nIt like that:\n\n```\n> web3.eth.getCompilers()\n[\"Solidity\"]\n> source = \"contract test { function multiply(uint a) returns(uint d) { return a * 7; } }\"\n\"contract test { function multiply(uint a) returns(uint d) { return a * 7; } }\"\n> source\n\"contract test { function multiply(uint a) returns(uint d) { return a * 7; } }\"\n> clientContract = eth.compile.solidity(source).test\nundefined\n```\n\nI don't know why the result is \"undefined\", what is wrong? I'm using it on the mac os.\n\n========================================\n\nCode:\n```text\n> web3.eth.getCompilers()\n[\"Solidity\"]\n> source = \"contract test { function multiply(uint a) returns(uint d) { return a * 7; } }\"\n\"contract test { function multiply(uint a) returns(uint d) { return a * 7; } }\"\n> source\n\"contract test { function multiply(uint a) returns(uint d) { return a * 7; } }\"\n> clientContract = eth.compile.solidity(source).test\nundefined\n```\n\n```text\nundefined\n```\n\n```text\nundefined\n```\n\n```text\nclientContract\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- Also have the same question in Ubuntu.\n- Thanks for your answer. I solve this question. That is not a wrong, is the solidity version change.","metadata":{"transformedAt":"2026-08-18T18:33:36.115Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":56,"estimatedTokens":336}}49{"id":"stack-72563398","source":"stackoverflow","questionId":72563398,"title":"Is it possible to top up smart contract's balance at the time of its deployment?","tags":["solidity","ethers.js","hardhat","rsk"],"text":"Title: Is it possible to top up smart contract's balance at the time of its deployment?\nTags: solidity, ethers.js, hardhat, rsk\nSource: Stack Overflow\n\nQuestion:\nSay I have a Solidity smart contract `MultiToken.sol` which I am developing and testing using Hardhat and deploying to the RSK network.\n​\n\n```\n//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n​\nimport \"@openzeppelin/contracts/token/ERC1155/ERC1155.sol\";\n​\ncontract MultiToken is ERC1155 {\n constructor(string memory uri) ERC1155(uri) {}\n}\n```\n\n​\nI am deploying the smart contract in the tests `before` section:\n​\n\n```\nconst { expect } = require('chai');\nconst { ethers } = require('hardhat');\n​\ndescribe('MultiToken', () => {\n let multiToken;\n​\n const uri = 'https://token-cdn-domain/{id}.json';\n​\n before(async () => {\n const factory = await ethers.getContractFactory('MultiToken');\n multiToken = await factory.deploy(uri);\n await multiToken.deployed();\n });\n​\n it('MultiToken URI must be correct', async () => {\n const multiTokenUri = await multiToken.uri(0);\n expect(multiTokenUri).to.equal(uri);\n });\n});\n```\n\n​\nI would like to be able to transfer some RBTC to my smart contract's address during the deployment transaction. Is it possible to top up smart contract's balance at the time of its deployment using Hardhat and Ethers?\n​\nSpecifically, can I do this with a *single transaction*?\n​\nFor reference, this is my `hardhat.config.js`:\n​\n\n```\nrequire('@nomiclabs/hardhat-waffle');\nconst { mnemonic } = require('./.secret.json');\n​\nmodule.exports = {\n solidity: '0.8.4',\n defaultNetwork: 'rskregtest',\n networks: {\n rskregtest: {\n url: 'http://localhost:4444',\n chainId: 33,\n },\n rsktestnet: {\n chainId: 31,\n url: 'https://public-node.testnet.rsk.co/',\n accounts: {\n mnemonic,\n path: \"m/44'/60'/0'/0\",\n },\n },\n },\n};\n```\n\n========================================\n\nCode:\n```text\n//SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.0;\n​\nimport \"@openzeppelin/contracts/token/ERC1155/ERC1155.sol\";\n​\ncontract MultiToken is ERC1155 {\n    constructor(string memory uri) ERC1155(uri) {}\n}\n```\n\n```js\nconst { expect } = require('chai');\nconst { ethers } = require('hardhat');\n​\ndescribe('MultiToken', () => {\n  let multiToken;\n​\n  const uri = 'https://token-cdn-domain/{id}.json';\n​\n  before(async () => {\n    const factory = await ethers.getContractFactory('MultiToken');\n    multiToken = await factory.deploy(uri);\n    await multiToken.deployed();\n  });\n​\n  it('MultiToken URI must be correct', async () => {\n    const multiTokenUri = await multiToken.uri(0);\n    expect(multiTokenUri).to.equal(uri);\n  });\n});\n```\n\n```js\nrequire('@nomiclabs/hardhat-waffle');\nconst { mnemonic } = require('./.secret.json');\n​\nmodule.exports = {\n  solidity: '0.8.4',\n  defaultNetwork: 'rskregtest',\n  networks: {\n    rskregtest: {\n      url: 'http://localhost:4444',\n      chainId: 33,\n    },\n    rsktestnet: {\n      chainId: 31,\n      url: 'https://public-node.testnet.rsk.co/',\n      accounts: {\n        mnemonic,\n        path: \"m/44'/60'/0'/0\",\n      },\n    },\n  },\n};\n```\n\n```text\nMultiToken.sol\n```\n\n```text\nbefore\n```\n\n```text\nhardhat.config.js\n```\n\n```text\ncontract MultiToken is ERC1155 {\n    constructor(string memory uri) ERC1155(uri) payable {}\n}\n```\n\n```text\nmultiToken = await factory.deploy(uri, {\n    value: ethers.utils.parseUnits(\"1\"), // 1 RBTC to wei\n});\n```\n\n```text\nconstructor\n```\n\n```text\npayable\n```\n\n```text\nvalue\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":172,"estimatedTokens":852}}50{"id":"stack-68182729","source":"stackoverflow","questionId":68182729,"title":"Implementing fixtures with @nomiclabs/hardhat-waffle","tags":["typescript","ethereum","solidity","waffle","hardhat"],"text":"Title: Implementing fixtures with @nomiclabs/hardhat-waffle\nTags: typescript, ethereum, solidity, waffle, hardhat\nSource: Stack Overflow\n\nQuestion:\nIn the official waffle documentation you may find the next way to implement fixtures:\n\n```\nimport {expect} from 'chai';\nimport {loadFixture, deployContract} from 'ethereum-waffle';\nimport BasicTokenMock from './build/BasicTokenMock';\n\ndescribe('Fixtures', () => {\n async function fixture([wallet, other], provider) {\n const token = await deployContract(wallet, BasicTokenMock, [\n wallet.address, 1000\n ]);\n return {token, wallet, other};\n }\n\n it('Assigns initial balance', async () => {\n const {token, wallet} = await loadFixture(fixture);\n expect(await token.balanceOf(wallet.address)).to.equal(1000);\n });\n\n it('Transfer adds amount to destination account', async () => {\n const {token, other} = await loadFixture(fixture);\n await token.transfer(other.address, 7);\n expect(await token.balanceOf(other.address)).to.equal(7);\n });\n});\n```\n\nHowever, this won't work while using the plugin on hardhat. No official instructions were given on the plugin docs.\n\nAnswer below.\n\n========================================\n\nTop Answer:\nRemember, hardhat uses mocha as its test runner, so you can use the hooks that mocha describes in its documentation: before(), after(), beforeEach(), and afterEach().\n\nHere's an example of deploying a token contract and using the contract instance to run tests.\n\n\r\n\r\n\n```\nbeforeEach(async function () {\n \n Token = await ethers.getContractFactory(\"Token\");\n [owner, addr1, addr2, ...addrs] = await ethers.getSigners();\n\n hardhatToken = await Token.deploy();\n});\n \ndescribe(\"Deployment\", function () {\n\n it(\"Should set the right owner\", async function () {\n expect(await hardhatToken.owner()).to.equal(owner.address);\n });\n \n});\n```\n\n========================================\n\nCode:\n```text\nimport {expect} from 'chai';\nimport {loadFixture, deployContract} from 'ethereum-waffle';\nimport BasicTokenMock from './build/BasicTokenMock';\n\ndescribe('Fixtures', () => {\n  async function fixture([wallet, other], provider) {\n    const token = await deployContract(wallet, BasicTokenMock, [\n      wallet.address, 1000\n    ]);\n    return {token, wallet, other};\n  }\n\n  it('Assigns initial balance', async () => {\n    const {token, wallet} = await loadFixture(fixture);\n    expect(await token.balanceOf(wallet.address)).to.equal(1000);\n  });\n\n  it('Transfer adds amount to destination account', async () => {\n    const {token, other} = await loadFixture(fixture);\n    await token.transfer(other.address, 7);\n    expect(await token.balanceOf(other.address)).to.equal(7);\n  });\n});\n```\n\n```text\nimport {Wallet, Contract} from \"ethers\";\n    import {MockProvider} from \"ethereum-waffle\";\n    import {ethers, waffle} from \"hardhat\";\n    const {loadFixture, deployContract} = waffle;\n\n\n//Contract ABI\n// For typescript only!\n// In order to be able to import .json files make sure you tsconfig.json has set \"compilerOptions\" > \"resolveJsonModule\": true. My tsconfig.json at the bottom!\n//For obvious reasons change this to the path of your compiled ABI\n\n  import * as TodoListABI from \"../artifacts/contracts/TodoList.sol/TodoList.json\";\n\n    //Fixtures\n  async function fixture(_wallets: Wallet[], _mockProvider: MockProvider) {\n    const signers = await ethers.getSigners();\n    let token: Contract = await deployContract(signers[0], TodoListABI);\n    return {token};\n  }\n```\n\n```text\nit(\"My unit test\", async function () {\n    const {token} = await loadFixture(fixture);\n    // Your code....\n  });\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"target\": \"es2018\",\n    \"module\": \"commonjs\",\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"outDir\": \"dist\",\n    \"resolveJsonModule\": true\n  },\n  \"include\": [\"./scripts\", \"./test\"],\n  \"files\": [\"./hardhat.config.ts\"]\n}\n```\n\n```js\nbeforeEach(async function () {\n  \n  Token = await ethers.getContractFactory(\"Token\");\n  [owner, addr1, addr2, ...addrs] = await ethers.getSigners();\n\n  hardhatToken = await Token.deploy();\n});\n  \ndescribe(\"Deployment\", function () {\n\n  it(\"Should set the right owner\", async function () {\n    expect(await hardhatToken.owner()).to.equal(owner.address);\n  });\n  \n});\n```\n\n========================================\n\nComments:\n- not working, hardhatToken is undefined\n- @MaximeKrier higher up in the code just define hardhatToken - ie `let hardhatToken;`","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":161,"estimatedTokens":1097}}51{"id":"stack-71121396","source":"stackoverflow","questionId":71121396,"title":"How is uniswap assembly create2 function working?","tags":["solidity","smartcontracts","uniswap"],"text":"Title: How is uniswap assembly create2 function working?\nTags: solidity, smartcontracts, uniswap\nSource: Stack Overflow\n\nQuestion:\nI was going through uniswap code trying to understand the code and most of it is pretty clear but I do have a few questions.\n\nin this function:\n\n```\nfunction createPair(address tokenA, address tokenB) external returns (address pair) {\n require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');\n (address token0, address token1) = tokenA There is the assembly line. According to solidity docs this deploys a new contract but I don't understand how it works where it gets the code from and so on.\n\nSo is it possible to \"translate\" this into solidity somehow? Thanks a lot!\n\n========================================\n\nCode:\n```text\nfunction createPair(address tokenA, address tokenB) external returns (address pair) {\n    require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');\n    (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n    require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');\n    require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient\n    bytes memory bytecode = type(UniswapV2Pair).creationCode;\n    bytes32 salt = keccak256(abi.encodePacked(token0, token1));\n    assembly {\n        pair := create2(0, add(bytecode, 32), mload(bytecode), salt)\n    }\n    IUniswapV2Pair(pair).initialize(token0, token1);\n    getPair[token0][token1] = pair;\n    getPair[token1][token0] = pair; // populate mapping in the reverse direction\n    allPairs.push(pair);\n    emit PairCreated(token0, token1, pair, allPairs.length);\n```\n\n```text\npragma solidity ^0.8;\n\ncontract UniswapV2Pair {\n}\n\ncontract MyContract {\n    function createPair() external {\n        bytes32 salt = 0x1234567890123456789012345678901234567890123456789012345678901234;\n        address pair = address(\n            new UniswapV2Pair{salt: salt}()\n        );\n    }\n}\n```\n\n```text\ncreate2\n```\n\n```text\ncreate2\n```\n\n```text\nsalt\n```\n\n```text\ncreate2\n```\n\n```text\ncreate\n```\n\n```text\n0x123\n```\n\n```text\n0x456\n```\n\n```text\nUniswapV2Pair\n```\n\n```text\n0xabc\n```\n\n```text\n0x123\n```\n\n```text\n0x789\n```\n\n```text\nUniswapV2Pair\n```\n\n```text\n0xdef\n```\n\n========================================\n\nComments:\n- Thanks a lot! I was confused why they didn't just use the new keyword but I didn't realise that it was written in solidity 0.5.0.","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":109,"estimatedTokens":604}}52{"id":"stack-48245051","source":"stackoverflow","questionId":48245051,"title":"How to get transaction cost in smart contract - Solidity, Ethereum","tags":["ethereum","solidity"],"text":"Title: How to get transaction cost in smart contract - Solidity, Ethereum\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nHow would I get the transaction cost inside of my contract? Would it just be: `tx.gasprice` ? And will this always be a value in gwei or will it be wei ?\n\n========================================\n\nCode:\n```text\ntx.gasprice\n```\n\n```text\nthrow\n```\n\n```text\ntx.gasprice\n```\n\n```text\nmsg.gas\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":25,"estimatedTokens":106}}53{"id":"stack-69900547","source":"stackoverflow","questionId":69900547,"title":"Weird error using Smart Contracts with @usedapp and @ethersproject/contracts","tags":["typescript","blockchain","ethereum","solidity","brownie"],"text":"Title: Weird error using Smart Contracts with @usedapp and @ethersproject/contracts\nTags: typescript, blockchain, ethereum, solidity, brownie\nSource: Stack Overflow\n\nQuestion:\nHello there I'm trying to use a contract made on solidity and deployed with brownie on my front end using React and typescript. also using the framework usedapp, as the documentation here says in order to interact with a contract function I should create a new contract, providing the address and the ABI. Here is my code:\n\n```\nimport {useContractFunction, useEthers} from '@usedapp/core'\nimport TokenFarm from \"../chain-info/contracts/TokenFarm.json\"\nimport ERC20 from \"../chain-info/contracts/MockERC20.json\"\nimport networkMapping from \"../chain-info/deployments/map.json\"\nimport {constants, utils} from \"ethers\"\nimport {Contract} from '@ethersproject/contracts'\n\nexport const useStakeTokens = (tokenAddress: string) => {\n // chainId \n const {chainId} = useEthers()\n // abi\n const {abi} = TokenFarm\n // address\n // const dappTokenAddress = chainId ? networkMapping[String(chainId)][\"DappToken\"][0] : constants.AddressZero\n const tokenFarmAddress = chainId ? networkMapping[String(chainId)][\"TokenFarm\"][0] : constants.AddressZero\n // approve\n const tokenFarmInterface = new utils.Interface(abi)\n const tokenFarmContract = new Contract(tokenFarmAddress, tokenFarmInterface)\n\n const erc20ABI = ERC20.abi\n const erc20Interface = new utils.Interface(erc20ABI)\n const erc20Contract = new Contract(tokenAddress, erc20Interface)\n // approve\n const { send: approveErc20Send, state: approveAndStakeErc20State } =\n useContractFunction(erc20Contract, \"approve\", {\n transactionName: \"Approve ERC20 transfer\",\n })\n\n}\n```\n\nThe error occurs on `useContractFunction`with `erc20Contract`:\n\nVscode error\n\nThis is the complete error message\n\n```\nArgument of type 'import(\"/home/cromewar/Solidity-Projects/full_defi_app/dev/front_end/node_modules/@ethersproject/contracts/lib/index\").Contract' is not assignable to parameter of type 'import(\"/home/cromewar/Solidity-Projects/full_defi_app/dev/front_end/node_modules/@usedapp/core/node_modules/@ethersproject/contracts/lib/index\").Contract'.\n Types of property '_runningEvents' are incompatible.\n Type '{ [eventTag: string]: RunningEvent; }' is not assignable to type '{ [eventTag: string]: RunningEvent; }'. Two different types with this name exist, but they are unrelated.\n 'string' index signatures are incompatible.\n Type 'RunningEvent' is not assignable to type 'RunningEvent'. Two different types with this name exist, but they are unrelated.\n Types have separate declarations of a private property '_listeners'. TS2345\n\n 23 | // approve\n 24 | const { send: approveErc20Send, state: approveAndStakeErc20State } =\n > 25 | useContractFunction(erc20Contract, \"approve\", {\n | ^\n 26 | transactionName: \"Approve ERC20 transfer\",\n 27 | })\n 28 |\n```\n\n```\nArgument of type 'import(\"/home/cromewar/Solidity-Projects/full_defi_app/dev/front_end/node_modules/@ethersproject/contracts/lib/index\").Contract' is not assignable to parameter of type 'import(\"/home/cromewar/Solidity-Projects/full_defi_app/dev/front_end/node_modules/@usedapp/core/node_modules/@ethersproject/contracts/lib/index\").Contract'.\n Types of property '_runningEvents' are incompatible.\n Type '{ [eventTag: string]: RunningEvent; }' is not assignable to type '{ [eventTag: string]: RunningEvent; }'. Two different types with this name exist, but they are unrelated.\n 'string' index signatures are incompatible.\n Type 'RunningEvent' is not assignable to type 'RunningEvent'. Two different types with this name exist, but they are unrelated.\n Types have separate declarations of a private property '_listeners'. TS2345\n```\n\nIt says the types are not compatible but they are actually the exact same, does anyone has a clue about what is happening?\n\n========================================\n\nCode:\n```js\nimport {useContractFunction, useEthers} from '@usedapp/core'\nimport TokenFarm from \"../chain-info/contracts/TokenFarm.json\"\nimport ERC20 from \"../chain-info/contracts/MockERC20.json\"\nimport networkMapping from \"../chain-info/deployments/map.json\"\nimport {constants, utils} from \"ethers\"\nimport {Contract} from '@ethersproject/contracts'\n\nexport const useStakeTokens = (tokenAddress: string) => {\n    // chainId \n    const {chainId} = useEthers()\n    // abi\n    const {abi} = TokenFarm\n    // address\n    // const dappTokenAddress = chainId ? networkMapping[String(chainId)][\"DappToken\"][0] : constants.AddressZero\n    const tokenFarmAddress = chainId ? networkMapping[String(chainId)][\"TokenFarm\"][0] : constants.AddressZero\n    // approve\n    const tokenFarmInterface = new utils.Interface(abi)\n    const tokenFarmContract = new Contract(tokenFarmAddress, tokenFarmInterface)\n\n    const erc20ABI = ERC20.abi\n    const erc20Interface = new utils.Interface(erc20ABI)\n    const erc20Contract = new Contract(tokenAddress, erc20Interface)\n    // approve\n    const { send: approveErc20Send, state: approveAndStakeErc20State } =\n        useContractFunction(erc20Contract, \"approve\", {\n            transactionName: \"Approve ERC20 transfer\",\n        })\n\n}\n```\n\n```text\nArgument of type 'import(\"/home/cromewar/Solidity-Projects/full_defi_app/dev/front_end/node_modules/@ethersproject/contracts/lib/index\").Contract' is not assignable to parameter of type 'import(\"/home/cromewar/Solidity-Projects/full_defi_app/dev/front_end/node_modules/@usedapp/core/node_modules/@ethersproject/contracts/lib/index\").Contract'.\n  Types of property '_runningEvents' are incompatible.\n    Type '{ [eventTag: string]: RunningEvent; }' is not assignable to type '{ [eventTag: string]: RunningEvent; }'. Two different types with this name exist, but they are unrelated.\n      'string' index signatures are incompatible.\n        Type 'RunningEvent' is not assignable to type 'RunningEvent'. Two different types with this name exist, but they are unrelated.\n          Types have separate declarations of a private property '_listeners'.  TS2345\n\n    23 |     // approve\n    24 |     const { send: approveErc20Send, state: approveAndStakeErc20State } =\n  > 25 |         useContractFunction(erc20Contract, \"approve\", {\n       |                             ^\n    26 |             transactionName: \"Approve ERC20 transfer\",\n    27 |         })\n    28 |\n```\n\n```text\nArgument of type 'import(\"/home/cromewar/Solidity-Projects/full_defi_app/dev/front_end/node_modules/@ethersproject/contracts/lib/index\").Contract' is not assignable to parameter of type 'import(\"/home/cromewar/Solidity-Projects/full_defi_app/dev/front_end/node_modules/@usedapp/core/node_modules/@ethersproject/contracts/lib/index\").Contract'.\n  Types of property '_runningEvents' are incompatible.\n    Type '{ [eventTag: string]: RunningEvent; }' is not assignable to type '{ [eventTag: string]: RunningEvent; }'. Two different types with this name exist, but they are unrelated.\n      'string' index signatures are incompatible.\n        Type 'RunningEvent' is not assignable to type 'RunningEvent'. Two different types with this name exist, but they are unrelated.\n          Types have separate declarations of a private property '_listeners'.  TS2345\n```\n\n```text\nuseContractFunction\n```\n\n```text\nerc20Contract\n```\n\n```text\nimport {Contract} from '@ethersproject/contracts'\n```\n\n```text\nimport {Contract} from '@usedapp/core/node_modules/@ethersproject/contracts'\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":149,"estimatedTokens":1844}}54{"id":"stack-71367683","source":"stackoverflow","questionId":71367683,"title":"How to get Transaction Receipt Event Logs?","tags":["javascript","ethereum","blockchain","solidity","smartcontracts"],"text":"Title: How to get Transaction Receipt Event Logs?\nTags: javascript, ethereum, blockchain, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI need to get the events emitted by my smart contract and consume them in the front end via web3.\n\nI made some event on my contract that returns event winner and ticket number:\n\n```\nevent Winner(uint256 ticketNumber, address winner);\n```\n\nSo I emit this event, and I see it on transaction logs.\n\nFrom Etherscan:\n\nhttps://i.sstatic.net/F9Wpn.png\n\nOK! What I need is the data: ticketNumber: 1, winner: 0x........\nHow did I get this from web3?\n\nIm trying to use:\n\n```\nawait web3.eth.getTransactionReceipt(txnHash, function (error, result) {\n console.log(result);\n });\n```\n\nBut when I check console log, I cannot see this information, I suspect that result.logs.data is the right info, but I don't know for sure, and I don't know how to translate:\n\n\"0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000005964b608ea267bfe9ef77707fce8105a2d145e7a\"\n\nAnybody have an idea?\n\n========================================\n\nTop Answer:\nIf you don't have the contract ABI with you, you can these steps to retrieve the events,\n\nStep 1 - use `await web3.eth.getTransactionReceipt(txHash)` as shown here.\n\nStep 2 - You would receive an object with a field `logs`. This would be an array of objects with the length equal to the number of events emitted in that transaction. \n\nStep 3 - In each of these objects there would be two fields that would be important to us. `data` and `topic`. The `data` field will contain all the unindexed parameters of the given event. To decode that you can use `web3.eth.abi.decodeLog(inputs, hexString, topics)` as shown here.\n\nStep 4 - You can get the name of the event from the first element of the field `topic`. The first element here corresponds to the keccak256 of the event signature. `web3.utils.sha3(string)` can be used to to hash your event signature to check if the first entry of `topics` array match. More info here.\n\nStep 5- If your event has indexed parameters, they can be found from the rest of the entries of the the `topics` array. To convert then to human readable form, the same steps as step 3.\n\n========================================\n\nCode:\n```text\nevent Winner(uint256 ticketNumber, address winner);\n```\n\n```text\nawait web3.eth.getTransactionReceipt(txnHash, function (error, result) {\n          console.log(result);\n        });\n```\n\n```text\nmyContract.getPastEvents('MyEvent', {\n    filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23\n    fromBlock: 0,\n    toBlock: 'latest'\n}, function(error, events){ console.log(events); })\n.then(function(events){\n    console.log(events) // same results as the optional callback above\n});\n```\n\n```text\ncontract.events.Winner()\n.on('data', (event) => {\n    console.log(event);\n})\n.on('error', console.error);\n```\n\n```text\ngetPastEvents\n```\n\n```text\nawait web3.eth.getTransactionReceipt(txHash)\n```\n\n```text\nlogs\n```\n\n```text\ndata\n```\n\n```text\ntopic\n```\n\n```text\ndata\n```\n\n```text\nweb3.eth.abi.decodeLog(inputs, hexString, topics)\n```\n\n```text\ntopic\n```\n\n```text\nweb3.utils.sha3(string)\n```\n\n```text\ntopics\n```\n\n```text\ntopics\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":126,"estimatedTokens":814}}55{"id":"stack-48970458","source":"stackoverflow","questionId":48970458,"title":"In Solidity, what is the difference between using if() and require()?","tags":["conditional-statements","blockchain","solidity"],"text":"Title: In Solidity, what is the difference between using if() and require()?\nTags: conditional-statements, blockchain, solidity\nSource: Stack Overflow\n\nQuestion:\nI can run code inside a conditional if statement. I can also require a condition before running some code. Are they interchangeable or are there reasons I would choose to rely on one and not the other?\n\n========================================\n\nCode:\n```text\nif\n```\n\n```text\nrequire\n```\n\n```text\nrequire\n```\n\n```text\nrequire\n```\n\n```text\nassert\n```\n\n```text\nrevert\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":33,"estimatedTokens":133}}56{"id":"stack-70664908","source":"stackoverflow","questionId":70664908,"title":"web3 - VM Exception while processing transaction: out of gas","tags":["javascript","mocha.js","solidity","web3js","ganache"],"text":"Title: web3 - VM Exception while processing transaction: out of gas\nTags: javascript, mocha.js, solidity, web3js, ganache\nSource: Stack Overflow\n\nQuestion:\nI have this contract:\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.7;\n\ncontract CampaignFactory {\n address[] public deployedCampaigns;\n\n function createCampaign(uint minimum) public {\n address newCampaign = address(new Campaign(minimum, msg.sender));\n deployedCampaigns.push(newCampaign);\n }\n\n function getDeployedCampaigns() public view returns(address[] memory) {\n return deployedCampaigns;\n }\n}\n\ncontract Campaign {\n struct Request {\n string description;\n uint value;\n address recipient;\n bool complete;\n uint approvalCount;\n mapping(address => bool) approvals;\n }\n\n Request[] public requests;\n address public manager;\n uint public minimumContribution;\n mapping(address => bool) public approvers;\n uint public approversCount;\n\n modifier restricted() {\n require(msg.sender == manager);\n _;\n }\n\n constructor(uint minimum, address creator) {\n manager = creator;\n minimumContribution = minimum;\n }\n\n function contribute() public payable {\n require(msg.value > minimumContribution);\n\n approvers[msg.sender] = true;\n approversCount++;\n }\n\n function createRequest(string calldata description, uint value, address recipient) public restricted {\n Request storage newRequest = requests.push();\n newRequest.description = description;\n newRequest.value = value;\n newRequest.recipient = recipient;\n newRequest.complete = false;\n newRequest.approvalCount = 0;\n }\n\n function approveRequest(uint index) public {\n Request storage request = requests[index];\n\n require(approvers[msg.sender]);\n require(!request.approvals[msg.sender]);\n\n request.approvals[msg.sender] = true;\n request.approvalCount++;\n }\n\n function finalizeRequest(uint index) public restricted {\n Request storage request = requests[index];\n\n require(request.approvalCount > (approversCount / 2));\n require(!request.complete);\n\n payable(request.recipient).transfer(request.value); \n request.complete = true;\n }\n}\n```\n\nAnd test:\n\n```\nconst assert = require('assert');\nconst ganache = require('ganache-cli');\nconst Web3 = require('web3');\nconst web3 = new Web3(ganache.provider());\n\nconst compiledFactory = require('../ethereum/build/CampaignFactory.json');\nconst compiledCampaign = require('../ethereum/build/Campaign.json');\n\nlet accounts;\nlet factory;\nlet campaignAddress;\nlet campaign;\n\nbeforeEach(async() => {\n accounts = await web3.eth.getAccounts();\n\n web3.eth.getBalance(accounts[0]).then(result => console.log(result));\n\n factory = await new web3.eth.Contract(compiledFactory.abi)\n .deploy({ data: compiledFactory.evm.bytecode.object })\n .send({ from: accounts[0], gas: '1000000' });\n\n await factory.methods.createCampaign('100').send({\n from: accounts[0],\n gas: '1000000'\n });\n\n [campaignAddress] = await factory.methods.getDeployedCampaigns().call();\n campaign = await new web3.eth.Contract(\n JSON.parse(compiledCampaign.interface),\n campaignAddress\n );\n});\n\ndescribe('Campaigns', () => {\n it('deploys a factory and a campaign', () => {\n assert.ok(factory.options.address);\n assert.ok(campaign.options.address);\n });\n});\n```\n\nWhen I run the test, I get VM Exception while processing transaction: out of gas, but it logs that accounts[0] balance is 100000000000000000000. The problem occurs where the factory is assigned a new contract instance saying there isn't enough gas, while there clearly is.\n\n========================================\n\nTop Answer:\nPlease update the `gasLimit`.\n\n`test/Campaign.test.js`\n\n```\nconst assert = require(\"assert\");\nconst ganache = require(\"ganache-cli\");\nconst Web3 = require(\"web3\");\n\nconst options = {\n gasLimit: 10000000,\n};\nconst web3 = new Web3(ganache.provider(options));\n\nconst compiledFactory = require(\"../build/CampaignFactory.json\");\nconst compiledCampaign = require(\"../build/Campaign.json\");\n\nlet accounts;\nlet factory;\nlet campaignAddress;\nlet campaign;\n\nbeforeEach(async () => {\n accounts = await web3.eth.getAccounts();\n\n factory = await new web3.eth.Contract(compiledFactory.abi)\n .deploy({ data: compiledFactory.evm.bytecode.object })\n .send({ from: accounts[0], gas: \"10000000\" });\n\n await factory.methods.createCampaign(\"100\").send({\n from: accounts[0],\n gas: \"10000000\",\n });\n\n [campaignAddress] = await factory.methods.getDeployedCampaigns().call();\n\n campaign = await new web3.eth.Contract(compiledCampaign.abi, campaignAddress);\n});\n\ndescribe(\"Campaigns\", () => {\n it(\"deploys a factory and a campaign\", () => {\n assert.ok(factory.options.address);\n assert.ok(campaign.options.address);\n });\n});\n```\n\nIt works for me!\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.7;\n\ncontract CampaignFactory {\n    address[] public deployedCampaigns;\n\n    function createCampaign(uint minimum) public {\n        address newCampaign = address(new Campaign(minimum, msg.sender));\n        deployedCampaigns.push(newCampaign);\n    }\n\n    function getDeployedCampaigns() public view returns(address[] memory) {\n        return deployedCampaigns;\n    }\n}\n\ncontract Campaign {\n    struct Request {\n        string description;\n        uint value;\n        address recipient;\n        bool complete;\n        uint approvalCount;\n        mapping(address => bool) approvals;\n    }\n\n    Request[] public requests;\n    address public manager;\n    uint public minimumContribution;\n    mapping(address => bool) public approvers;\n    uint public approversCount;\n\n    modifier restricted() {\n        require(msg.sender == manager);\n        _;\n    }\n\n    constructor(uint minimum, address creator) {\n        manager = creator;\n        minimumContribution = minimum;\n    }\n\n    function contribute() public payable {\n        require(msg.value > minimumContribution);\n\n        approvers[msg.sender] = true;\n        approversCount++;\n    }\n\n    function createRequest(string calldata description, uint value, address recipient) public restricted {\n        Request storage newRequest = requests.push();\n        newRequest.description = description;\n        newRequest.value = value;\n        newRequest.recipient = recipient;\n        newRequest.complete = false;\n        newRequest.approvalCount = 0;\n    }\n\n    function approveRequest(uint index) public {\n        Request storage request = requests[index];\n\n        require(approvers[msg.sender]);\n        require(!request.approvals[msg.sender]);\n\n        request.approvals[msg.sender] = true;\n        request.approvalCount++;\n    }\n\n    function finalizeRequest(uint index) public restricted {\n        Request storage request = requests[index];\n\n        require(request.approvalCount > (approversCount / 2));\n        require(!request.complete);\n\n        payable(request.recipient).transfer(request.value); \n        request.complete = true;\n    }\n}\n```\n\n```text\nconst assert = require('assert');\nconst ganache = require('ganache-cli');\nconst Web3 = require('web3');\nconst web3 = new Web3(ganache.provider());\n\nconst compiledFactory = require('../ethereum/build/CampaignFactory.json');\nconst compiledCampaign = require('../ethereum/build/Campaign.json');\n\nlet accounts;\nlet factory;\nlet campaignAddress;\nlet campaign;\n\nbeforeEach(async() => {\n    accounts = await web3.eth.getAccounts();\n\n    web3.eth.getBalance(accounts[0]).then(result => console.log(result));\n\n    factory = await new web3.eth.Contract(compiledFactory.abi)\n        .deploy({ data: compiledFactory.evm.bytecode.object })\n        .send({ from: accounts[0], gas: '1000000' });\n\n    await factory.methods.createCampaign('100').send({\n        from: accounts[0],\n        gas: '1000000'\n    });\n\n    [campaignAddress] = await factory.methods.getDeployedCampaigns().call();\n    campaign = await new web3.eth.Contract(\n        JSON.parse(compiledCampaign.interface),\n        campaignAddress\n    );\n});\n\ndescribe('Campaigns', () => {\n    it('deploys a factory and a campaign', () => {\n        assert.ok(factory.options.address);\n        assert.ok(campaign.options.address);\n    });\n});\n```\n\n```text\n.send({ from: accounts[0], gas: '1000000' })\n```\n\n```text\n1000000\n```\n\n```text\nfrom\n```\n\n```text\nconst assert = require(\"assert\");\nconst ganache = require(\"ganache-cli\");\nconst Web3 = require(\"web3\");\n\nconst options = {\n  gasLimit: 10000000,\n};\nconst web3 = new Web3(ganache.provider(options));\n\nconst compiledFactory = require(\"../build/CampaignFactory.json\");\nconst compiledCampaign = require(\"../build/Campaign.json\");\n\nlet accounts;\nlet factory;\nlet campaignAddress;\nlet campaign;\n\nbeforeEach(async () => {\n  accounts = await web3.eth.getAccounts();\n\n  factory = await new web3.eth.Contract(compiledFactory.abi)\n    .deploy({ data: compiledFactory.evm.bytecode.object })\n    .send({ from: accounts[0], gas: \"10000000\" });\n\n  await factory.methods.createCampaign(\"100\").send({\n    from: accounts[0],\n    gas: \"10000000\",\n  });\n\n  [campaignAddress] = await factory.methods.getDeployedCampaigns().call();\n\n  campaign = await new web3.eth.Contract(compiledCampaign.abi, campaignAddress);\n});\n\ndescribe(\"Campaigns\", () => {\n  it(\"deploys a factory and a campaign\", () => {\n    assert.ok(factory.options.address);\n    assert.ok(campaign.options.address);\n  });\n});\n```\n\n```text\ngasLimit\n```\n\n```text\ntest/Campaign.test.js\n```\n\n========================================\n\nComments:\n- Double check how you provide gas and/or gas fees. It sounds like the problem lies there, not in your contract implementation.\n- @MarkoPopovic what do you mean how do I provide gas? I am using web3 account that you get with web3 library. So far I haven't had any issues with writing my tests this way.\n- Does this answer your question? VM Exception while processing transaction: out of gas","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":383,"estimatedTokens":2421}}57{"id":"stack-65234522","source":"stackoverflow","questionId":65234522,"title":"Warning: SPDX license identifier not provided in source file","tags":["blockchain","solidity","remix","spdx"],"text":"Title: Warning: SPDX license identifier not provided in source file\nTags: blockchain, solidity, remix, spdx\nSource: Stack Overflow\n\nQuestion:\nI created a new solidity contract. The contract is up and running but giving me this warning.\n\n```\nWarning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing \"SPDX-License-Identifier: \" to each source file. Use \"SPDX-License-Identifier: UNLICENSED\" for non-open-source code. Please see https://spdx.org for more information.\n```\n\nThere are no errors while compilation.\n\nThe Compiler version I am using in https://remix.ethereum.org/ is **v0.7.5+commit.eb77ed08**\nLanguage: Solidity\nEVM VERSION: compiler default\n\nWhenever I press compile it gives me the warning but there is no problem while deploying.\n\nMy code snippet:\n\n```\npragma solidity ^0.7.5;\ncontract TestContract {\n// Some logic\n}\n```\n\n========================================\n\nCode:\n```text\nWarning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing \"SPDX-License-Identifier: <SPDX-License>\" to each source file. Use \"SPDX-License-Identifier: UNLICENSED\" for non-open-source code. Please see https://spdx.org for more information.\n```\n\n```text\npragma solidity ^0.7.5;\ncontract TestContract {\n// Some logic\n}\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.7.5;\ncontract TestContract {\n// Some logic\n}\n```\n\n```text\n// SPDX-License-Identifier: GPL-3.0-or-later\n```\n\n========================================\n\nComments:\n- docs.soliditylang.org/en/v0.6.8/&hellip;\n- Can you use a commercial (i.e. non open source) license?","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":59,"estimatedTokens":414}}58{"id":"stack-58258808","source":"stackoverflow","questionId":58258808,"title":"Data location must be \"memory\" for return parameter in function, but none was given","tags":["blockchain","ethereum","solidity"],"text":"Title: Data location must be \"memory\" for return parameter in function, but none was given\nTags: blockchain, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI tried solidity example like as above in remix, solidity version > 0.5.0\nBut I am getting this error now.\nWhat is the way to solve this error?\n\n```\ncontract MyContract {\n string value;\n\n function get() public view returns (string) {\n return value;\n }\n\n function set(string _value) public {\n value = _value;\n }\n\n constructor() public {\n value = \"myValue\";\n }\n}\n```\n\n========================================\n\nTop Answer:\nValues of reference type can be modified through multiple different\nnames. Contrast this with value types where you get an independent\ncopy whenever a variable of value type is used. Because of that,\nreference types have to be handled more carefully than value types.\nCurrently, reference types comprise structs, arrays and mappings. If\nyou use a reference type, you always have to explicitly provide the\ndata area where the type is stored: memory (whose lifetime is limited\nto an external function call), storage (the location where the state\nvariables are stored, where the lifetime is limited to the lifetime of\na contract) or calldata (special data location that contains the\nfunction arguments).\n\n`Warning`\n\nPrior to version 0.5.0 the data location could be omitted, and would default to different locations depending on the kind of variable, function type, etc., but all complex types must now give an explicit data location.\n\nhttps://docs.soliditylang.org/en/latest/types.html#reference-types\n\nso you have to put `memory` or `calldata` after String as follows:\n\n```\ncontract MyContract {\n string value;\n\n function get() public view returns (string memory) {\n return value;\n }\n\n function set(string memory _value) public {\n value = _value;\n }\n\n constructor() {\n value = \"myValue\";\n }\n}\n```\n\nanother thing to notice that you dont have to put public in the constructor any more:\n\nWarning: Prior to version 0.7.0, you had to specify the visibility of\nconstructors as either internal or public.\n\nhttps://docs.soliditylang.org/en/latest/contracts.html?highlight=constructor#constructors\n\n========================================\n\nCode:\n```text\ncontract MyContract {\n    string value;\n\n    function get() public view returns (string) {\n        return value;\n    }\n\n    function set(string _value) public {\n        value = _value;\n    }\n\n    constructor() public {\n        value = \"myValue\";\n    }\n}\n```\n\n```text\ncontract MyContract {\n    string value;\n\n    function get() public view returns (string memory) {\n        return value;\n    }\n\n    function set(string memory _value) public {\n        value = _value;\n    }\n\n    constructor() public {\n        value = \"myValue\";\n    }\n}\n```\n\n```text\ncontract MyContract {\n    string value;\n\n    function get() public view returns (string memory) {\n        return value;\n    }\n\n    function set(string memory _value) public {\n        value = _value;\n    }\n\n    constructor() public {\n        value = \"myValue\";\n    }\n}\n```\n\n```text\ncontract MyContract {\n    string value;\n\n    function get() public view returns (string calldata) {\n        return value;\n    }\n\n    function set(string calldata _value) public {\n        value = _value;\n    }\n\n    constructor() public {\n        value = \"myValue\";\n    }\n}\n```\n\n```text\ncontract MyContract {\n    string value;\n\n    function get() public view returns (string memory) {\n        return value;\n    }\n\n    function set(string memory _value) public {\n        value = _value;\n    }\n\n    constructor() {\n        value = \"myValue\";\n    }\n}\n```\n\n```text\nWarning\n```\n\n```text\nmemory\n```\n\n```text\ncalldata\n```\n\n```text\nfunction getAllPlayers() public view returns(address[] memory){\n        return players;\n    }\n```\n\n```text\nmemory\n```\n\n```text\naddress type\n```\n\n```text\ncontract Greeter{\n\n    string greeting;\n\n    function greeter(string memory _greeting) public{\n        greeting = _greeting;\n\n    }\n\n    function greet() public returns(string memory)\n    {\n        return greeting;\n    }\n\n}\n```\n\n========================================\n\nComments:\n- Can you help to explain difference between `memory` and `calldata` and there use cases?\n- The simplest explanation is: `calldata` is a non-modifiable, non-persistent area where function arguments are stored, and behaves mostly like memory, it must be used when declaring an external function's dynamic parameters. `memory` is mutable, non-persistent and used for both function declaration parameters, its ifetime is limited to a function call and it should be used when declaring variables (both function parameters as well as inside the logic of a function) that you want stored in memory (temporary)\n- This is a code only answer, consider adding an explanation. Also I would reuse the OP's original code instead of providing a random example.","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":218,"estimatedTokens":1215}}59{"id":"stack-33839154","source":"stackoverflow","questionId":33839154,"title":"In Ethereum Solidity, what is the purpose of the \"memory\" keyword?","tags":["memory","blockchain","ethereum","solidity","smartcontracts"],"text":"Title: In Ethereum Solidity, what is the purpose of the \"memory\" keyword?\nTags: memory, blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nWhen looking at sample contracts, sometimes arrays are declared in methods with \"memory\" and sometimes they aren't. What's the difference?\n\n========================================\n\nTop Answer:\nStorage holds data between function calls. It is like a computer hard drive. State variables are storage data. These state\nvariables reside in the smart contract data section on the blockchain. Writing variables into storage is very expensive because each node that runs the transaction has to do the same operation, it makes the transaction more expensive and causes the blockchain bigger.\n\nMemory is a temporary place to store data, like RAM. Function args and local variables in functions are memory data. (if the function is external, args will be stored in the stack (calldata)) Ethereum virtual machine has limited space for memory so values stored here are erased between function calls.\n\nThe cost of global storage is 20,000 wei for writing the first time,\n5,000 wei for updating the same storage location, and 200 wei for\nreading the storage. It is to be noted that these costs are per 32\nbytes of storage. For example, reading 64 bytes will cost 2 * 200 wei,\nthat is, 400 wei.\n\nThe cost of memory storage for both reading and writing 32 bytes of\ndata is 2 wei. The cost of memory is way cheaper than global storage.\n\nAs you know accessing data inside a database is more expensive than accessing data inside the memory (session,cache).\n\nLet's say we want to modify the top-level state variable inside a\nfunction.\n\n```\nthis inside the function int[] public numbers\n\nfunction Numbers()public{\n numbers.push(5)\n numbers.push(10)\n int[] storage myArray=numbers\n\n // numbers[0] will also be changed to 1\n myArray[0]=1 \n\n //Imagine you have an NFT contract and store the user's purchased nfts in a state variable on top-level\n // now inside a function maybe you need to delete one of the NFT's, since user sold it\n // so you will be modifying that list, inside a function using \"storage\"\n}\n```\n\n`int[] storage myArray=numbers` in this case myArray will point to the same address as \"numbers\" (it is similar to how referencing objects behave in javascript). In the function I added 5, then 10 to \"numbers\" which is placed into Storage. But if you deploy the code on remix and get `numbers[0]`, you will get 1 because of `myArray[0]=1`\n\n### If you define `myArray` as memory it will be a different story.\n\n```\n// state variables are placed in Storage\nint[] public numbers\n\nfunction Numbers() public{\n numbers.push(5)\n numbers.push(10)\n // we are telling Solidity make numbers local variable using \"memory\"\n // That reduces gas cost of your contract\n int[] memory myArray=numbers\n myArray[0]=1 \n\n // Now, this time maybe you want to user's NFT's where price is less than 100 $\n // so you create an array stored in \"memory\" INSIDE the function\n // You loop through user's Nft's and push the ones that priceIn this case, \"numbers\" array is copied into Memory, and myArray now references a memory address which is different from the \"numbers\" address. If you deploy this code and reach `numbers[0]` you will get 5.\n\n- by copying the storage variables onto the memory, we are preventing our state variables from unwanted change. Everytime client calls the public function would modify the storage variables and imagine if thousands of clients call the same function how were you keep track of state variables\n\nI showed the difference on a simple function so it can be easily tested on Remix\n\n========================================\n\nCode:\n```text\nuint8 storage var;\n```\n\n```text\nstruct User {\n string name;\n}\nUser[] users;\n\nfunction f() external {\n User memory user = users[0]; // create a pointer\n user.name = \"example name\" // can't change the value of struct User\n}\n```\n\n```text\nmemory\n```\n\n```text\nmemory\n```\n\n```text\nf()\n```\n\n```text\nmemory\n```\n\n```text\nUser\n```\n\n```text\nstorage\n```\n\n```text\nUser\n```\n\n```js\nthis inside the function int[] public numbers\n\nfunction Numbers()public{\n    numbers.push(5)\n    numbers.push(10)\n    int[] storage myArray=numbers\n\n   // numbers[0] will also be changed to 1\n   myArray[0]=1 \n\n  //Imagine you have an NFT contract and store the user's purchased nfts in a state variable on top-level\n  // now inside a function maybe you need to delete one of the NFT's, since user sold it\n  // so you will be modifying that list, inside a function using \"storage\"\n}\n```\n\n```js\n// state variables are placed in Storage\nint[] public numbers\n\nfunction Numbers() public{\n    numbers.push(5)\n    numbers.push(10)\n    // we are telling Solidity make numbers local variable using \"memory\"\n    // That reduces gas cost of your contract\n    int[] memory myArray=numbers\n    myArray[0]=1 \n\n   // Now, this time maybe you want to user's NFT's where price is less than 100 $\n   // so you create an array stored in \"memory\" INSIDE the function\n   // You loop through user's Nft's and push the ones that price<100\n   // then return the memory variable\n   // so, after you return the memory variable, it will be deleted from the memory\n\n}\n```\n\n```text\nint[] storage myArray=numbers\n```\n\n```text\nnumbers[0]\n```\n\n```text\nmyArray[0]=1\n```\n\n```text\nmyArray\n```\n\n```text\nnumbers[0]\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\ncontract StorageMemory1{\n    uint storageVariable;\n\n    constructor() {\n    }\n\n    function assignToValue(uint memoryVariable) public {\n        storageVariable = memoryVariable;\n    }\n}\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\ncontract StorageMemory2 {\n    uint[] public values;\n\n    function doSomething() public\n    {\n        values.push(5);\n        values.push(10);\n\n        uint[] newArray = values; // The error will show here\n    }\n}\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport 'hardhat/console.sol'; // to use console.log\n\ncontract StorageMemory2 {\n    uint[] public values;\n\n    function doSomething() public\n    {\n        values.push(5);\n        values.push(10);\n\n        console.log(values[0]); // it will log: 5\n\n        uint[] storage newArray = values; // 'newArray' references/points to 'values'\n\n        newArray[0] = 8888;\n\n        console.log(values[0]); // it will log: 8888\n        console.log(newArray[0]); // it will also log: 8888\n    }\n}\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport 'hardhat/console.sol'; // to use console.log\n\ncontract StorageMemory2 {\n    uint[] public values;\n\n    function doSomething() public\n    {\n        values.push(5);\n        values.push(10);\n\n        console.log(values[0]); // it will log: 5\n\n        uint[] memory newArray = values; // 'newArray' is a separate copy of 'values'\n\n        newArray[0] = 8888;\n\n        console.log(values[0]); // it will log: 5\n        console.log(newArray[0]); // it will log: 8888\n    }\n}\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\ncontract CallDataExample {\n    uint[] public values;\n\n    function doSomething() public\n    {\n        values.push(5);\n        values.push(10);\n\n        modifyArray(values);\n    }\n\n    function modifyArray(uint[] calldata arrayToModify) pure private {\n        arrayToModify[0] = 8888; // you will get an error saying the array is read only\n    }\n}\n```\n\n========================================\n\nComments:\n- Do you have any links to the docs that explain this? I would like to read a bit more on how does the storage works.\n- @Acapuclo It's in the FAQ \"What is the memory keyword? What does it do?\"\n- The FAQ links doesn't work, but if you want to read a similar link I suggest docs.soliditylang.org/en/v0.5.3/&hellip;\n- Here is an ariticle I found useful.\n- I read it but still need a beginner explanation on this, so basically to avoid an expensive operation (save on storage) we should use the `memory` keyword before a function param? If Memory is ephemeral then what's the reason for using it? And how can a contract still call those functions and therefore modify memory once it's already deployed?\n- As someone who hasn't used Solidity it seems bizarre that variables wouldn't be by default in memory and persisting them would be the thing that needs to be explicit\n- Could you add what is the difference to `calldata`?\n- > local variables of struct, array or mapping type reference storage by default if they are stored in storage that means they are part of the blockchain/contract state. Are you saying struct/arrays/mapping declared in a function ends up in the storage? How can they then be accessed (apart from during the call of that function)? Also can't this create bugs? I assumed if they are stored in storage, then their value persist across function calls, and you might not expect this to be the case\n- Since the `int[] storage myArray` is only a pointer to the numbers variable and no space in storage is reserved for myArray. What's the gas cost for myArray being assigned to numbers ?\n- Also, myArray is a storage reference, so does this pointer is stored in memory or storage itself ?\n- So in simple words (please current me if I'm wrong): `memory` keyword means 2 things: (1) copy by value. (2) declare a variable as a pointer to the new allocated-copied value. `storage` means: (1) do not copy by value; copy the reference. (2) declare a variable as a pointer to the new allocated-*not*-copied value.\n- @StavAlfi with memory keyword you make the storage varible local. Updated the answer","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":296,"estimatedTokens":2394}}60{"id":"stack-51372365","source":"stackoverflow","questionId":51372365,"title":"Warning: Using contract member \"balance\" inherited from the address type is deprecated. Solidity","tags":["ethereum","solidity","remix","ether"],"text":"Title: Warning: Using contract member \"balance\" inherited from the address type is deprecated. Solidity\nTags: ethereum, solidity, remix, ether\nSource: Stack Overflow\n\nQuestion:\nWarning: Using contract member \"balance\" inherited from the address type is deprecated. Convert the contract to \"address\" type to access the member, for example use \"address(contract).balance\" instead.\n\nI am getting this warning in Solidity using the Remix editor.\n\nThis is the code chunk:\n\n```\nfunction getSummary() public view returns(\n uint, uint, uint, uint, address\n){\n return (\n minimumContribution,\n this.balance, // This is the warning line.\n requests.length,\n approversCount,\n manager\n );\n}\n```\n\nI tried following what the warning suggests:\n\n```\nfunction getSummary() public view returns(\n uint, uint, uint, uint, address\n){\n return (\n minimumContribution,\n address(contract).balance,\n requests.length,\n approversCount,\n manager\n );\n}\n```\n\nBut that does not work.\n\n========================================\n\nTop Answer:\nAlternatively you could assign `this` to a local variable of type `address`...\n\n```\naddress contractAddress = this;\n\nfunction getSummary() public view returns(\n uint, uint, uint, uint, address\n){\n return (\n minimumContribution,\n contractAddress.balance,\n requests.length,\n approversCount,\n manager\n );\n}\n```\n\n========================================\n\nCode:\n```text\nfunction getSummary() public view returns(\n    uint, uint, uint, uint, address\n){\n    return (\n        minimumContribution,\n        this.balance, // This is the warning line.\n        requests.length,\n        approversCount,\n        manager\n    );\n}\n```\n\n```text\nfunction getSummary() public view returns(\n    uint, uint, uint, uint, address\n){\n    return (\n        minimumContribution,\n        address(contract).balance,\n        requests.length,\n        approversCount,\n        manager\n    );\n}\n```\n\n```text\nfunction getSummary() public view returns(\n    uint, uint, uint, uint, address\n){\n    return (\n        minimumContribution,\n        address(this).balance,\n        requests.length,\n        approversCount,\n        manager\n    );\n}\n```\n\n```text\nbalance\n```\n\n```text\naddress\n```\n\n```text\naddress(this).balance\n```\n\n```text\naddress contractAddress = this;\n\nfunction getSummary() public view returns(\n    uint, uint, uint, uint, address\n){\n  return (\n    minimumContribution,\n    contractAddress.balance,\n    requests.length,\n    approversCount,\n    manager\n  );\n}\n```\n\n```text\nthis\n```\n\n```text\naddress\n```\n\n========================================\n\nComments:\n- That's what I was looking for. Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":149,"estimatedTokens":644}}61{"id":"stack-69628306","source":"stackoverflow","questionId":69628306,"title":"How to pass empty bytes to a solidity function in Remix?","tags":["ethereum","solidity"],"text":"Title: How to pass empty bytes to a solidity function in Remix?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI couldnt figure out a way to pass empty bytes to a solidity function on remix.\nHere is my function\n\n```\nfunction checkEmptyBytes(bytes calldata _data) external pure returns (string memory){\n if (_data.length > 0){\n return \"NOT_ZERO\";\n }\n return \"ZER0\";\n \n }\n```\n\nOn remix, I have to pass _data such that it should return \"ZERO\"\n\n========================================\n\nTop Answer:\nYou can also use 0x (normally a bytes value is in the form of 0x123456, while 0x is basically an empty bytes).\n\n========================================\n\nCode:\n```text\nfunction checkEmptyBytes(bytes calldata _data) external pure returns (string memory){\n        if (_data.length > 0){\n            return \"NOT_ZERO\";\n        }\n        return \"ZER0\";\n        \n    }\n```\n\n```text\n[]\n```\n\n========================================\n\nComments:\n- If I use `[]` as a function parameter, when calling one function from another in Solidity, I get `TypeError: Unable to deduce common type for array elements.`\n- @LukeHutchison Depending on the called function param type, you need to actually declare the empty array - not just use the `[]` expression. Example: `string[] memory arr; innerFunction(arr);` for the `innerFunction` accepting `string[] memory`.\n- I'm trying to call a superconstructor from a constructor, and there's no chance to declare a local in that way before calling the superconstructor. I can't declare an empty array field that way either. It only works for locals. See: github.com/ethereum/solidity/issues/12401\n- @LukeHutchison It's currently (v0.8) not possible to both declare and pass a dynamic-length array in a one-line statement. Having said that, I responded with a workaround in the Github issue.\n- @PetrHejda You can also pass empty arrays like so `new address[](0)` (I chose address type here, but it works for any type)","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":50,"estimatedTokens":488}}62{"id":"stack-52065303","source":"stackoverflow","questionId":52065303,"title":"How to test payable method in truffle?","tags":["testing","ethereum","solidity","smartcontracts","truffle"],"text":"Title: How to test payable method in truffle?\nTags: testing, ethereum, solidity, smartcontracts, truffle\nSource: Stack Overflow\n\nQuestion:\nI'm trying to test smart contract's payable method in truffle framework: \n\n```\ncontract Contract {\n mapping (address => uint) public balances;\n\n function myBalance() public view returns(uint) {\n return balances[msg.sender];\n }\n\n function deposit() external payable {\n balances[msg.sender] += msg.value;\n }\n}\n\ncontract TestContract {\n\n function testDeposit() external payable {\n Contract c = new Contract();\n\n c.deposit.value(1);\n\n Assert.equal(c.myBalance(), 1, \"#myBalance() should returns 1\");\n }\n}\n```\n\nAfter I run `truffle test`, it's fails with `TestEvent(result: , message: #myBalance() should returns 1 (Tested: 0, Against: 1))` error. Why?\n\n========================================\n\nCode:\n```solidity\ncontract Contract {\n  mapping (address => uint) public balances;\n\n  function myBalance() public view returns(uint) {\n    return balances[msg.sender];\n  }\n\n  function deposit() external payable {\n    balances[msg.sender] += msg.value;\n  }\n}\n\ncontract TestContract {\n\n  function testDeposit() external payable {\n    Contract c = new Contract();\n\n    c.deposit.value(1);\n\n    Assert.equal(c.myBalance(), 1, \"#myBalance() should returns 1\");\n  }\n}\n```\n\n```text\ntruffle test\n```\n\n```text\nTestEvent(result: <indexed>, message: #myBalance() should returns 1 (Tested: 0, Against: 1))\n```\n\n```text\ncontract TestContract {\n  uint public initialBalance = 1 wei;\n\n  function testDeposit() external payable {\n    Contract c = new Contract();\n\n    c.deposit.value(1)();\n\n    Assert.equal(c.myBalance(), 1, \"#myBalance() should returns 1\");\n  }\n}\n```\n\n```text\nTestContract\n```\n\n```text\nContract\n```\n\n```text\ninitialBalance\n```\n\n```text\ndeposit\n```\n\n```text\ncontract.functionName.value(valueInWei)(<parameter list>)\n```\n\n```text\nTestContract\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":107,"estimatedTokens":470}}63{"id":"stack-50014286","source":"stackoverflow","questionId":50014286,"title":"Is it possible to predefine smart contracts in genesis.json?","tags":["blockchain","ethereum","solidity","smartcontracts","go-ethereum"],"text":"Title: Is it possible to predefine smart contracts in genesis.json?\nTags: blockchain, ethereum, solidity, smartcontracts, go-ethereum\nSource: Stack Overflow\n\nQuestion:\nI encountered exactly the same issue as this https://ethereum.stackexchange.com/questions/7707/is-it-possible-to-preload-contracts-in-the-genesis-block?rq=1\n\nAgian, is it possible to predefine a contract by assigning alloc -> code field like this,\n\nhttps://i.sstatic.net/28qsP.png\n\nHowever, it seems like no matter which method in the contract I call, it always returns the Bytecode of the contract itself regardless of the logic and content of this method.\n\nhttps://i.sstatic.net/Ujbax.png\n\nAnd this might be the reason when I deploy a contract:\n\nhttps://i.sstatic.net/ing5G.png\n\nWhen I call test(), obtaining:\n\nhttps://i.sstatic.net/Kc06Z.png\nwhich is not a string.\n\nWhen I call test2(), obtaining:\n\nhttps://i.sstatic.net/b3qc1.png\nwhich is a very big number.\n\nWhen I call test3(1), obtaining a false,\nwhich is not 1 == 1.\n\nI have taken a look through the related threads, found this, https://ethereum.stackexchange.com/questions/30366/how-does-the-genesis-json-file-define-the-initial-state-of-the-blockchain\n\nIt looks like the storage setting is necessary but I have totally no idea what key/value I should write.\n\nHow could I deal with this case then?\n\n========================================\n\nCode:\n```text\n--bin\n```\n\n```text\n--bin-runtime\n```\n\n```text\nsolc\n```\n\n```text\ncode\n```\n\n```text\n--bin\n```\n\n```text\n--bin-runtime\n```\n\n========================================\n\nComments:\n- ethereum.stackexchange.com/questions/7707/&hellip;\n- bytecode is generated via the Remix IDE. So you mean the bytecode generated in the first place is not the one actually stored in the statedb.Code/CodeHash? As such how could I get the code meant to be included in the contract?\n- sorry, i mean *to be included in the blockchain\n- solved by using solc --bin-runtime..Thx so much again.\n- @SaberYu Glad it helped. Please mark the answer as correct","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":73,"estimatedTokens":501}}64{"id":"stack-37644395","source":"stackoverflow","questionId":37644395,"title":"How to find out if an Ethereum address is a contract?","tags":["ethereum","blockchain","solidity","smartcontracts"],"text":"Title: How to find out if an Ethereum address is a contract?\nTags: ethereum, blockchain, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nAn address in Solidity can be an account or a contract (or other things, such as a transaction). When I have a variable x, holding an address, how can I test if it is a contract or not?\n\n(Yes, I've read the chapter on types in the doc)\n\n========================================\n\nTop Answer:\nYes you can, by using some EVM assembly code to get the address' code size:\n\n```\nfunction isContract(address addr) returns (bool) {\n uint size;\n assembly { size := extcodesize(addr) }\n return size > 0;\n}\n```\n\n========================================\n\nCode:\n```text\n> eth.getCode(\"0xbfb2e296d9cf3e593e79981235aed29ab9984c0f\")\n```\n\n```text\n0xbfb2e296d9cf3e593e79981235aed29ab9984c0f\n```\n\n```text\nfunction isContract(address addr) returns (bool) {\n  uint size;\n  assembly { size := extcodesize(addr) }\n  return size > 0;\n}\n```\n\n```text\nrequire(tx.origin == msg.sender);\n```\n\n```text\nisContract\n```\n\n```text\nrequire(msg.sender == tx.origin)\n```\n\n```text\nrequire(msg.sender == tx.origin)\n```\n\n```js\nconst Web3 = require('web3')\n\n// make sure you are running geth locally\nconst web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))\n\nis_contract = async function(address) {\n    res = await web3.eth.getCode(address)\n    return res.length > 5\n}\n\nis_contract('your address').then(console.log)\n```\n\n```text\npragma solidity ^0.8.1;\n\nfunction isContract(address account) internal view returns (bool) {\n    // This method relies on extcodesize/address.code.length, which returns 0\n    // for contracts in construction, since the code is only stored at the end\n    // of the constructor execution.\n\n    return account.code.length > 0;\n}\n```\n\n```text\nisContract\n```\n\n========================================\n\nComments:\n- The gas consumed by sending to contract is utterly different than the gas consumed by sending to an address. If there were a goal to treat those two things in the same way, there couldn't be a gas distinction.\n- This link is clearly outdated. It's 2021, this answer is from 2016.\n- Here's some info on how this function works\n- This code is dangerous and no longer advisable as it is hackable because EXTCODESIZE returns 0 in a contract's constructor.\n- this means that direct user is calling the function. this is one way of mitigating reentrancy attack because if `(tx.origin == msg.sender)` means there is not a chain of function calls\n- It should probably be pointed out that `require(msg.sender == tx.origin)` only detects if the caller of a function is an EOA, it can't be used to detect if any other third-party contract is an EOA (such as a contract that you want to call from your own function).\n- @LukeHutchison Upvoted, great point! Added the caller and callee case; happy to hear from you if I missed some things or you have other suggestions.\n- For completeness you could add that extcodesize is now abstracted away to `.code.size` in solidity (no assembly needed). People need to recognize this form too. (I might have the syntax wrong, I'm not near a computer right now.)\n- I don't think it makes much of a difference, but I'm curious as to why you went with `return res.length > 5`? If it's not a Smart contract shouldn't `res` be `0x`, meaning `res.length > 2` should work just as well? I guess you can also test for `res.startsWith(\"0x6080604052\")`?","metadata":{"transformedAt":"2026-08-18T18:33:36.116Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":99,"estimatedTokens":858}}65{"id":"stack-66799537","source":"stackoverflow","questionId":66799537,"title":"Member \"push\" not found or not visible after argument-dependent lookup in address payable[] storage ref","tags":["ethereum","solidity"],"text":"Title: Member \"push\" not found or not visible after argument-dependent lookup in address payable[] storage ref\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nIn the statement `players.push(msg.sender);` I am getting following error:\n\n**Member \"push\" not found or not visible after argument-dependent lookup in address payable[] storage ref.**\n\nThus I cannot push to address payable array in solidity. What's the workaround here?\n\n```\n// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.0;\n\ncontract Lottery {\n address public manager;\n address payable[] public players;\n\n constructor() {\n manager = msg.sender;\n }\n\n function enter() public payable {\n players.push(msg.sender); // ERROR IN THIS LINE\n }\n}\n```\n\n========================================\n\nTop Answer:\nI had to explicitly convert `msg.sender` into `payable` to get it working.\n\n```\n// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.7.0;\n\ncontract Lottery {\n address payable public manager;\n address payable[] public players;\n \n constructor() {\n manager = payable(msg.sender);\n }\n \n function enter() public payable {\n players.push(manager);\n } \n}\n```\n\nReferences:\n\nCasting from address to address payable\n\nTypeError: push is not detected as a function for address payable dynamic array\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.0;\n\ncontract Lottery {\n    address public manager;\n    address payable[] public players;\n\n    constructor() {\n        manager = msg.sender;\n    }\n\n    function enter() public payable {\n        players.push(msg.sender);            // ERROR IN THIS LINE\n    }\n}\n```\n\n```text\nplayers.push(msg.sender);\n```\n\n```text\nplayers.push(payable(msg.sender));\n```\n\n```text\nmsg.sender\n```\n\n```text\npayable\n```\n\n```text\npayable\n```\n\n```text\ntx.origin\n```\n\n```text\nmsg.sender\n```\n\n```text\naddress\n```\n\n```text\naddress payable\n```\n\n```text\naddress payable\n```\n\n```text\npayable(tx.origin)\n```\n\n```text\npayable(msg.sender)\n```\n\n```text\n// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.7.0;\n\ncontract Lottery {\n    address payable public manager;\n    address payable[] public players;\n    \n    constructor() {\n        manager = payable(msg.sender);\n    }\n    \n    function enter() public payable {\n        players.push(manager);\n    } \n}\n```\n\n```text\nmsg.sender\n```\n\n```text\npayable\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":154,"estimatedTokens":590}}66{"id":"stack-71936210","source":"stackoverflow","questionId":71936210,"title":"How do I determine whether a recipient is a liquidity pool?","tags":["ethereum","solidity","smartcontracts","uniswap"],"text":"Title: How do I determine whether a recipient is a liquidity pool?\nTags: ethereum, solidity, smartcontracts, uniswap\nSource: Stack Overflow\n\nQuestion:\nI'm creating a token which when sold on a liquidity pool, takes fees and burns a certain amount.\n\nGiven that I have a recipient address, how would I check whether it is a liquidity pool?\n\nI think I may be able to use this: https://docs.uniswap.org/protocol/V2/reference/smart-contracts/pair-erc-20 however I'm not sure which function would work or if there's another way.\n\n========================================\n\nTop Answer:\nIn Uniswap V3\n\n```\nimport \"@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol\";\n\n address poolAddress = IUniswapV3Factory(_factory).getPool(\n _token0,\n _token1,\n _fee\n );\n```\n\nyou can get the _factory address from here https://docs.uniswap.org/protocol/reference/deployments.\n\n`getPool` is a mapping.\n\n```\nmapping(address => mapping(address => mapping(uint24 => address))) public override getPool;\n```\n\nwhen you call `IUniswapV3Factory(_factory).getPool`, if the key does not exist it will return the default address type which is `address(0)`. so you should add an `require` condition\n\n```\nrequire(poolAddress!=address(0))\n```\n\nIf this condition passes, that means you got a valid pool address from the mapping.\n\n========================================\n\nCode:\n```text\npragma solidity ^0.8;\n\nimport \"https://github.com/Uniswap/v2-core/blob/master/contracts/interfaces/IUniswapV2Factory.sol\";\nimport \"https://github.com/Uniswap/v3-core/blob/main/contracts/interfaces/IUniswapV3Factory.sol\";\nimport \"https://github.com/Uniswap/v2-core/blob/master/contracts/interfaces/IUniswapV2Pair.sol\";\nimport \"https://github.com/Uniswap/v3-core/blob/main/contracts/interfaces/IUniswapV3Pool.sol\";\n\ncontract MyContract {\n    IUniswapV2Factory constant v2Factory = IUniswapV2Factory(address(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f));\n    IUniswapV3Factory constant v3Factory = IUniswapV3Factory(address(0x1F98431c8aD98523631AE4a59f267346ea31F984));\n\n    /**\n     * true on Ethereum mainnet - 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852\n     * false on Ethereum mainnet - 0xdAC17F958D2ee523a2206206994597C13D831ec7\n     */\n    function isUniswapV2Pair(address target) external view returns (bool) {\n        if (target.code.length == 0) {\n            return false;\n        }\n\n        IUniswapV2Pair pairContract = IUniswapV2Pair(target);\n\n        address token0;\n        address token1;\n\n        try pairContract.token0() returns (address _token0) {\n            token0 = _token0;\n        } catch (bytes memory) {\n            return false;\n        }\n\n        try pairContract.token1() returns (address _token1) {\n            token1 = _token1;\n        } catch (bytes memory) {\n            return false;\n        }\n\n        return target == v2Factory.getPair(token0, token1);\n    }\n\n    /**\n     * true on Ethereum mainnet - 0x4e68Ccd3E89f51C3074ca5072bbAC773960dFa36\n     * false on Ethereum mainnet - 0xdAC17F958D2ee523a2206206994597C13D831ec7\n     */\n    function isUniswapV3Pool(address target) external view returns (bool) {\n        if (target.code.length == 0) {\n            return false;\n        }\n\n        IUniswapV3Pool poolContract = IUniswapV3Pool(target);\n\n        address token0;\n        address token1;\n        uint24 fee;\n\n        try poolContract.token0() returns (address _token0) {\n            token0 = _token0;\n        } catch (bytes memory) {\n            return false;\n        }\n\n        try poolContract.token1() returns (address _token1) {\n            token1 = _token1;\n        } catch (bytes memory) {\n            return false;\n        }\n\n        try poolContract.fee() returns (uint24 _fee) {\n            fee = _fee;\n        } catch (bytes memory) {\n            return false;\n        }\n\n        return target == v3Factory.getPool(token0, token1, fee);\n    }\n}\n```\n\n```text\nif (target.code.length == 0)\n```\n\n```text\nimport \"@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol\";\n\n address poolAddress = IUniswapV3Factory(_factory).getPool(\n        _token0,\n        _token1,\n        _fee\n    );\n```\n\n```text\nmapping(address => mapping(address => mapping(uint24 => address))) public override getPool;\n```\n\n```text\nrequire(poolAddress!=address(0))\n```\n\n```text\ngetPool\n```\n\n```text\nIUniswapV3Factory(_factory).getPool\n```\n\n```text\naddress(0)\n```\n\n```text\nrequire\n```\n\n========================================\n\nComments:\n- Is this only for pools that are on uniswap? Or also pools that are on another DEX for example? I see that uniswap makes a distinction between Pair and Pair (ERC-20) contracts docs.uniswap.org/protocol/V2/reference/smart-contracts/pair . What's the difference?\n- @Ayudh This example works only with Uniswap (both V2 and V3) pools. Other DEXes usually implement the Uniswap interface but their factory contracts are deployed on a different address. So to expand this example to e.g. Sushiswap (which uses the Uniswap V2 interface), you'll need to create a new function, that practically copies the existing `isUniswapV2Pair()` - except it queries the Sushiswap factory address (`0xC0AE...`) instead of the Uniswap factory (`0x5C69...`).\n- I see, thank you. Lastly, could you explain the difference between Pair (ERC-20) and Pair contracts? docs.uniswap.org/protocol/V2/reference/smart-contracts/pair & docs.uniswap.org/protocol/V2/reference/smart-contracts/&hellip;\n- @Ayudh A \"Pair contract\" is their V2 wording for what is a Pool in V3 - a contract that holds liquidity of two tokens and allows users to swap them ... A \"Pair (ERC-20)\" is, in the context of Uniswap V2, a token representing liquidity in such \"Pair contract\". For example, you provide liquidity to a Pair contract A/B, and you are minted this ERC-20 token in exchange, representing your % stake in this total liquidity. When you decide to remove the liquidity, they burn these \"Pair ERC20\" tokens and send you back the original A and B tokens.\n- This added logic of the token, representing your liquidity stake, allows for trading the liquidity token as well. Same way as you could sell a a debt someone ows you to a third party in a regular finance.","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":170,"estimatedTokens":1533}}67{"id":"stack-51250211","source":"stackoverflow","questionId":51250211,"title":"Converting Object Promise to String in Javascript","tags":["javascript","reactjs","solidity","semantic-ui-react","next.js"],"text":"Title: Converting Object Promise to String in Javascript\nTags: javascript, reactjs, solidity, semantic-ui-react, next.js\nSource: Stack Overflow\n\nQuestion:\nI'm working with React, Next.Js, semantic-ui-react and Solidity. It is my goal to print out the users address (from MetaMask) and a ProjectTitle (set by User) as meta infomation for a semantic-ui-react card. To print out the address in the 'header' is working, but I'm not able to print out the ProjectTitle as 'meta'. The Title should be a String but I'm receiving a Object Promise. \n\n```\nstatic async getInitialProps() {\n const projects = await factory.methods.getDeployedProjects().call();\n return {\n projects\n };\n}\n\nasync getProjectTitle(address) {\n let title;\n try {\n title = await factory.methods.projectTitle(address).call();\n } catch (err) {\n console.log('err');\n }\n return title;\n}\n\nrenderProjects() {\n const items = this.props.projects.map(address => {\n return {\n header: address,\n color: 'green',\n description: (\n \n View Project\n \n ),\n **meta: this.getProjectTitle(address)**,\n fluid: true,\n style: { overflowWrap: 'break-word' }\n };\n }, );\n return \n}\n```\n\nPart of the Solidity Contract:\n\n```\naddress[] public deployedProjects;\nmapping(address => string) public projectTitle;\n\nfunction createProject(string startup, string title, string deadline, string description, uint wage) public {\n address newProject = new Project(startup, title, deadline, description, wage, msg.sender);\n projectTitle[newProject] = title;\n deployedProjects.push(newProject);\n}\n\nfunction getDeployedProjects() public view returns (address[]) {\n return (\n deployedProjects\n );\n}\n```\n\nThe basic framework is from the Udemy Course \"Ethereum and Solidity: The Complete Developer's Guide\" by Stephen Grider.\n\n========================================\n\nCode:\n```text\nstatic async getInitialProps() {\n    const projects = await factory.methods.getDeployedProjects().call();\n    return {\n        projects\n    };\n}\n\nasync getProjectTitle(address) {\n    let title;\n    try {\n        title = await factory.methods.projectTitle(address).call();\n    } catch (err) {\n        console.log('err');\n    }\n    return title;\n}\n\nrenderProjects() {\n    const items = this.props.projects.map(address => {\n        return {\n            header: address,\n            color: 'green',\n            description: (\n                <Link route={`/projects/${address}`}>\n                    <a>View Project</a>\n                </Link>\n            ),\n            **meta: this.getProjectTitle(address)**,\n            fluid: true,\n            style: { overflowWrap: 'break-word' }\n        };\n    }, );\n    return <Card.Group items={items} />\n}\n```\n\n```text\naddress[] public deployedProjects;\nmapping(address => string) public projectTitle;\n\nfunction createProject(string startup, string title, string deadline, string description, uint wage) public {\n    address newProject = new Project(startup, title, deadline, description, wage, msg.sender);\n    projectTitle[newProject] = title;\n    deployedProjects.push(newProject);\n}\n\nfunction getDeployedProjects() public view returns (address[]) {\n    return (\n        deployedProjects\n    );\n}\n```\n\n```text\nawait\n```\n\n```text\n.then()\n```\n\n========================================\n\nComments:\n- You can't \"convert\" the Promise; you have to `await` the function call or else explicitly use `.then()` and a callback function.\n- Ok, thank you. That's the answer I was expecting. But that brings me to another question which might be quite simple. I wrote the following lines: *var title = this.getProjectTitle(address).then(res => { console.log('res ', res); });* 'res' brings the type (string) which I need. But I don't know how to transfer the variable to the meta tag. Maybe I'm a bit slow today.\n- You can move the projectTitle async call just before the return { header: address, ... } object and wait for the promise to return. Inside thennable you can use setState() or any component function that records the result outside the scope of the thennable. As a downside, this makes the map() synchronized with waiting the results of these promises one by one. A better approach could be to use the new Promise.all() and fetch project names on initial render / mount depending if it is a function or a React.Component.","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":136,"estimatedTokens":1066}}68{"id":"stack-47129173","source":"stackoverflow","questionId":47129173,"title":"How to convert uint to string in solidity?","tags":["blockchain","solidity"],"text":"Title: How to convert uint to string in solidity?\nTags: blockchain, solidity\nSource: Stack Overflow\n\nQuestion:\nIn Solidity, is there a way I can convert my int to string ?\n\nExample:\n\n```\npragma solidity ^0.4.4;\n\ncontract someContract {\n\n uint i;\n\n function test() pure returns (string) {\n\n return \"Here and Now is Happiness!\";\n\n }\n\n function love() pure returns(string) {\n\n i = i +1;\n\n return \"I love \" + functionname(i) + \" persons\" ;\n }\n\n}\n```\n\nWhat is functionname?Thanks!\n\n========================================\n\nTop Answer:\n```\nsolidity ^0.8.0\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\n\nStrings.toString(myUINT)\n```\n\nworks for me.\n\nhttps://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol#L15-L35\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.4;\n\ncontract someContract {\n\n    uint i;\n\n    function test() pure returns (string) {\n\n      return \"Here and Now is Happiness!\";\n\n    }\n\n    function love() pure returns(string) {\n\n        i = i +1;\n\n        return \"I love \" + functionname(i) + \" persons\" ;\n    }\n\n\n\n}\n```\n\n```text\nfunction uintToString(uint v) constant returns (string str) {\n        uint maxlength = 100;\n        bytes memory reversed = new bytes(maxlength);\n        uint i = 0;\n        while (v != 0) {\n            uint remainder = v % 10;\n            v = v / 10;\n            reversed[i++] = byte(48 + remainder);\n        }\n        bytes memory s = new bytes(i + 1);\n        for (uint j = 0; j <= i; j++) {\n            s[j] = reversed[i - j];\n        }\n        str = string(s);\n    }\n```\n\n```text\n/// @notice converts number to string\n    /// @dev source: https://github.com/provable-things/ethereum-api/blob/master/oraclizeAPI_0.5.sol#L1045\n    /// @param _i integer to convert\n    /// @return _uintAsString\n    function uintToStr(uint _i) internal pure returns (string memory _uintAsString) {\n        uint number = _i;\n        if (number == 0) {\n            return \"0\";\n        }\n        uint j = number;\n        uint len;\n        while (j != 0) {\n            len++;\n            j /= 10;\n        }\n        bytes memory bstr = new bytes(len);\n        uint k = len - 1;\n        while (number != 0) {\n            bstr[k--] = byte(uint8(48 + number % 10));\n            number /= 10;\n        }\n        return string(bstr);\n    }\n```\n\n```text\n\"uintToStr\": Avoid assigning to function parameters. [security/no-assign-params]\n```\n\n```text\n_i\n```\n\n```text\nnumber\n```\n\n```text\nfunction uint2str(uint _i) internal pure returns (string memory _uintAsString) {\n        if (_i == 0) {\n            return \"0\";\n        }\n        uint j = _i;\n        uint len;\n        while (j != 0) {\n            len++;\n            j /= 10;\n        }\n        bytes memory bstr = new bytes(len);\n        uint k = len;\n        while (_i != 0) {\n            k = k-1;\n            uint8 temp = (48 + uint8(_i - _i / 10 * 10));\n            bytes1 b1 = bytes1(temp);\n            bstr[k] = b1;\n            _i /= 10;\n        }\n        return string(bstr);\n    }\n```\n\n```text\nuint2str()\n```\n\n```text\nbyte\n```\n\n```text\nbytes1\n```\n\n```text\nfunction uint2str(\n  uint256 _i\n)\n  internal\n  pure\n  returns (string memory str)\n{\n  if (_i == 0)\n  {\n    return \"0\";\n  }\n  uint256 j = _i;\n  uint256 length;\n  while (j != 0)\n  {\n    length++;\n    j /= 10;\n  }\n  bytes memory bstr = new bytes(length);\n  uint256 k = length;\n  j = _i;\n  while (j != 0)\n  {\n    bstr[--k] = bytes1(uint8(48 + j % 10));\n    j /= 10;\n  }\n  str = string(bstr);\n}\n```\n\n```text\nfunction uintToString(uint v, bool scientific) public pure returns (string memory str) {\n\n    if (v == 0) {\n        return \"0\";\n    }\n\n    uint maxlength = 100;\n    bytes memory reversed = new bytes(maxlength);\n    uint i = 0;\n    \n    while (v != 0) {\n        uint remainder = v % 10;\n        v = v / 10;\n        reversed[i++] = byte(uint8(48 + remainder));\n    }\n\n    uint zeros = 0;\n    if (scientific) {\n        for (uint k = 0; k < i; k++) {\n            if (reversed[k] == '0') {\n                zeros++;\n            } else {\n                break;\n            }\n        }\n    }\n\n    uint len = i - (zeros > 2 ? zeros : 0);\n    bytes memory s = new bytes(len);\n    for (uint j = 0; j < len; j++) {\n        s[j] = reversed[i - j - 1];\n    }\n\n    str = string(s);\n\n    if (scientific && zeros > 2) {\n        str = string(abi.encodePacked(s, \"e\", uintToString(zeros, false)));\n    }\n}\n```\n\n```text\nfunction testUintToString() public {\n\n    Assert.equal(Utils.uintToString(0, true), '0', '0');\n    Assert.equal(Utils.uintToString(1, true), '1', '1');\n    Assert.equal(Utils.uintToString(123, true), '123', '123');\n    Assert.equal(Utils.uintToString(107680546035, true), '107680546035', '107680546035');\n    Assert.equal(Utils.uintToString(1e9, true), '1e9', '1e9');\n    Assert.equal(Utils.uintToString(1 ether, true), '1e18', '1 ether');\n    Assert.equal(Utils.uintToString(550e8, true), '55e9', '55e9');\n}\n```\n\n```text\n0.6.0\n```\n\n```text\nsolidity ^0.8.0\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\n\nStrings.toString(myUINT)\n```\n\n```solidity\nfunction itoa32 (uint x) private pure returns (uint y) {\n    unchecked {\n        require (x < 1e32);\n        y = 0x3030303030303030303030303030303030303030303030303030303030303030;\n        y += x % 10; x /= 10;\n        y += x % 10 << 8; x /= 10;\n        y += x % 10 << 16; x /= 10;\n        y += x % 10 << 24; x /= 10;\n        y += x % 10 << 32; x /= 10;\n        y += x % 10 << 40; x /= 10;\n        y += x % 10 << 48; x /= 10;\n        y += x % 10 << 56; x /= 10;\n        y += x % 10 << 64; x /= 10;\n        y += x % 10 << 72; x /= 10;\n        y += x % 10 << 80; x /= 10;\n        y += x % 10 << 88; x /= 10;\n        y += x % 10 << 96; x /= 10;\n        y += x % 10 << 104; x /= 10;\n        y += x % 10 << 112; x /= 10;\n        y += x % 10 << 120; x /= 10;\n        y += x % 10 << 128; x /= 10;\n        y += x % 10 << 136; x /= 10;\n        y += x % 10 << 144; x /= 10;\n        y += x % 10 << 152; x /= 10;\n        y += x % 10 << 160; x /= 10;\n        y += x % 10 << 168; x /= 10;\n        y += x % 10 << 176; x /= 10;\n        y += x % 10 << 184; x /= 10;\n        y += x % 10 << 192; x /= 10;\n        y += x % 10 << 200; x /= 10;\n        y += x % 10 << 208; x /= 10;\n        y += x % 10 << 216; x /= 10;\n        y += x % 10 << 224; x /= 10;\n        y += x % 10 << 232; x /= 10;\n        y += x % 10 << 240; x /= 10;\n        y += x % 10 << 248;\n    }\n}\n\nfunction itoa (uint x) internal pure returns (string memory s) {\n    unchecked {\n        if (x == 0) return \"0\";\n        else {\n            uint c1 = itoa32 (x % 1e32);\n            x /= 1e32;\n            if (x == 0) s = string (abi.encode (c1));\n            else {\n                uint c2 = itoa32 (x % 1e32);\n                x /= 1e32;\n                if (x == 0) {\n                    s = string (abi.encode (c2, c1));\n                    c1 = c2;\n                } else {\n                    uint c3 = itoa32 (x);\n                    s = string (abi.encode (c3, c2, c1));\n                    c1 = c3;\n                }\n            }\n            uint z = 0;\n            if (c1 >> 128 == 0x30303030303030303030303030303030) { c1 <<= 128; z += 16; }\n            if (c1 >> 192 == 0x3030303030303030) { c1 <<= 64; z += 8; }\n            if (c1 >> 224 == 0x30303030) { c1 <<= 32; z += 4; }\n            if (c1 >> 240 == 0x3030) { c1 <<= 16; z += 2; }\n            if (c1 >> 248 == 0x30) { z += 1; }\n            assembly {\n                let l := mload (s)\n                s := add (s, z)\n                mstore (s, sub (l, z))\n            }\n        }\n    }\n}\n```\n\n```text\nitoa32\n```\n\n```text\nitoa\n```\n\n```text\nitoa32\n```\n\n```text\nstring(abi.encode(myUint))\n```\n\n```text\nfunction uint2str(uint256 _i) internal pure returns (string memory result) {\n    if (_i == 0) {\n        return \"0\";\n    }\n    uint256 temp = _i;\n    uint256 length;\n    while (temp != 0) {\n        length++;\n        temp /= 10;\n    }\n    bytes memory buffer = new bytes(length);\n    while (_i != 0) {\n        length--;\n        buffer[length] = bytes1(uint8(48 + (_i % 10)));\n        _i /= 10;\n    }\n    return string(buffer);\n}\n```\n\n```text\nHandles the edge case where _i is 0 by returning \"0\".\nCalculates the number of digits in _i to size the bytes array.\nBuilds the string digit-by-digit using ASCII values (48 is '0', and + (_i % 10) adjusts for each digit).\nConverts the bytes array to a string.\n```\n\n========================================\n\nComments:\n- This variant was buggy when I tested it, solution from Oraclize github.com/oraclize/ethereum-api/blob/master/&hellip; may be better: function uint2str(uint i) internal pure returns (string){ if (i == 0) return \"0\"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); }\n- Yeah I agree that the version in the answer did not work for me, but the one provided in github.com/provable-things/ethereum-api/blob/master/&hellip; did, as pointed out by Dmitriy above here.\n- Also: solc 0.7.0 does not like `byte(48 + remainder)`. Cannot explicitly convert uint256 to bytes1.\n- This version works with solidity 0.8.1 ! Please upvote. :)\n- Can you modify this to have a decimals parameters? e.g., if uint is 20000 and decimals is 3, then the result would be 20.\n- appriciate the update\n- This should be the accepted answer.\n- Agreed this should be accepted\n- Perfect answer. Also to concatenate strings, `+` doesn't work, but this shall be done with `return string(abi.encodePacked(\"I love \", Strings.toString(i), \" persons\"));`\n- Now you can do string.concat(s1, s2) @ChristopheVidal","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":399,"estimatedTokens":2412}}69{"id":"stack-67341914","source":"stackoverflow","questionId":67341914,"title":"ERROR send and transfer are only available for objects of type address payable , not address","tags":["solidity"],"text":"Title: ERROR send and transfer are only available for objects of type address payable , not address\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\n```\nfunction finalizeRequest(uint index) public restricted {\n Request storage request = requests[index];\n \n require(request.approvalCount > (approversCount / 2));\n require(!request.complete);\n \n request.recipient.transfer(request.value);\n request.complete = true;\n}\n```\n\nerror line ---> `request.recipient.transfer(request.value);`\n\ncan someone help me with this? Thank you.\n\nsolidity version I'm using:\n\n```\npragma solidity >0.4.17 <0.8.0;\n```\n\n========================================\n\nTop Answer:\nIf you are using a complier older than 0.6, you can declare `recipient` as `address payable` instead of `address`.\nIf you are using a compiler more or equal to 0.6, you can use the solution provided by @Petr Hejda.\n\n========================================\n\nCode:\n```text\nfunction finalizeRequest(uint index) public restricted {\n    Request storage request = requests[index];\n    \n    require(request.approvalCount > (approversCount / 2));\n    require(!request.complete);\n    \n    request.recipient.transfer(request.value);\n    request.complete = true;\n}\n```\n\n```text\npragma solidity >0.4.17 <0.8.0;\n```\n\n```text\nrequest.recipient.transfer(request.value);\n```\n\n```text\npayable(request.recipient).transfer(request.value);\n```\n\n```text\nrequest.recipient\n```\n\n```text\npayable\n```\n\n```text\ntx.origin\n```\n\n```text\nmsg.sender\n```\n\n```text\naddress\n```\n\n```text\naddress payable\n```\n\n```text\naddress payable\n```\n\n```text\npayable(tx.origin)\n```\n\n```text\npayable(msg.sender)\n```\n\n```text\nrecipient\n```\n\n```text\naddress payable\n```\n\n```text\naddress\n```\n\n========================================\n\nComments:\n- That gives me: ParserError: Expected primary expression.payable(orders[i].investor).transfer(msg.value * orders[i].amount / totalRaised); ^-----^\n- @lampbottle This seems like a syntax error unrelated to this question. Please post a separate question with steps to reproduce your issue.\n- It was because I was using an older version of solidity","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":114,"estimatedTokens":523}}70{"id":"stack-68198724","source":"stackoverflow","questionId":68198724,"title":"How would I send an eth value to specific smart contract function that is payable in ethers.js?","tags":["node.js","ethereum","solidity","ethers.js"],"text":"Title: How would I send an eth value to specific smart contract function that is payable in ethers.js?\nTags: node.js, ethereum, solidity, ethers.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to call a payable function on a smart contract that only accepts one argument.\n\nHow would I send an eth value to this function in ethers.js along with the function call? The docs don't seem to give much examples on the best way to do this.\n\nMy function call\n\n```\nconst reciept = await contract.buyPunk(1001);\n```\n\nall other read and write function calls work as expected, but its calling a payable function that I have yet to solve.\n\n========================================\n\nCode:\n```text\nconst reciept = await contract.buyPunk(1001);\n```\n\n```js\nconst options = {value: ethers.utils.parseEther(\"1.0\")}\nconst reciept = await contract.buyPunk(1001, options);\n```\n\n```text\nvalue\n```\n\n========================================\n\nComments:\n- Does this answer your question? How to test payable/external method with waffle and ethers.js\n- With unit testing, the notation is different as you're working within chai's framework, thanks for the suggestion though\n- Thanks a bunch! This solved it, yes I did see that in the documentation, but wasn't sure what properties the object should contain. Pretty cool that you can specific GasLimit and price also within the object. Makes for a nice modular approach\n- Is there any option to use something similar to specify which erc20 does the value net to be paid in? Let's say I would like to force the user to pay 100 USDC.\n- I'm trying something simiar, but it's returning `Error: non-payable method cannot override value`. Any idea on how to fix this?\n- I was trying to find this solution for many hours, thanks pal!","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":42,"estimatedTokens":437}}71{"id":"stack-52113202","source":"stackoverflow","questionId":52113202,"title":"How to set default parameters to functions in Solidity","tags":["solidity"],"text":"Title: How to set default parameters to functions in Solidity\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI came across below example from the `Solidity Documentation` and have similar code in my project and want to set `default value` to key parameter if the key is not passed from the caller\n\n```\npragma solidity ^0.4.0;\n\ncontract C {\n function f(uint key, uint value) public {\n // ...\n }\n\n function g() public {\n // named arguments\n f({value: 2, key: 3});\n }\n}\n```\n\nMy questions are -\n\n- Do Solidity language provides `default parameters`?\n\n- How to achieve the same if default parameters are not allowed then?\n\nAppreciate the help?\n\n========================================\n\nTop Answer:\nOpenzeppelin does a great job exemplifying how you can make \"default\" arguments. Check out their SafeMath Library.\n\nIn it, they have two sub (subtraction) contracts that are identical visibility and mutability wise- but a key difference:\n\n```\nfunction sub(\n uint256 a,\n uint256 b\n)internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n}\n\nfunction sub(\n uint256 a,\n uint256 b,\n string memory errorMessage\n) internal pure returns (uint256) {\n require(b The first one by default takes two arguments a & b (which will be subtracted). If a third argument is not given (the error statement) it will default to\n\nSafeMath: subtraction overflow\n\nIf a third argument is given, it will replace that error statement.\n\nEssentially:\n\n```\npragma solidity >=0.6.0 <0.9.0;\n\ncontract C {\n function f(unit value) public {\n uint defaultVal = 5;\n f(defaultVal, value);\n\n function f(uint key, uint value) public {\n // ...\n }\n\n function g() public {\n // named arguments\n f(2, 3);\n }\n}\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.0;\n\ncontract C {\n    function f(uint key, uint value) public {\n        // ...\n    }\n\n    function g() public {\n        // named arguments\n        f({value: 2, key: 3});\n    }\n}\n```\n\n```text\nSolidity Documentation\n```\n\n```text\ndefault value\n```\n\n```text\ndefault parameters\n```\n\n```text\npragma solidity ^0.4.0;\n\ncontract C {\n    function f(uint key, uint value) public {\n        // ...\n    }\n\n    function h(uint value) public {\n        f(123, value);\n    }\n\n    function g() public {\n        // named arguments\n        f({value: 2, key: 3});\n    }\n\n    function i() public {\n        h({value: 2});\n    }\n}\n```\n\n```text\nfunction sub(\n    uint256 a,\n    uint256 b\n)internal pure returns (uint256) {\n    return sub(a, b, \"SafeMath: subtraction overflow\");\n}\n\nfunction sub(\n    uint256 a,\n    uint256 b,\n    string memory errorMessage\n) internal pure returns (uint256) {\n    require(b <= a, errorMessage);\n    uint256 c = a - b;\n\n    return c;\n}\n```\n\n```text\npragma solidity >=0.6.0 <0.9.0;\n\ncontract C {\n    function f(unit value) public {\n        uint defaultVal = 5;\n        f(defaultVal, value);\n\n    function f(uint key, uint value) public {\n        // ...\n    }\n\n    function g() public {\n        // named arguments\n        f(2, 3);\n    }\n}\n```\n\n========================================\n\nComments:\n- It seems worth pointing out that Solidity allows functions with the same name, if they have different argument types. So they could all be called `f(...)`.\n- Very true. I have no idea why I used `h()`...especially after mentioning function overloading.\n- Thank you Adam and Carver that's a very valid information\n- This is briliant... Been wondering about it for a while.\n- But, with this solution how I can use both `f` methods from web3? Because I could only use the first method f.\n- @HenryPalacios I believe if it doesn't work by calling `f()` with the supplied arguments (2 vs 3) you may need to get the HASH ID name and call the function that way from a web3 perspective.","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":178,"estimatedTokens":938}}72{"id":"stack-42520069","source":"stackoverflow","questionId":42520069,"title":"Handling user profiles in Ethereum DApps","tags":["blockchain","ethereum","solidity","ipfs"],"text":"Title: Handling user profiles in Ethereum DApps\nTags: blockchain, ethereum, solidity, ipfs\nSource: Stack Overflow\n\nQuestion:\nI'm in the process of creating an Ethereum DApp. The DApp consists of users who have associated data like email, name, and a profile picture. I would like to store the contents of the user within IPFS as a JSON object and reference this on chain using the IPFS hash. How could I go about associating this data with a particular user? In the sense, that subsequent interactions with the DApp connect the user with the data stored in IPFS. Is this done using the users account hash with a password of some sort?\n\nFor example, **user A** is interested in using the DApp and so, provides his or her email, name, and profile picture. Then any subsequent interaction with the DApp, like a comment or post would link this user to the respective user data in IPFS.\n\nAny suggestions or adjustments to this way of modeling users would be greatly appreciated. Thanks!\n\n(P.S. I come from the traditional web/mobile app world so I'm just getting accustomed to modeling things using smart contracts. So I apologize in advance if this is a simple or ill-structured question.)\n\n========================================\n\nCode:\n```text\nweb3.eth.accounts[0]\n```\n\n========================================\n\nComments:\n- Thanks for the great response! You clarified a considerable amount of my confusion. I'm going to model this using IPFS with your approach. I think what I couldn't quite grasp was the idea of the user being tied to an ethereum account which can be accessed through a special DApp browser. So essentially in order for the user to interact with any DApp they would need to have mist installed locally which would require the DApp to be a client application. Or if it is going to be a website, they would need MetaMask installed, so that web3 could be used to retrieve their account.\n- top notch response i didnt know this is how it works thanks !!\n- is it possible for a malicious user to inject his own fake object web3 (using the javascript console in the browser) with accounts[0] address set to someone else's, and fool the \"zero click login\" system to gain access to such a DApp? Obviously, he'd not be able to transact, but might be able to view things which aren't viewable normally?","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":26,"estimatedTokens":578}}73{"id":"stack-59651032","source":"stackoverflow","questionId":59651032,"title":"Why does Solidity suggest me to implement a receive ether function when I have a fallback function?","tags":["solidity"],"text":"Title: Why does Solidity suggest me to implement a receive ether function when I have a fallback function?\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nThe recent change in Solidity changed the fallback function format from just function() to fallback(), which is pretty nice for beginners to understand what is going on, but I have a question about a suggestion that the compiler gives me when I implement such a fallback.\n\nFor example, a piece of code from my project:\n\n```\npragma solidity ^0.6.1;\n\ncontract payment{\n mapping(address => uint) _balance;\n\n fallback() payable external {\n _balance[msg.sender] += msg.value;\n }\n}\n```\n\nEverything goes fine, but the compiler suggests that:\n\n```\nWarning: This contract has a payable fallback function, but no receive ether function.\nConsider adding a receive ether function.\n```\n\nWhat does it mean by a receive ether function? I tried looking it up and many examples I could find is just another fallback function.\n\nI am using version 0.6.1+commit.e6f7d5a4\n\n========================================\n\nTop Answer:\nAs a complement to the accepted answer, here's how you should define the unnamed **fallback** and **receive** functions to solve this error:\n\n```\ncontract MyContract {\n\n fallback() external payable {\n // custom function code\n }\n\n receive() external payable {\n // custom function code\n }\n}\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.6.1;\n\ncontract payment{\n    mapping(address => uint) _balance;\n\n    fallback() payable external {\n        _balance[msg.sender] += msg.value;\n    }\n}\n```\n\n```text\nWarning: This contract has a payable fallback function, but no receive ether function.\nConsider adding a receive ether function.\n```\n\n```text\ncontract MyContract {\n\n    fallback() external payable {\n        // custom function code\n    }\n\n    receive() external payable {\n        // custom function code\n    }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":82,"estimatedTokens":477}}74{"id":"stack-49345903","source":"stackoverflow","questionId":49345903,"title":"Copying of type struct memory[] memory to storage not yet supported","tags":["solidity","smartcontracts"],"text":"Title: Copying of type struct memory[] memory to storage not yet supported\nTags: solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nHow do I add a new empty Parent instance to the list of parents in the code sample below? I keep getting\n\n```\nUnimplementedFeatureError: Copying of type struct Test.Child memory[] memory\nto storage not yet supported.\n```\n\nMinimal example:\n\n```\ncontract Test {\n struct Child { } \n struct Parent { Child[] children; }\n\n Parent[] parents;\n\n function test() {\n parents.push(Parent(new Child[](0)));\n }\n}\n```\n\n========================================\n\nTop Answer:\nIt doesn’t work (as of Solidity 0.4.24, at least) if the child array type is another struct, but it works if the child array type is a primitive type like `uint256`.\n\nSo if you have e.g.\n\n```\nstruct Child {\n uint256 x;\n bytes32 y;\n}\n```\n\nthen you could define:\n\n```\nstruct Parent {\n uint256[] childXs;\n bytes32[] childYs;\n}\n```\n\nand then you could write:\n\n```\nparents.push(Parent({\n childXs: new uint256[](0),\n childYs: new bytes32[](0)\n}));\n```\n\n(Same workaround is applicable when you want to pass an array of structs as an argument to a public function.)\n\nIt’s not ideal, but it works.\n\nP.S. Actually (if you are using the primitive array children) you could just write:\n\n```\nParent memory p;\nparents.push(p);\n```\n\n========================================\n\nCode:\n```text\nUnimplementedFeatureError: Copying of type struct Test.Child memory[] memory\nto storage not yet supported.\n```\n\n```text\ncontract Test {\n  struct Child { } \n  struct Parent { Child[] children; }\n\n  Parent[] parents;\n\n  function test() {\n    parents.push(Parent(new Child[](0)));\n  }\n}\n```\n\n```text\ncontract Test {\n  struct Child { } \n  struct Parent { \n      mapping(uint => Child) children;\n      uint childrenSize;\n  }\n\n  Parent[] parents;\n\n  function testWithEmptyChildren() public {\n      parents.push(Parent({childrenSize: 0}));\n  }\n\n  function testWithChild(uint index) public {\n      Parent storage p = parents[index];\n\n      p.children[p.childrenSize] = Child();\n      p.childrenSize++;\n  }\n}\n```\n\n```text\ncontract Test {\n  struct Child { } \n  struct Parent { Child[] children; }\n\n  Parent[] parents;\n\n  function test() public {\n      parents.length++;\n      Parent storage p = parents[parents.length - 1];\n\n      Child memory c;\n\n      p.children.push(c);\n  }\n}\n```\n\n```text\nParent.childrenSize\n```\n\n```text\nParent.children\n```\n\n```text\nparents\n```\n\n```text\nstruct Child {\n  uint256 x;\n  bytes32 y;\n}\n```\n\n```text\nstruct Parent {\n  uint256[] childXs;\n  bytes32[] childYs;\n}\n```\n\n```text\nparents.push(Parent({\n    childXs: new uint256[](0),\n    childYs: new bytes32[](0)\n}));\n```\n\n```text\nParent memory p;\nparents.push(p);\n```\n\n```text\nuint256\n```\n\n========================================\n\nComments:\n- Thanks! So you're saying that arrays can't be used that way and you'll have to use mappings as a workaround?\n- For this specific example, yes. The issue is you're trying to create what is essentially an empty `Parent` that has non-optional members. This could be the result of you providing a minimal example, but the approach is a bit weird because typically you wouldn't attempt to create an empty `Parent` like this. You would just increase the size of the array and Solidity automatically sets values to \"zero\". I'll edit the answer to include that last point.","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":179,"estimatedTokens":837}}75{"id":"stack-53353167","source":"stackoverflow","questionId":53353167,"title":"npm solc: AssertionError [ERR_ASSERTION]: Invalid callback specified","tags":["node.js","npm","ethereum","solidity"],"text":"Title: npm solc: AssertionError [ERR_ASSERTION]: Invalid callback specified\nTags: node.js, npm, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI am trying to compile solidity smart contract using npm solc. I tried to different examples. \nLink to example: https://medium.com/coinmonks/how-to-compile-a-solidity-smart-contract-using-node-js-51ea7c6bf440\n\nI wrote my code like following:\n\n```\nconst path = require('path');\nconst fs = require('fs');\nconst solc = require('solc');\n\nconst helloPath = path.resolve(__dirname, 'contracts', 'hello.sol');\nconsole.log(\"First\" + helloPath);\nconst source = fs.readFileSync(helloPath, 'UTF-8');\nconsole.log(\"Second\" + source);\nconsole.log(solc.compile(source, 1));\n```\n\nI am getting following error when running the above code.\n\n```\nAssertionError [ERR_ASSERTION]: Invalid callback specified.\n at wrapCallback (C:\\Users\\mouazzamj058\\solc_example\\node_modules\\solc\\wrapper.js:16:5)\n at runWithReadCallback (C:\\Users\\mouazzamj058\\solc_example\\node_modules\\solc\\wrapper.js:37:42)\n at compileStandard (C:\\Users\\mouazzamj058\\solc_example\\node_modules\\solc\\wrapper.js:78:14)\n at Object.compileStandardWrapper (C:\\Users\\mouazzamj058\\solc_example\\node_modules\\solc\\wrapper.js:85:14)\n at Object. (C:\\Users\\mouazzamj058\\solc_example\\example.js:4:19)\n at Module._compile (module.js:652:30)\n at Object.Module._extensions..js (module.js:663:10)\n at Module.load (module.js:565:32)\n at tryModuleLoad (module.js:505:12)\n at Function.Module._load (module.js:497:3)\n```\n\nPlease help.\n\n========================================\n\nTop Answer:\nIf you are using latest version ie. 0.5.9 there is change in how you compile the code.\n\n```\nconst path = require('path');\nconst fs = require('fs');\nconst solc = require('solc');\n\nconst helloPath = path.resolve(__dirname, 'contracts', 'hello.sol');\nconst source = fs.readFileSync(helloPath, 'UTF-8');\n\nvar input = {\n language: 'Solidity',\n sources: {\n 'hello.sol' : {\n content: source\n }\n },\n settings: {\n outputSelection: {\n '*': {\n '*': [ '*' ]\n }\n }\n }\n}; \nconsole.log(JSON.parse(solc.compile(JSON.stringify(input))));\n```\n\n========================================\n\nCode:\n```text\nconst path = require('path');\nconst fs = require('fs');\nconst solc = require('solc');\n\n\n\nconst helloPath = path.resolve(__dirname, 'contracts', 'hello.sol');\nconsole.log(\"First\" + helloPath);\nconst source = fs.readFileSync(helloPath, 'UTF-8');\nconsole.log(\"Second\" + source);\nconsole.log(solc.compile(source, 1));\n```\n\n```text\nAssertionError [ERR_ASSERTION]: Invalid callback specified.\n    at wrapCallback (C:\\Users\\mouazzamj058\\solc_example\\node_modules\\solc\\wrapper.js:16:5)\n    at runWithReadCallback (C:\\Users\\mouazzamj058\\solc_example\\node_modules\\solc\\wrapper.js:37:42)\n    at compileStandard (C:\\Users\\mouazzamj058\\solc_example\\node_modules\\solc\\wrapper.js:78:14)\n    at Object.compileStandardWrapper (C:\\Users\\mouazzamj058\\solc_example\\node_modules\\solc\\wrapper.js:85:14)\n    at Object.<anonymous> (C:\\Users\\mouazzamj058\\solc_example\\example.js:4:19)\n    at Module._compile (module.js:652:30)\n    at Object.Module._extensions..js (module.js:663:10)\n    at Module.load (module.js:565:32)\n    at tryModuleLoad (module.js:505:12)\n    at Function.Module._load (module.js:497:3)\n```\n\n```text\nnpm uninstall solc\nnpm install solc@0.4.25\n```\n\n```text\npragma solidity ^0.4.17\n```\n\n```text\nnpm install solc@0.4.17\n```\n\n```text\nconst path = require('path');\nconst fs = require('fs');\nconst solc = require('solc');\n\n\n\nconst helloPath = path.resolve(__dirname, 'contracts', 'hello.sol');\nconst source = fs.readFileSync(helloPath, 'UTF-8');\n\nvar input = {\n    language: 'Solidity',\n    sources: {\n        'hello.sol' : {\n            content: source\n        }\n    },\n    settings: {\n        outputSelection: {\n            '*': {\n                '*': [ '*' ]\n            }\n        }\n    }\n}; \nconsole.log(JSON.parse(solc.compile(JSON.stringify(input))));\n```\n\n```text\nnpm install --save solc@0.4.17\n```\n\n```text\nnpm install --save solc@0.4.25\n```\n\n```js\nconst solc = require('solc');\n\nvar input = {\n    language: 'Solidity',\n    sources: {\n        'hello.sol': {\n            content: 'contract hello { function f() public { } }'\n        }\n    },\n    settings: {\n        outputSelection: {\n            '*': {\n                '*': ['*']\n            }\n        }\n    }\n};\n\nvar output = JSON.parse(solc.compile(JSON.stringify(input)));\nconsole.log(output);\n```\n\n```text\nconst path = require('path');\nconst solc = require('solc');\nconst fs = require('fs-extra');\n\nconst buildPath = path.resolve(__dirname, 'build');\nfs.removeSync(buildPath); // remove build folder\n\n// Read 'hello.sol' file from the 'contracts' folder\nconst helloPath = path.resolve(__dirname, 'contracts', 'hello.sol');\nconst source = fs.readFileSync(helloPath, 'utf8');\n\nvar input = {\n    language: 'Solidity',\n    sources: {\n        'hello.sol': {\n            content: source\n        }\n    },\n    settings: {\n        outputSelection: {\n            '*': {\n                '*': ['*']\n            }\n        }\n    }\n};\n\n\nvar output = JSON.parse(solc.compile(JSON.stringify(input)));\n\nfs.ensureDirSync(buildPath); // ensure build folder exists\n\nfor (let contract in output) {\n    fs.outputJSONSync(\n        path.resolve(buildPath, contract + '.json'),\n        output[contract]\n    );\n}\n```\n\n```html\nconst path = require('path');\nconst solc = require('solc');\nconst fs = require('fs-extra');\n\nconst buildPath = path.resolve(__dirname, 'build');\nfs.removeSync(buildPath);\n\nconst campaignPath = path.resolve(__dirname, 'contracts', 'Campaign.sol');\nconst source = fs.readFileSync(campaignPath, 'UTF-8');\n\nvar input = {\n    language: 'Solidity',\n    sources: {\n        'Campaign.sol' : {\n            content: source\n        }\n    },\n    settings: {\n        outputSelection: {\n            '*': {\n                '*': [ '*' ]\n            }\n        }\n    }\n};\n\nvar output = JSON.parse(solc.compile(JSON.stringify(input)));\nfs.ensureDirSync(buildPath);\n\nfor(contractName in output.contracts['Campaign.sol']){\n    fs.outputJSONSync(\n        path.resolve(buildPath, contractName + '.json'),\n        output.contracts['Campaign.sol'][contractName]\n    );\n}\n```\n\n```html\nconst HDWalletProvider = require('@truffle/hdwallet-provider');\nconst Web3 = require('web3');\nconst compiledFactory = require('./build/CampaignFactory.json');\n\nconst provider = new HDWalletProvider(\n    process.env.NEXT_PUBLIC_META_MASK,\n    process.env.NEXT_PUBLIC_INFURA_API\n);\n\nconst web3 = new Web3(provider);\n\nconst deploy = async () => {\n    const accounts = await web3.eth.getAccounts();\n    console.log('attempting to deploy from account: ', accounts[0]);\n\n    const result = await new web3.eth.Contract(compiledFactory.abi)\n    .deploy({data: compiledFactory.evm.bytecode.object})\n    .send( {from:accounts[0], gas:'3000000'});\n\n    console.log('Contract deployed to: ', result.options.address);\n    provider.engine.stop();\n};\n\ndeploy();\n```\n\n========================================\n\nComments:\n- Are you sure this error is from `solc`. Can you debug and see where exactly you get the error from?\n- There was a bug I guess. Installing solc@0.4.25 worked.\n- This should be the accepted answer simply downgrading the version is not a solution\n- but going foward","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":287,"estimatedTokens":1806}}76{"id":"stack-48664570","source":"stackoverflow","questionId":48664570,"title":"what approve and allowance methods are really doing in ERC20 Standard?","tags":["blockchain","ethereum","solidity","smartcontracts","erc20"],"text":"Title: what approve and allowance methods are really doing in ERC20 Standard?\nTags: blockchain, ethereum, solidity, smartcontracts, erc20\nSource: Stack Overflow\n\nQuestion:\nThe problem is what `allowance` and `approve` are really doing?\n\nAnd what is `_spender` and what is it doing?\n\nIs there anybody who can explain it to me?\n\n```\ncontract Token {\n uint256 public totalSupply;\n function balanceOf(address _owner) constant returns (uint256 balance);\n function transfer(address _to, uint256 value) returns (bool success);\n function transferFrom(address _from, address _to, uint256 value) returns (bool success);\n function approve(address _spender, uint256 _value) returns (bool success);\n function allowance(address _owner, address _spender) constant returns (uint256 remaining);\n event Transfer(address indexed _from, address indexed _to, uint256 _value);\n event Approval(address indexed _owner, address indexed _spender, uint256 _value);\n}\n```\n\n========================================\n\nTop Answer:\n`Allowance` means that we can grant approval to another contract or address to be able to transfer our ERC20 tokens. And this requirement is common in distributed applications, such as escrows, games, auctions, etc. Hence, we need a way to approve other addresses to spend our tokens. Let's say you have `tether` contract and you want a DEX(Decentralized Exchange) or any other entity transfer coins from the `tether` contract. So you keep track of which entity how much can transfer from tether contract in a mapping.\n\n```\n// my address is allowing your address for this much token\n mapping(address=>mapping(address=>uint)) public allowance;\n```\n\nIn the ERC20 standard, we have a global variable `allowed` in which we keep the mapping from an \"owner's address\" to an \"approved spender’s\" address and then to the amount of tokens. Calling `approve()` function can add an approval to its desired `_spender` and `_value`. The amount of token is not checked here and it will be checked in transfer().\n\nOnce the approval is granted, the \"approved spender\" can use `transferFrom()` to transfer tokens. `_from` is the owner address and `_to` is the receiver’s address and `_value` is the required number of tokens to be sent. First, we check if the owner actually possesses the required number of tokens.\n\nLet's say you want to deposit some ether to a DEFI platform. Interacting with a DEFI platform is actually interacting with the smart contract of that platform. Before you deposit money, you first `approve` the transaction. You are telling that this contract address can take some money from my account. Then you call the `deposit` function of DEFI smart contract and deposit the money. This how transfer occurs in order:\n\n1- Inside Defi, defi contract has `deposit` to get coin from `tether`\n\n```\nfunction depositTokens(uint _amount) public{\n require(_amount>0,'amount cannot be zero');\n // transfer tether to this contract address for staking\n tether.transferFrom(msg.sender,address(this), _amount);\n // update the state inside Defi, like staked tokens, amount etc\n}\n```\n\n2- Inside `tether` we have `transferFrom`\n\n```\nmapping(address=>mapping(address=>uint)) public allowance;\n\nfunction transferFrom(address _from, address _to, uint256 _value) public returns (bool success){\n // check the allowance\n require(_value The first requirement is checking the allowance. `mapping(address=>mapping(address=>uint)) public allowance`. So actually before calling this, `tether` contract has to update its `allowance` mapping so this `transferFrom` will run smoothly\n\n3- Update the allowance with `approve`:\n\n```\nfunction approve(address _spender, uint _value)public returns (bool success){\n allowance[msg.sender][_spender]=_value;\n // This event must trigger when a successful call is made to the approve function.\n emit Approval(msg.sender,_spender,_value);\n return true;\n }\n```\n\n========================================\n\nCode:\n```text\ncontract Token {\n    uint256 public totalSupply;\n    function balanceOf(address _owner) constant returns (uint256 balance);\n    function transfer(address _to, uint256 value) returns (bool success);\n    function transferFrom(address _from, address _to, uint256 value) returns (bool success);\n    function approve(address _spender, uint256 _value) returns (bool success);\n    function allowance(address _owner, address _spender) constant returns (uint256 remaining);\n    event Transfer(address indexed _from, address indexed _to, uint256 _value);\n    event Approval(address indexed _owner, address indexed _spender, uint256 _value);\n}\n```\n\n```text\nallowance\n```\n\n```text\napprove\n```\n\n```text\n_spender\n```\n\n```text\napprove(address(B), 100, {\"from\": address(A)})\n```\n\n```text\nallowance(address(A), address(B))\n```\n\n```text\ntransferFrom(address(A), address(B), 100, {\"from\": address(B)})\n```\n\n```text\n// my address is allowing your address for this much token\n mapping(address=>mapping(address=>uint)) public allowance;\n```\n\n```text\nfunction depositTokens(uint _amount) public{\n  require(_amount>0,'amount cannot be zero');\n  // transfer tether to this contract address for staking\n  tether.transferFrom(msg.sender,address(this), _amount);\n // update the state inside Defi, like staked tokens, amount etc\n}\n```\n\n```text\nmapping(address=>mapping(address=>uint)) public allowance;\n\nfunction transferFrom(address _from, address _to, uint256 _value) public returns (bool success){\n        // check the allowance\n        require(_value <=allowance[_from][msg.sender]);\n        balanceOf[_to]+=_value;\n        balanceOf[_from]-=_value;\n        allowance[_from][msg.sender]-=_value;\n        emit Transfer(_from,_to,_value);\n        return true;\n    }\n```\n\n```text\nfunction approve(address _spender, uint _value)public returns (bool success){\n        allowance[msg.sender][_spender]=_value;\n        // This event must trigger when a successful call is made to the approve function.\n        emit Approval(msg.sender,_spender,_value);\n        return true;\n    }\n```\n\n```text\nAllowance\n```\n\n```text\ntether\n```\n\n```text\ntether\n```\n\n```text\nallowed\n```\n\n```text\napprove()\n```\n\n```text\n_spender\n```\n\n```text\n_value\n```\n\n```text\ntransferFrom()\n```\n\n```text\n_from\n```\n\n```text\n_to\n```\n\n```text\n_value\n```\n\n```text\napprove\n```\n\n```text\ndeposit\n```\n\n```text\ndeposit\n```\n\n```text\ntether\n```\n\n```text\ntether\n```\n\n```text\ntransferFrom\n```\n\n```text\nmapping(address=>mapping(address=>uint)) public allowance\n```\n\n```text\ntether\n```\n\n```text\nallowance\n```\n\n```text\ntransferFrom\n```\n\n```text\napprove\n```\n\n========================================\n\nComments:\n- In transferFrom, can B send this money to someone else like C?\n- Yes, B can send token to C in that case. @EresDev","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":33,"totalLines":241,"estimatedTokens":1668}}77{"id":"stack-42738640","source":"stackoverflow","questionId":42738640,"title":"Division in Ethereum Solidity","tags":["ethereum","solidity"],"text":"Title: Division in Ethereum Solidity\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI am creating a contract that issues tokens. I would like an account that holds tokens to be able to check what percentage they own out of all the tokens issued. I know that Ethereum has not implemented floating point numbers yet. What should I do?\n\n========================================\n\nTop Answer:\nYou could use `binary point` or `fixed number representation`. Introduction to Fixed Point Number Representation For example\n\n```\n11010.1 in base2 = 1 * 24 + 1 * 23 + 0 * 22 + 1 * 21 + 0* 20 + 1 * 2-1 = 26.5\n```\n\nPercentage is calculated by\n\n```\n// x is the percentage\n a/b = x/100 => x= (100*a)/b\n```\n\nto calculate the division of big numbers, you can use FixidityLib.sol library.\n\n```\nfunction divide(Fixidity storage fixidity, int256 a, int256 b) public view returns (int256) {\n if(b == fixidity.fixed_1) return a;\n assert(b != 0);\n return multiply(fixidity, a, reciprocal(fixidity, b));\n}\n```\n\nThere are too many mathematical libraries or contracts and each implements divide operation differently:\n\nFloatMath.sol\n\nDSMath Contract\n\nabdk-libraries-solidity\n\nopenzeppelin-contracts\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.6;\n\ncontract Divide {\n\n  function percent(uint numerator, uint denominator, uint precision) public \n\n  constant returns(uint quotient) {\n\n         // caution, check safe-to-multiply here\n        uint _numerator  = numerator * 10 ** (precision+1);\n        // with rounding of last digit\n        uint _quotient =  ((_numerator / denominator) + 5) / 10;\n        return ( _quotient);\n  }\n\n}\n```\n\n```text\n11010.1 in base2 = 1 * 24 + 1 * 23 + 0 * 22 + 1 * 21 + 0* 20 + 1 * 2-1 = 26.5\n```\n\n```text\n// x is the percentage\n  a/b = x/100 => x= (100*a)/b\n```\n\n```text\nfunction divide(Fixidity storage fixidity, int256 a, int256 b) public view returns (int256) {\n    if(b == fixidity.fixed_1) return a;\n    assert(b != 0);\n    return multiply(fixidity, a, reciprocal(fixidity, b));\n}\n```\n\n```text\nbinary point\n```\n\n```text\nfixed number representation\n```\n\n========================================\n\nComments:\n- This would be needed for a calculation of how much the contract is able to pay out for the given token holder. For example if a token holder owns 20 tokens and there are 100 total tokens. The contract needs to be able to decide that 20 tokens is worth 20% of the total ether in the contract. The total ether may be 5 eth for example. Could I divide Wei? How would this work?\n- Fair enough, and No. The Wei is the smallest unit so you have to decide what to do with remainders. If you're going for full precision, then track fractional Wei using higher precision user balances as state variables ... occasional settlement when cumulative balance is large enough. Remember, it will cost gas to actually move a single unit of Wei so think about the efficiency of moving small amounts around.\n- Ok, so how would I multiply that percentage? I would first need to turn it into a decimal (not sure how to do that), than I would need to multiply it by the [this].balance? By the way thanks for the help.\n- Well, if you pass 20,100,3 then you get 200 - let's call it \"portion\"), meaning 200 parts per thousand, or 20.0%. So, you can have as much precision as you need. Then, you could say amountToDivide * portion / 1000. 1,000 is 3(the original precision)**10. I corrected an oversight in the function so it correctly rounds up. BTW, \"convert to decimal\" is a shorthand I've heard in financial circles ... means multiply by 100. Nothing special. Also, comment about \"safe-to\" is in case you are dealing with large numbers that could overflow and do nasty things.\n- So in what conditions would it not be safe to multiply?\n- Overflow. If the number is too large for uint256 it won't throw ... it'll just toss the high order bits and return a small number. Why you see example like if(a+b<a) throw; in the docs. Need to think that through for this case. Something like if(numerator*10*(precision+1) < numerator) throw; ... I would think it through a little more before I would say I'm sure about that check. Hopefully communicates the idea.\n- Sorry for the silly question, but what is \"5\" from Rob's quotient equation?\n- It handles rounding up because otherwise, Solidity truncates.","metadata":{"transformedAt":"2026-08-18T18:33:36.117Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":101,"estimatedTokens":1083}}78{"id":"stack-42716858","source":"stackoverflow","questionId":42716858,"title":"String array in solidity","tags":["ethereum","solidity","eris-blockchain"],"text":"Title: String array in solidity\nTags: ethereum, solidity, eris-blockchain\nSource: Stack Overflow\n\nQuestion:\nI came across quite a common problem that it seems I can't solve elegantly and efficiently in solidity.\n\nI've to pass an arbitrary long array of arbitrary long strings to a solidity contract.\n\nIn my mind it should be something like\n\n```\nfunction setStrings(string [] row)\n```\n\nbut it seems it can't be done.\n\nHow can I solve this problem?\n\n========================================\n\nTop Answer:\n### December 2021 Update\n\nAs of Solidity 0.8.0, `ABIEncoderV2`, which provides native support for dynamic string arrays, is used by default.\n\n```\npragma solidity ^0.8.0;\n\ncontract Test {\n string[] public row;\n\n function getRow() public view returns (string[] memory) {\n return row;\n }\n\n function pushToRow(string memory newValue) public {\n row.push(newValue);\n }\n}\n```\n\n========================================\n\nCode:\n```text\nfunction setStrings(string [] row)\n```\n\n```text\nstring\n```\n\n```text\nbyte[]\n```\n\n```text\nstring[]\n```\n\n```text\nbyte[][]\n```\n\n```text\nfunction setStrings(byte[MAX_LENGTH][] row) {...}\n```\n\n```text\nint[5] list_of_students;\nlist_of_students = [\"Faisal\",\"Asad\",\"Naeem\"];\n```\n\n```text\nint[] list_of_students;\nlist_of_students.push(\"Faisal\");\nlist_of_students.push(\"Asad\");\nlist_of_students.push(\"Smith\");\n```\n\n```text\npush\n```\n\n```text\npop\n```\n\n```text\npragma experimental ABIEncoderV2;\n```\n\n```text\nstring[] memory myStrings;\n```\n\n```text\npragma solidity ^0.8.0;\n\ncontract Test {\n    string[] public row;\n\n    function getRow() public view returns (string[] memory) {\n        return row;\n    }\n\n    function pushToRow(string memory newValue) public {\n        row.push(newValue);\n    }\n}\n```\n\n```text\nABIEncoderV2\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.1;\n\ncontract HelloWorld {\n    string[] strings;\n\n    // push one string to array\n    function pushToStrings(string memory _data) public{\n        strings.push(_data);\n    }\n    \n    //get all the strings in array form\n    function GetAllStrings() view public returns(string[] memory){\n        return strings;\n    }\n\n    //get nth string of strings array\n    function GetNthStrings(uint x) view public returns(string memory){\n        return strings[x];\n    }\n\n    //push array of strings in strings\n    function pushStringsArray(string[] memory someData) public{\n        for (uint i=0; i < someData.length; i++) {\n           strings.push(someData[i]);\n        }\n    }\n    \n    //change whole strings, take array of strings as input\n    function changeWholeString(string[] memory someData) public{\n       strings=someData;\n\n    }\n}\n```\n\n```text\npragma solidity ^0.8.4;\n\ncontract Array {\n  string[] private fruits = [\"banana\", \"apple\", \"avocado\", \"pineapple\", \"grapes\"];\n\n  function push(string memory item) public {\n    fruits.push(item);\n  }\n\n  function get(uint256 index) public view returns (string memory) {\n    return fruits[index];\n  }\n\n  function remove(uint256 index) public returns (bool) {\n    if (index >= 0 && index < fruits.length) {\n      fruits[index] = fruits[fruits.length - 1];\n      fruits.pop();\n      return true;\n    }\n    revert(\"index out of bounds\");\n  }\n\n  function getAll() public view returns (string[] memory) {\n    return fruits;\n  }\n}\n```\n\n```text\npush\n```\n\n```text\nget\n```\n\n```text\ngetAll\n```\n\n```text\nremove\n```\n\n========================================\n\nComments:\n- I just added an updated answer as of December 2021\n- And then how the conversion would be?","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":204,"estimatedTokens":873}}79{"id":"stack-37606839","source":"stackoverflow","questionId":37606839,"title":"How to return mapping list in Solidity? (Ethereum contract)","tags":["blockchain","ethereum","solidity","smartcontracts"],"text":"Title: How to return mapping list in Solidity? (Ethereum contract)\nTags: blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI want to make a simple smart contract that has a list, can set item, and can get the list.\n\nCode in solidity:\n\n```\ncontract lister {\n mapping(int => string) list;\n int id = 0;\n \n function getList() returns ( /*HERE*/ ) {\n return list;\n }\n\n function setItemToList(string str) {\n list[id] = str;\n id++;\n }\n}\n```\n\nI want to make getList() return the list, but the return type is not compatible.\nHow can I do that?\n\n========================================\n\nTop Answer:\nWith mappings, keys are not stored and the values can not be iterated upon, so they are really only good for single-value lookups. In the example you provide, it may be a better choice to use an array.\n\nOn the other hand, if you use an array and need to do a search on it (loop through all items), you need to be careful because if there are too many items in your array, it could end up costing a considerable amount of gas to call the function.\n\n========================================\n\nCode:\n```text\ncontract lister {\n    mapping(int => string) list;\n    int id = 0;\n    \n    function getList() returns ( /*HERE*/ ) {\n        return list;\n    }\n\n    function setItemToList(string str) {\n        list[id] = str;\n        id++;\n    }\n}\n```\n\n```text\nmapping(int => string) public list;\n```\n\n```text\naddress[] public addresses;\n```\n\n```text\nfunction getAddressCount() public view returns(uint){\n        return addresses.length;\n    }\n```\n\n```text\nfunction getAddressByIndex(uint index) public view returns(address){\n\n   return addresses[index]\n}\n```\n\n```text\nlet addresses,addressCount;\ntry {\n     addressesCount = await ContractName.methods.getCampaignCounts().call();\n       \n    addresses = await Promise.all(\n      Array(parseInt(addressesCount))\n        .fill()\n        .map((element, index) => {\n          return ContractName.methods.getAddressByIndex(index).call();\n        })\n    );\n    \n  } catch (e) {\n    console.log(\"error in pulling array list\", e);\n  }\n```\n\n```text\nweb3\n```\n\n========================================\n\nComments:\n- I believe the answer to this question is yes. In fact you can see which sites do this since they will be accessible without metamask installed.\n- I am still looking for an answer to this, and so far, it seems the only way to get access to the entire list without executing a for loop/rate limited, is to process transaction/event history and store the data myself... which means I need to keep the data in sync at all times between my own storage and the blockchain...\n- you should not do this. This makes map available to any one. So they can access the map without knowing key values.\n- @e.k It looks like OP wants to make the map available to anyone. Is there any other reason this is bad practice, or just bad if you want to keep it private?\n- does this make anyone able to edit it ?","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":105,"estimatedTokens":738}}80{"id":"stack-32157648","source":"stackoverflow","questionId":32157648,"title":"String concatenation in solidity?","tags":["string","blockchain","ethereum","solidity","smartcontracts"],"text":"Title: String concatenation in solidity?\nTags: string, blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nHow do I concatenate strings in solidity?\n\n```\nvar str = 'asdf'\nvar b = str + 'sdf'\n```\n\nseems not to work.\n\nI looked up the documentation and there is not much mentioned about string concatenation.\n\nBut it is stated that it works with the dot ('.')?\n\n```\n\"[...] a mapping key k is located at sha3(k . p) where . is concatenation.\"\n```\n\nDidn't work out for me too. :/\n\n========================================\n\nTop Answer:\nYou can't concatenate strings. You also can not check equals (`str0 == str1`) yet. The string type was just recently added back to the language so it will probably take a while until all of this works. What you can do (which they recently added) is to use strings as keys for mappings.\n\nThe concatenation you're pointing to is how storage addresses are computed based on field types and such, but that's handled by the compiler.\n\n========================================\n\nCode:\n```text\nvar str = 'asdf'\nvar b = str + 'sdf'\n```\n\n```text\n\"[...] a mapping key k is located at sha3(k . p) where . is concatenation.\"\n```\n\n```text\nimport \"github.com/Arachnid/solidity-stringutils/strings.sol\";\n\ncontract C {\n  using strings for *;\n  string public s;\n\n  function foo(string s1, string s2) {\n    s = s1.toSlice().concat(s2.toSlice());\n  }\n}\n```\n\n```text\nsha256\n```\n\n```text\nripemd160\n```\n\n```text\nsha3\n```\n\n```text\nstr0 == str1\n```\n\n```text\nsha256\n```\n\n```text\nripemd160\n```\n\n```text\nsha3\n```\n\n```text\npragma solidity ^0.4.19;\n\nlibrary Strings {\n\n    function concat(string _base, string _value) internal returns (string) {\n        bytes memory _baseBytes = bytes(_base);\n        bytes memory _valueBytes = bytes(_value);\n\n        string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length);\n        bytes memory _newValue = bytes(_tmpValue);\n\n        uint i;\n        uint j;\n\n        for(i=0; i<_baseBytes.length; i++) {\n            _newValue[j++] = _baseBytes[i];\n        }\n\n        for(i=0; i<_valueBytes.length; i++) {\n            _newValue[j++] = _valueBytes[i];\n        }\n\n        return string(_newValue);\n    }\n\n}\n\ncontract TestString {\n\n    using Strings for string;\n\n    function testConcat(string _base) returns (string) {\n        return _base.concat(\"_Peter\");\n    }\n}\n```\n\n```text\nfunction concat(string _a, string _b) constant returns (string){\n    bytes memory bytes_a = bytes(_a);\n    bytes memory bytes_b = bytes(_b);\n    string memory length_ab = new string(bytes_a.length + bytes_b.length);\n    bytes memory bytes_c = bytes(length_ab);\n    uint k = 0;\n    for (uint i = 0; i < bytes_a.length; i++) bytes_c[k++] = bytes_a[i];\n    for (i = 0; i < bytes_b.length; i++) bytes_c[k++] = bytes_b[i];\n    return string(bytes_c);\n}\n```\n\n```text\nstring.concat(s1, s2)\n```\n\n```text\nbytes memory b;\n\nb = abi.encodePacked(\"hello\");\nb = abi.encodePacked(b, \" world\");\n\nstring memory s = string(b);\n// s == \"hello world\"\n```\n\n```text\nabi.encodePacked\n```\n\n```text\nfunction cancat(string memory a, string memory b) public view returns(string memory){\n        return(string(abi.encodePacked(a,\"/\",b)));\n    }\n```\n\n```text\npragma solidity 0.5.0;\npragma experimental ABIEncoderV2;\n\n\ncontract StringUtils {\n\n    function conc( string memory tex) public payable returns(string \n                   memory result){\n        string memory _result = string(abi.encodePacked('-->', \": \", tex));\n        return _result;\n    }\n\n}\n```\n\n```text\nreturn string(abi.encodePacked(str, b));\n```\n\n```text\nabi.encodePacked(str,b)\n```\n\n```text\nstring(abi.encodePacked(str, b))\n```\n\n```text\n//SPDX-License-Identifier: GPL-3.0\n \npragma solidity >=0.7.0 < 0.9.0;\n\ncontract test {\n    function appendStrings(string memory string1, string memory string2) public pure returns(string memory) {\n        return string(abi.encodePacked(string1, string2));\n    }\n}\n```\n\n```text\n// SPDX-License-Identifier: GPL-3.0\n\n    pragma solidity >=0.5.0 <0.9.0;\n\n\n   contract AX{\n      string public s1 = \"aaa\";\n      string public s2 = \"bbb\";\n      string public new_str;\n \n      function concatenate() public {\n         new_str = string(abi.encodePacked(s1, s2));\n       } \n    }\n```\n\n```text\n// concat strgin\nstring memory result = string(abi. encodePacked(\"Hello\", \"World\"));\n\n\n// check qual\nif (keccak256(abi.encodePacked(\"banana\")) == keccak256(abi.encodePacked(\"banana\"))) {\n  // your logic here\n}\n```\n\n```text\nconcat\n```\n\n```text\nequal\n```\n\n```text\n//SPDX-License-Identifier: GPT-3\npragma solidity >=0.8.4;\n\nlibrary Strings {\n    \n    function concat(string memory a, string memory b) internal pure returns (string memory) {\n        return string(bytes.concat(bytes(a),bytes(b)));\n    }\n}\n```\n\n```text\ncontract Implementation {\n    using Strings for string;\n\n    string a = \"first\";\n    string b = \"second\";\n    string public c;\n    \n    constructor() {\n        c = a.concat(b); // \"firstsecond\"\n    }\n}\n```\n\n```text\n// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.0 <0.9.0;\n\ncontract String{   \n    function concatenate(string memory firstName,string memory lastName) public pure returns (string memory fullName)  {\n        bytes memory full=string.concat(bytes(firstName),bytes(lastName));\n        return string(full);\n    }\n}\n```\n\n========================================\n\nComments:\n- As a general advise, usually (not always) you can design your programs so that you do not need to do string concatenation, or any string operations in Solidity. Smart contracts and blockchain virtual machines are not intended for string operations, so with a smarter architecture you can avoid it.\n- This answer is not up to date anymore. See the other ones.\n- I have deployed smart contract with s string, how to read the string?\n- @TomaszWaszczyk If the string is `public` use its accessor, otherwise the contract needs a function that returns the string. If you are \"calling\" the smart contract function, this might help ethereum.stackexchange.com/questions/765/&hellip; because there are different ways of \"calling\" a smart contract.\n- the second for loop contains an error, should be `_newValue[j++] = _valueBytes[i];`\n- What is `\"&#47;\"` for?\n- Generally, there is no reason to work with strings in Solidity. Usually, it is a sign of bad architectural design or cluelessness about blockchain technology.","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":283,"estimatedTokens":1586}}81{"id":"stack-69593720","source":"stackoverflow","questionId":69593720,"title":"How to initialize a mapping in Solidity, what is the best practice?","tags":["solidity","smartcontracts"],"text":"Title: How to initialize a mapping in Solidity, what is the best practice?\nTags: solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI would like to initialise my mapping in the declaration line in a smart contract. I was wondering what is the best practice? I have tried the following but Remix is giving me errors:\n\n`mapping(address _addr) public view myMap = [ addr-1 : true, addr-2 : false, addr-3 : true ];`\n\n========================================\n\nCode:\n```text\nmapping(address _addr) public view myMap = [ addr-1 : true, addr-2 : false, addr-3 : true ];\n```\n\n```text\npragma solidity ^0.8;\n\ncontract MyContract {\n    mapping(address => bool) public myMap;\n    \n    constructor() {\n        myMap[address(0x123)] = true;\n        myMap[address(0x456)] = false;\n        myMap[address(0x789)] = true;\n    }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":29,"estimatedTokens":206}}82{"id":"stack-42230532","source":"stackoverflow","questionId":42230532,"title":"Getting the address of a contract deployed by another contract","tags":["javascript","ethereum","solidity"],"text":"Title: Getting the address of a contract deployed by another contract\nTags: javascript, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI am trying to deploy a contract from another factory contract and then return the address of the newly created contract. The address it returns however is the transaction hash not the contract address. I believe this is because the contract is not yet mined when the address is returned. When I deploy a contract using the web3 deploy it seems to wait until the contract is deployed before outputting the address.\n\nThe factory contract:\n\n```\ncontract Factory {\nmapping(uint256 => Contract) deployedContracts;\nuint256 numContracts;\nfunction Factory(){\n numContracts = 0;\n}\n\nfunction createContract (uint32 name) returns (address){\n deployedContracts[numContracts] = new Contract(name);\n numContracts++;\n return deployedContracts[numContracts];\n}}\n```\n\nThis is how I am calling the createContract function.\n\n```\nfactory.createContract(2,function(err, res){\n if (err){\n console.log(err)\n }else{\n console.log(res)\n }\n });\n```\n\n========================================\n\nTop Answer:\nWe ran across this problem today, and we're solving it as follows:\n\nIn the creation of the new contract raise an event.\n\nThen once the block has been mined use the transaction hash and call `web3.eth.getTransaction`:\nhttp://web3js.readthedocs.io/en/1.0/web3-eth.html#gettransaction\n\nThen look at the `logs` object and you should find the event called by your newly created contract with its address.\n\nNote: this assumes you're able to update the Solidity code for the contract being created, or that it already calls such an event upon creation.\n\n========================================\n\nCode:\n```text\ncontract Factory {\nmapping(uint256 => Contract) deployedContracts;\nuint256 numContracts;\nfunction Factory(){\n    numContracts = 0;\n}\n\nfunction createContract (uint32 name) returns (address){\n    deployedContracts[numContracts] = new Contract(name);\n    numContracts++;\n    return deployedContracts[numContracts];\n}}\n```\n\n```text\nfactory.createContract(2,function(err, res){\n        if (err){\n            console.log(err)\n        }else{\n        console.log(res)\n        }\n    });\n```\n\n```text\ncontract Object {\n\n    string name;\n    function Object(String _name) {\n        name = _name\n    }\n}\n\ncontract ObjectFactory {\n    function createObject(string name) returns (address objectAddress) {\n        return address(new Object(name));\n    }\n}\n```\n\n```text\ncontract ObjectFactory {\n    Object public theObj;\n\n    function createObject(string name) returns (address objectAddress) {\n        theObj = address(new Object(name));\n        return theObj;\n    }\n}\n```\n\n```text\nvar address = web3.eth.contract(objectFactoryAbi)\n    .at(contractFactoryAddress)\n    .createObject.call(\"object\");\n```\n\n```text\nvar txHash = web3.eth.contract(objectFactoryAbi)\n    .at(contractFactoryAddress)\n    .createObject(\"object\", { gas: price, from: accountAddress });\n```\n\n```text\nvar ethJsUtil = require('ethereumjs-util');\nvar futureAddress = ethJsUtil.bufferToHex(ethJsUtil.generateAddress(\n      contractFactoryAddress,\n      await web3.eth.getTransactionCount(contractFactoryAddress)));\n```\n\n```text\nCall\n```\n\n```text\ncall\n```\n\n```text\nweb3.eth.getTransaction\n```\n\n```text\nlogs\n```\n\n========================================\n\nComments:\n- Where is the address var used in #2 ?\n- The `address` var in #2 is the new contract address, so you can do what ever you want to do with it. Probably save it somewhere.\n- Using approach #1 I'm getting back an address that does not represent the child object. What is possibly causing this error?","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":146,"estimatedTokens":909}}83{"id":"stack-35743893","source":"stackoverflow","questionId":35743893,"title":"How do I initialize an array in a struct","tags":["arrays","struct","ethereum","solidity"],"text":"Title: How do I initialize an array in a struct\nTags: arrays, struct, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI have a struct Purchase in which I'm putting an array of payments. However, when I try to add the new payments array in my `makePayment` method I get an error back from the solidity compiler: \"Internal compiler error: Copying of type struct Payment memory[] memory to storage not yet supported.\" When I change the mayment array to be `storage` or `memory`, I get the same error. I've added the relevant code below.\n\nIs it possible to do what I'm trying to do in solidity? I don't see anything explicitly saying it's not possible in the documentation but I also don't see any examples doing what I'm trying to do. :|\n\n```\nstruct Payment {\n address maker;\n uint amount;\n }\n\n struct Purchase {\n uint product_id;\n bool complete;\n Payment[] payments;\n }\n Purchase[] purchases;\n\n function makePayment(uint product_id, uint amt, uint purchase_id) returns (bool) {\n\n Payment[] payments;\n payments[0] = Payment(address, amt);\n purchases[purchase_id] = Purchase(product_id, false, payments);\n }\n```\n\n========================================\n\nTop Answer:\nI found this as best solution.\n\n```\nevent OnCreateRoom(address indexed _from, uint256 _value);\n\n struct Room {\n address[] players; \n uint256 whosTurnId;\n uint256 roomState;\n } \n\n Room[] rooms;\n\n function createRoom() public{\n address[] adr;\n adr.push(msg.sender);\n Room memory room = Room(adr, 0, 0); \n rooms.push(room);\n OnCreateRoom(msg.sender, 0);\n }\n```\n\n========================================\n\nCode:\n```text\nstruct Payment {\n    address maker;\n    uint amount;\n  }\n\n  struct Purchase {\n    uint product_id;\n    bool complete;\n    Payment[] payments;\n  }\n  Purchase[] purchases;\n\n  function makePayment(uint product_id, uint amt, uint purchase_id) returns (bool) {\n\n      Payment[] payments;\n      payments[0] = Payment(address, amt);\n      purchases[purchase_id] = Purchase(product_id, false, payments);\n  }\n```\n\n```text\nmakePayment\n```\n\n```text\nstorage\n```\n\n```text\nmemory\n```\n\n```text\nPayment[] payments;\n  payments[payments.length++] = Payment(address, amt);\n```\n\n```text\nPayment[] payments;\npayments.push(Payment(address, amt));\n```\n\n```text\nuint purchase_id = purchases.length++;\npurchases[purchase_id].product_id = product_id;\npurchases[purchase_id].complete   = false;\npurchases[purchase_id].payments.push(Payment(msg.sender, amt));\n```\n\n```text\nevent OnCreateRoom(address indexed _from, uint256 _value);\n\n   struct Room {\n      address[] players;       \n      uint256 whosTurnId;\n      uint256 roomState;\n   }  \n\n   Room[] rooms;\n\n   function createRoom() public{\n       address[] adr;\n       adr.push(msg.sender);\n       Room memory room = Room(adr, 0, 0);   \n       rooms.push(room);\n       OnCreateRoom(msg.sender, 0);\n   }\n```\n\n========================================\n\nComments:\n- It's possible that this was happening because I wasn't using enough gas for the transaction.\n- Did you see there is an Ethereum SE beta?\n- Does `payments` need the `memory` keyword in this case?\n- In solidity 8 this solution won't work as length is read-only, but you can simply do `Purchase p = purchases.push()` instead, and instead of having index, you can do `p.product_id = product_id` and so on\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":136,"estimatedTokens":887}}84{"id":"stack-67856902","source":"stackoverflow","questionId":67856902,"title":"How to Logout of MetaMask account Using web3.js","tags":["reactjs","ethereum","solidity","web3js","metamask"],"text":"Title: How to Logout of MetaMask account Using web3.js\nTags: reactjs, ethereum, solidity, web3js, metamask\nSource: Stack Overflow\n\nQuestion:\nI am using MetaMask for sending transactions to contract in my DApp. I need help in **How to Disconnect MetaMask account from my DApp** when the user clicks on *logout button*.\n\nFront-end: ReactJS\n\nBack-end: Web3js, Solidity (Ethereum)\n\n========================================\n\nTop Answer:\nThe user can disconnect MetaMask account using the account disconnect button within the MetaMask itself. Also any page refresh or reload automatically disconnects MetaMask.\n\n========================================\n\nCode:\n```text\nconst {ethereum} = window;\nconst accounts = await ethereum.request({method: 'eth_accounts'});\nif (accounts && accounts.length > 0) {\n    console.log(\"user is connected\");\n} else {\n    console.log(\"user not connected\");\n}\n```\n\n```js\nwindow.ethereum.on('accountsChanged', async () => {\n    // Do something\n});\n```\n\n```js\n// Runs on page load\ninitialise();\n\n// Runs whenever the user changes account state\nwindow.ethereum.on('accountsChanged', async () => {\n    initialise();\n});\n```\n\n```js\nlet connected = false;\nlet installed = false;\n\nfunction isMetaMaskInstalled() {\n    return Boolean(window.ethereum && window.ethereum.isMetaMask);\n}\n\nasync function isMetaMaskConnected() {\n    const {ethereum} = window;\n    const accounts = await ethereum.request({method: 'eth_accounts'});\n    return accounts && accounts.length > 0;\n}\n\nasync function initialise() {\n    connected = await isMetaMaskConnected();\n    installed = isMetaMaskInstalled();\n}\n\ninitialise();\n\nwindow.ethereum.on('accountsChanged', async () => {\n    initialise();\n});\n```\n\n```text\ninstalled\n```\n\n```text\nconnected\n```\n\n```text\nawait web3Modal.clearCachedProvider()\n```\n\n```text\nimport { Mainnet,ChainId} from \"@usedapp/core\";\n\nfunction MyApp({ Component, pageProps }: AppProps) {\n  return (\n    <DAppProvider\n      config={{\n        supportedChains: [ChainId.Kovan, ChainId.Rinkeby],\n      }}\n    >\n      <Component {...pageProps} />\n    </DAppProvider>\n  );\n}\n```\n\n```text\nimport { useEthers } from \"@usedapp/core\";\n\nexport const Header = () => {\n  \n  const { account, activateBrowserWallet, deactivate } = useEthers();\n  const isConnected = account !== undefined;\n  return (\n    <div >\n      {isConnected ? (\n        <Button  onClick={deactivate}>\n          Disconnect\n        </Button>\n      ) : (\n        <Button onClick={() => activateBrowserWallet()}>\n          Connect\n        </Button>\n      )}\n    </div> );};\n```\n\n```text\nimport {\n  useAccount,\n  useConnect,\n  useDisconnect,\n  useNetwork,\n  useSignMessage\n} from \"wagmi\";\n```\n\n```text\nconst { disconnect } = useDisconnect();\n```\n\n```text\nconst disconnectWallet = async () => {\n    disconnect();\n    refreshState();\n  };\n```\n\n```text\n<HStack>\n          {!activeConnector ? (\n            <Button onClick={connectWallet}>Connect Wallet</Button>\n          ) : (\n            <Button onClick={disconnectWallet}>Disconnect</Button>\n          )}\n </HStack>\n```\n\n```js\n//utils/cookies.ts\nfunction delete_cookie(name: string, path: string, domain: string) {\n  if (get_cookie(name)) {\n    document.cookie =\n      name +\n      \"=\" +\n      (path ? \";path=\" + path : \"\") +\n      (domain ? \";domain=\" + domain : \"\") +\n      \";expires=Thu, 01 Jan 1970 00:00:01 GMT\";\n  }\n}\n\nfunction get_cookie(name: string) {\n  return document.cookie.split(\";\").some((c) => {\n    return c.trim().startsWith(name + \"=\");\n  });\n}\n\nexport function deleteWalletCookies() {\n  const path = \"/\";\n  const domain = window.location.hostname;\n\n  [\n    \"wagmi.recentConnectorId\",\n    \"wagmi.store\",\n    \"wagmi.walletConnect.requestedChains\",\n  ].forEach((name: string) => {\n    delete_cookie(name, path, domain);\n  });\n}\n```\n\n```js\n//hooks/useAuth.ts\nexport function useAuth() {\n  const {\n    isConnected: isWalletConnected,\n    signMessage,\n    disconnect: disconnectWallet, // <- this is wagmi disconnector\n    connect: connectWallet,\n  } = useWallet();\n\n  const disconnect = () => {\n    disconnectWallet();\n    deleteWalletCookies();\n    localStorage.removeItem(\"accessToken\");\n    window.location.reload();\n  };\n\n  return {\n    isConnected,\n    userCanPlay,\n    disconnect,\n    connect,\n    siwe,\n  };\n}\n```\n\n========================================\n\nComments:\n- yeah, I know that. But I want to implement a button on my front-end. when the user clicks on that button. It should Logout to MetaMask. For reference, see PanCakeSwap logout functionality.\n- They are not actually disconnecting metamask. You can see that in metamask it still displays `connected` even after clicking logout. They may be just the variable which they have assgined the address\n- This is the correct answer. The connect/disconnect functionality is entirely in the hands of the user due to security and privacy concerns. Resetting the accounts array programmatically does not disconnect the wallet.\n- The essence of the contents of eip-1193 is, you can only make a wallet connection via web3 programmatically and detect changes in events on the wallet user's side such as changing networks, changing wallets, but you can't programmatically disconnect wallets on web3. In the case of pancake connecting wallet using metamask, it only uses the variable that holds the user's wallet address, when the user clicks on the disconnect menu it just deletes the contents of the variable created by pancake, and it doesn't actually disconnect the user's wallet.\n- Hello. That's work but that's not really disconnect Metamsk from the site. And that's show me an error : Uncaught (in promise) TypeError: ethereum.clearCachedProvider is not a function Personnaly, I prefer reset to empty the account array. But that don't disconnect in metamask extension too...\n- OP never stated that they were using Web3Modal, besides this function clears cache of chosen provider in Web3Modal, so it's not relevant at all.\n- This is the correct answer in that there is currently no api to ask metamask to dissociate an account that is connected.","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":221,"estimatedTokens":1510}}85{"id":"stack-57370148","source":"stackoverflow","questionId":57370148,"title":"Is there any way to get the address of the library for a specific contract address?","tags":["ethereum","solidity","web3js","etherscan"],"text":"Title: Is there any way to get the address of the library for a specific contract address?\nTags: ethereum, solidity, web3js, etherscan\nSource: Stack Overflow\n\nQuestion:\nWe have a smart contract factory which deploys smart contract instances. These smart contract instances use SafeMath.\n\nWe want verify code for these instance on Etherscan. But, Etherscan requires SafeMath library address to verify contract code.\n\nHow can I get the SafeMath library address for each instance?","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":10,"estimatedTokens":120}}86{"id":"stack-43106483","source":"stackoverflow","questionId":43106483,"title":"Calling external contract in solidity dynamically","tags":["blockchain","ethereum","solidity"],"text":"Title: Calling external contract in solidity dynamically\nTags: blockchain, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI am trying to make a contract have a function that is capable of calling functions of another contract. The key part of my goal is that the contract should not be able to be deployed without any import statements and will not know the name of the contract by default. In other words the user of this contract would input the called contracts data (i.e. address, name) as parameters. What is the best way to accomplish this?\n\n========================================\n\nTop Answer:\nYou can do this by using an interface, as suggested by Rob Hitchens, or you could define the interface dynamically and execute a method by using .call, .callcode, .delegatecall.\n\nHere's an example:\n\n```\ncontract ContractsCaller {\n\n function execute(address contractAt, uint _i, bytes32 _b) returns (bool) {\n return contractAt.call(bytes4(sha3(\"testMethod(uint256,bytes32)\")), _i, _b);\n }\n}\n\ncontract Test {\n\n uint256 public i;\n bytes32 public b;\n\n function testMethod(uint256 _i, bytes32 _b) {\n i = _i;\n b = _b;\n }\n}\n```\n\nTest can be defined in a separate file. ContractsCaller doesn't need to know anything about Test besides its address and the signature of the method it's calling.\n\nThe signature of the method is the first 4 bytes of the method name and the types of its parameters:\n\n```\nbytes4(sha3(\"testMethod(uint256,bytes32)\"))\n```\n\nMore information about .call, .callcode, .delegatecall.\n\n========================================\n\nCode:\n```text\ncontract WidgetInterface {\n\n   function doSomething() returns(uint) {}\n   function somethingElse() returns(bool isTrue) {}\n\n}\n```\n\n```text\nWidgetInterface w = WidgetInterface(actualContractAddress);\n```\n\n```text\nif(!isAuthorized(actualContractAddress)) throw;\n```\n\n```text\nactualContractAddress\n```\n\n```text\nisAuthorized()\n```\n\n```text\ncontract ContractsCaller {\n\n    function execute(address contractAt, uint _i, bytes32 _b) returns (bool) {\n        return contractAt.call(bytes4(sha3(\"testMethod(uint256,bytes32)\")), _i, _b);\n    }\n}\n\ncontract Test {\n\n    uint256 public i;\n    bytes32 public b;\n\n    function testMethod(uint256 _i, bytes32 _b) {\n        i = _i;\n        b = _b;\n    }\n}\n```\n\n```text\nbytes4(sha3(\"testMethod(uint256,bytes32)\"))\n```\n\n========================================\n\nComments:\n- Dumb question. Once I have the instance, `w`. How do I call it's `doSomething` method? Is it as simple as `w.doSomething();`?\n- This is the correct answer. Although the overloading of the Type is not clear. `IERC721 MyContract;` then `MyContract = IERC721(address);`\n- That's instantiation. MyContract is the ERC721 Interface (type) located at the address.","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":102,"estimatedTokens":681}}87{"id":"stack-50201353","source":"stackoverflow","questionId":50201353,"title":"UnhandledPromiseRejectionWarning: Error: The contract code couldn't be stored, please check your gas limit","tags":["node.js","ethereum","solidity","smartcontracts"],"text":"Title: UnhandledPromiseRejectionWarning: Error: The contract code couldn't be stored, please check your gas limit\nTags: node.js, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI am trying to deploy my simple solidity smart contract onto the Rinkeby Network but I keep getting the error:\n\n UnhandledPromiseRejectionWarning: Error: The contract code couldn't be\n stored, please check your gas limit.\n\nMy solidity code is simple\n\n```\npragma solidity ^0.4.18; \n\ncontract Greetings{ \n string public message; \n\n function Greetings(string initialMessage) public{ \n message = initialMessage;\n } \n\n function setMessage(string newMessage) public {\n message = newMessage;\n } \n}\n```\n\nand my deploy script is:\n\n```\nconst HDWalletProvider = require('truffle-hdwallet-provider'); \nconst Web3 = require('web3');\nconst { interface,bytecode} = require('./compile');\n\nconst provider = new HDWalletProvider( \n 'twelve word mnemonic...', \n 'https://rinkeby.infura.io/GLm6McXWuaih4gqq8nTY' \n);\n\nconst web3 = new Web3(provider);\n\nconst deploy = async () => {\n accounts = await web3.eth.getAccounts(); \n\n console.log('attempting to deploy from account',accounts[0]);\n\n const result = await new web3.eth.Contract(JSON.parse(interface)) \n .deploy({data:bytecode, arguments:['Hello World']}) \n .send({from: accounts[0], gas:'1000000'}); \n\n console.log('Contract deployed to', result.options.address); \n};\n\ndeploy();\n```\n\nFunny thing is, I used to be able to deploy successfully, but when i created a new project and re did the same code, i get this error now. Please help!\n\n========================================\n\nTop Answer:\nThis issue can be solved by adding the '0x' as the prefix of the bytecode:\n\n```\n.deploy({ data: '0x' + bytecode, arguments: ['Hi there!'] })\n```\n\nMore information is at https://ethereum.stackexchange.com/a/47654.\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.18; \n\ncontract Greetings{ \n  string public message; \n\n  function Greetings(string initialMessage) public{ \n    message = initialMessage;\n  }  \n\n  function setMessage(string newMessage) public {\n    message = newMessage;\n  }  \n}\n```\n\n```text\nconst HDWalletProvider = require('truffle-hdwallet-provider'); \nconst Web3 = require('web3');\nconst { interface,bytecode} = require('./compile');\n\nconst provider = new HDWalletProvider(  \n  'twelve word mnemonic...', \n  'https://rinkeby.infura.io/GLm6McXWuaih4gqq8nTY'    \n);\n\nconst web3 = new Web3(provider);\n\nconst deploy = async () => {\n    accounts = await web3.eth.getAccounts(); \n\n    console.log('attempting to deploy from account',accounts[0]);\n\n    const result = await new web3.eth.Contract(JSON.parse(interface)) \n      .deploy({data:bytecode, arguments:['Hello World']})      \n      .send({from: accounts[0], gas:'1000000'});                              \n\n    console.log('Contract deployed to', result.options.address); \n};\n\ndeploy();\n```\n\n```text\nnpm uninstall truffle-hdwallet-provider\nnpm install --save truffle-hdwallet-provider@0.0.3\n```\n\n```text\ndata:'0x0' + bytecode\n```\n\n```text\n.deploy({ data: '0x' + bytecode, arguments: ['Hi there!'] })\n```\n\n========================================\n\nComments:\n- This along with the '0x' adding before the bytecode fixed same issue I had, I was about to give up on that udemy course.\n- This solution makes way more sense! Should be the accepted answer. Thanks for this, I was stuck on it for awhile!\n- This alone did not solve my problem, I had to downgrade Truffle to 0.0.3 to get this to work.","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":135,"estimatedTokens":877}}88{"id":"stack-68163319","source":"stackoverflow","questionId":68163319,"title":"Failing to compile multiple Solidity versions","tags":["compiler-errors","ethereum","solidity","hardhat"],"text":"Title: Failing to compile multiple Solidity versions\nTags: compiler-errors, ethereum, solidity, hardhat\nSource: Stack Overflow\n\nQuestion:\nI'm trying to compile (through Hardhat) a contract that imports several interfaces with different Solidity versions but I'm getting the following error:\n\n```\nError HH606: The project cannot be compiled, see reasons below.\n\nThese files and its dependencies cannot be compiled with your config. This can happen because they have incompatible Solidity pragmas, or don't match any of your configured Solidity compilers.\n\n * contracts/FlashLoaner.sol\n```\n\nFlashloaner.sol:\n\n```\npragma solidity >=0.5.0 Issue\nimport \"hardhat/console.sol\";\n\ncontract FlashLoaner {\n struct MyCustomData {\n address token;\n uint256 repayAmount;\n }\n\n address public logicContract;\n \n function execute(address _weth, address _contract) external view {\n console.log(_weth);\n }\n}\n```\n\nThe problem is with `@aave/protocol-v2/contracts/interfaces/ILendingPool.sol`. If I comment it out, my contract compiles good.\n\nIlendingPool.sol: `pragma solidity 0.6.12;`\n\nIERC20.sol: `pragma solidity ^0.5.0;`\n\nIWETH.sol: `pragma solidity >=0.5.0;`\n\nHardhat.config:\n\n```\nmodule.exports = {\n solidity: {\n compilers: [\n {\n version: \"0.5.7\"\n },\n {\n version: \"0.8.0\"\n },\n {\n version: \"0.6.12\"\n }\n ]\n }\n ...\n```\n\n========================================\n\nTop Answer:\nI had a similar problem.\n\nIn my case, my contracts used pragma solidity version ^0.8.0\n\nTo fix the problem, I added those lines to my hardhat.config.js (Inside the existing module.exports for most cases).\n\n```\nmodule.exports = {\n solidity: \"0.8.0\",\n}\n```\n\nI just deleted the \"^\" before the version.\n\n========================================\n\nCode:\n```text\nError HH606: The project cannot be compiled, see reasons below.\n\nThese files and its dependencies cannot be compiled with your config. This can happen because they have incompatible Solidity pragmas, or don't match any of your configured Solidity compilers.\n\n  * contracts/FlashLoaner.sol\n```\n\n```js\npragma solidity >=0.5.0 <=0.8.0;\n\nimport '@uniswap/v2-periphery/contracts/interfaces/IWETH.sol';\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport '@aave/protocol-v2/contracts/interfaces/ILendingPool.sol'; //---> Issue\nimport \"hardhat/console.sol\";\n\n\ncontract FlashLoaner {\n    struct MyCustomData {\n        address token;\n        uint256 repayAmount;\n    }\n\n    address public logicContract;\n    \n    function execute(address _weth, address _contract) external view {\n        console.log(_weth);\n    }\n}\n```\n\n```js\nmodule.exports = {\n  solidity: {\n    compilers: [\n      {\n        version: \"0.5.7\"\n      },\n      {\n        version: \"0.8.0\"\n      },\n      {\n        version: \"0.6.12\"\n      }\n    ]\n  }\n   ...\n```\n\n```text\n@aave/protocol-v2/contracts/interfaces/ILendingPool.sol\n```\n\n```text\npragma solidity 0.6.12;\n```\n\n```text\npragma solidity ^0.5.0;\n```\n\n```text\npragma solidity >=0.5.0;\n```\n\n```text\npragma solidity ^0.8.0\n```\n\n```text\nmodule.exports = {   solidity: {\n        compilers: [\n          {\n            version: \"0.5.5\",\n          },\n          {\n            version: \"0.6.7\",\n            settings: {},\n          },\n        ],   \n}, \n\n};\n```\n\n```js\nmodule.exports = {\n  solidity: \"0.8.0\",\n}\n```\n\n========================================\n\nComments:\n- Yes this works, shame that the compiler makes us jump through these ridiculous hoops because it thinks a function might not exist at a specific address\n- Hi! How is that different from what I tried on the initial post? (the last part of it)","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":179,"estimatedTokens":882}}89{"id":"stack-45006056","source":"stackoverflow","questionId":45006056,"title":"How to send an ETH address from a webpage to a smart contract?","tags":["php","ethereum","solidity"],"text":"Title: How to send an ETH address from a webpage to a smart contract?\nTags: php, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nWhat's the best way to get an ETH address from a website form submission (php) passed to a smart contract in order that the smart contract can send some new minted Tokens to the ETH address collected in the php form? \n\nThe user submitting the ETH address on the website does not have any ETH so we will have to pay for the Gas for any transactions.\n\nThe user's ETH address submitted on the php form is different to the msg.sender address (us).\n\nHave been considering using PHP with:\nhttps://github.com/digitaldonkey/ethereum-php\n\nBut is there an easier approach? Thank you\n\n========================================\n\nComments:\n- much appreciated. We've decided to adopt the JS route. Reading and learning. Tks again","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":20,"estimatedTokens":212}}90{"id":"stack-49959824","source":"stackoverflow","questionId":49959824,"title":"Call functions of a contract deployed at a specific address from solidity","tags":["ethereum","solidity"],"text":"Title: Call functions of a contract deployed at a specific address from solidity\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI'm dealing with inheritance and external calls of contract from within solidity. I have deployed my data structure and filled it at an address MapAdr\n\nMy code can me schemed as . In my DataStructure.sol I have:\n\n```\ninterface Graph {\nfunction getNeighbours(uint8 id) external view returns (uint8[8]);\nfunction getOrder() external view returns (uint8);\nfunction isNeighbour(uint8 strFrom, uint8 strTo) external view returns \n(bool success);\n\n}\n\ncontract DataStructure is Graph {\n....code....\nuint8 order;\nconstructor (uint8 size) {\norder = size;\n}\n....code...\n}\n```\n\nI deploy this contract and I save the address to MapAdr=0x1234567...\n\nNow I go to my other contract \n\n```\npragma solidity ^0.4.22;\n\nimport \"./DataStructure.sol\";\n\ncontract Data is Graph {\n.....code....\nDataStructure public data;\n\n constructor(address MapAdr) public {\n ....code...\n data = DataStructure(MapAdr);\n ....code...\n }\n.....code....\n}\n```\n\nBut then DataStructure is deployed but it's address is not MapAdr.\n\nThere is a way to have an instance of the deployed contract at that specific MadAdr (so with that exactly data inserted in that datastructure) so I can query it's storage ?\n\nThe idea is to deploy several DataStructure contracts with different data inserted and then referiing to one specific when deploying Data contract.\n\n========================================\n\nCode:\n```text\ninterface Graph {\nfunction getNeighbours(uint8 id) external view returns (uint8[8]);\nfunction getOrder() external view returns (uint8);\nfunction isNeighbour(uint8 strFrom, uint8 strTo) external view returns \n(bool success);\n\n}\n\ncontract DataStructure is Graph {\n....code....\nuint8 order;\nconstructor (uint8 size) {\norder = size;\n}\n....code...\n}\n```\n\n```text\npragma solidity ^0.4.22;\n\nimport \"./DataStructure.sol\";\n\n\ncontract Data is Graph {\n.....code....\nDataStructure public data;\n\n    constructor(address MapAdr) public {\n    ....code...\n    data = DataStructure(MapAdr);\n    ....code...\n    }\n.....code....\n}\n```\n\n```text\ncontract Admin {\n  address private owner;\n\n  function Admin() public { owner = msg.sender; }\n\n  function getOwner() public returns (address) {\n    return owner;\n  }\n\n  function transfer(address to) public {\n    require(msg.sender == owner);\n    owner = to;\n  }\n}\n\ncontract Lottery {\n  string public result;\n\n  Admin public admin = Admin(0x35d803f11e900fb6300946b525f0d08d1ffd4bed);  // Admin contract was deployed under this address\n\n  function setResult(string _result) public {\n    require(msg.sender == admin.getOwner());\n    result = _result;\n  }\n}\n```\n\n```text\nAdmin\n```\n\n```text\n0x35d...\n```\n\n```text\nLottery\n```\n\n```text\nadmin\n```\n\n```text\nadmin.getOwner();\n```\n\n```text\nAdmin\n```\n\n```text\nLottery\n```\n\n```text\nAdmin\n```\n\n```text\nLottery\n```\n\n========================================\n\nComments:\n- Yes it's quite similar. The difference here is that the constructor is without parameters and I don't know why in this way it works. But in my case my constructor got a parameter so calling it as I do should be incorrect since my construct accept uint8 as parameter and not an address.\n- The contract's constructor is executed **just once** when the contract is deployed to the blockchain. So, if you have one `uint` argument, you will need to send it while deploying the contract. That's different from **referencing the contract instance** from other contract. You do so, just be referencing the `address` where the first contract was deployed, and you shouldn't need to send any of the constructor arguments, because the constructor of the first contract won't actually be called again. Makes sense?\n- Anyway, hardcoding the contract `address` in that way is probably not a good idea. Imagine you need to change the `Admin` instance in the future. It's simply not possible because the address is hardcoded in the `Lottery` contract. For these cases it's better to implement a `setAdmin();` method, or even send the address of the `Admin` instance as a parameter to the constructor while creating the `Lottery` instance.\n- Hello and thanks for the answer. In my case hardcoding the address is OK in my case I'm aware of your warnings about. Can you give me more details about what is meaning \"referencing the address where the first contract was deployed\"? How can I do this? That's what I need from what I understand\n- Sure. To get your app \"live\" you will need to deploy contracts to the Ethereum blockchain. While developing you will probably be using a testnet, or a local running Javascript VM. In any of the cases, if you need to reference `contract1` from `contract2`, you will first need to create an instance of `contract1` (`Admin` in this example) by deploying it to the network. That will bring you an Ethereum address (similar to `0x35d...`), were the instance is available. You can now use that address from `contract2` to reference `contract1`.\n- You will basically need to split the deploy into these steps. Deploy `Admin` > get the address > reference from `Lottery` using previous address > Deploy `Lottery`. Hope it helps.\n- Thanks. But I've got a problem. I see that if your constructor doesn't accept parameters then calling it like Typecontract A = typecontract(address_reference) creates an istnace of your contract in the variable A. But if you have just one parameter which is not an address in the constructor then calling typecontract A = typecontract(address) is incorret and in my case it's exactly what is not working. I had to remove the parameters from the constructor and everything started to work. I don't get how it should work when you got parameters in the constructor.","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":171,"estimatedTokens":1436}}91{"id":"stack-49051856","source":"stackoverflow","questionId":49051856,"title":"Is there a pop functionality for solidity arrays?","tags":["data-structures","solidity"],"text":"Title: Is there a pop functionality for solidity arrays?\nTags: data-structures, solidity\nSource: Stack Overflow\n\nQuestion:\nI have used solidity to push data into an array. Is there a similar function for pop ?\n\n```\nstring[] myArray;\nmyArray.push(\"hello\")\n```\n\nWhat is the best solution for this ? How do I delete an element in a dynamic array in solidity ?\n\n========================================\n\nTop Answer:\n**You can try...**\n\n```\npragma solidity ^0.4.17;\n\ncontract TestArray {\n uint[] public items;\n\n constructor () public {\n items.push(1);\n items.push(2);\n items.push(3);\n items.push(4);\n }\n\n function pushElement(uint value) public {\n items.push(value);\n }\n\n function popElement() public returns (uint []){\n delete items[items.length-1];\n items.length--;\n return items;\n }\n\n function getArrayLength() public view returns (uint) {\n return items.length;\n }\n\n function getFirstElement() public view returns (uint) {\n return items[0];\n }\n\n function getAllElement() public view returns (uint[]) {\n return items;\n }\n}\n```\n\n========================================\n\nCode:\n```text\nstring[] myArray;\nmyArray.push(\"hello\")\n```\n\n```text\nstring element = myArray[index];\ndelete myArray[index];\nreturn element;\n```\n\n```text\nstring element = myArray[index];\nmyArray[index] = myArray[myArray.length - 1];\ndelete myArray[myArray.length - 1];\nmyArray.length--;\nreturn element;\n```\n\n```text\nstring element = myArray[index];\nfor (uint i = index; i < myArray.length - 1; i++) {\n  myArray[i] = myArray[i + 1];\n}\ndelete myArray[myArray.length - 1];\nmyArray.length--;\nreturn element;\n```\n\n```text\npragma solidity ^0.4.24;\n\nlibrary StackLib {\n  using StackLib for Stack;\n\n  struct Stack {\n    uint[] _items;\n  }\n\n  function pushElement(Stack storage self, uint element) internal returns (bool) {\n    self._items.push(element);\n  }\n\n  function popElement(Stack storage self) internal returns (uint) {\n    uint element = self.peek();\n\n    if (self.size() > 0)\n      delete self._items[self.size() - 1];\n\n    return element;\n  }\n\n  function peek(Stack storage self) internal returns (uint) {\n    uint value;\n\n    if (self.size() > 0)\n      value = self._items[self.size() - 1];\n\n    return value;\n  }\n\n  function size(Stack storage self) internal returns (uint8) {\n    return self.size();\n  }\n}\n```\n\n```text\ncontract Test {\n  using StackLib for StackLib.Stack;\n\n  StackLib.Stack numbers;\n\n  function add(uint v) public {\n    numbers.pushElement(v);\n  }\n\n  function doSomething() public {\n    for (uint8 i = 0; i < numbers.size(); i++) {\n      uint curNum = numbers.popElement();\n\n      // do something with curNum\n    }\n  }\n}\n```\n\n```text\npop\n```\n\n```text\ndelete\n```\n\n```text\nif(bytes(myArray[index]).length > 0) ...\n```\n\n```text\npopElement\n```\n\n```text\nvar\n```\n\n```text\npragma solidity ^0.4.17;\n\ncontract TestArray {\n   uint[] public items;\n\n   constructor () public {\n      items.push(1);\n      items.push(2);\n      items.push(3);\n      items.push(4);\n   }\n\n   function pushElement(uint value) public {\n      items.push(value);\n   }\n\n   function popElement() public returns (uint []){\n      delete items[items.length-1];\n      items.length--;\n      return items;\n   }\n\n   function getArrayLength() public view returns (uint) {\n      return items.length;\n   }\n\n   function getFirstElement() public view returns (uint) {\n      return items[0];\n   }\n\n   function getAllElement()  public view returns (uint[]) {\n      return items;\n   }\n}\n```\n\n```text\nfunction deleteElement(uint _index) public returns(bool) {\n    if (_index < 0 || _index >= x.length) {\n        return false;\n    } else if(x.length == 1) {\n        x.pop();\n        return true;\n    } else if (_index == x.length - 1) {\n        x.pop();\n        return true;\n    } else {\n        for (uint i = _index; i < x.length - 1; i++) {\n            x[i] = x[i + 1];\n        }\n        \n        x.pop();\n        return true;\n    }\n}\n```\n\n========================================\n\nComments:\n- Okay.. this makes sense.. and that is why in solidity I can actually go ahead and change the length of the dynamic array.. unlike other languages, where it's a function.\n- Thanks - very helpful explanation. I think there's a minor mistake in the `Swap & Delete` example though. `delete[myArray.length - 1];` should actually be `delete myArray[myArray.length - 1];`, no?\n- Im getting error `TypeError: Member \"length\" is read-only and cannot be used to resize arrays.`\n- @Codler - length was made read only in 0.6. From release notes “Member-access to length of arrays is now always read-only, even for storage arrays. It is no longer possible to resize storage arrays by assigning a new value to their length. Use push(), push(value) or pop() instead, or assign a full array, which will of course overwrite the existing content. The reason behind this is to prevent storage collisions of gigantic storage arrays.”\n- I'd recommend to write this as a library, though.\n- @L. Guthardt Sorry! I busy\n- @AdamKipnis i create utils for list integer, integer and string but i research for use type dynamic array in solidity but i not found. you can join for creating other utils. github.com/20Scoops-CNX/solidity-utils\n- @JedsadaTiwongvorakul See my updated answer for an example.\n- function getAllElement() public view returns (uint[] memory) { return numbers; }\n- Please add more details about you code and how does it answers the question.","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":237,"estimatedTokens":1340}}92{"id":"stack-49449474","source":"stackoverflow","questionId":49449474,"title":"Is it possible to modify a variable value from another contract?","tags":["ethereum","solidity"],"text":"Title: Is it possible to modify a variable value from another contract?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI could get the information about access another contract's variable from here \n\nBut I couldn't find how to modify another contract's variable.\n\nHere is the example of contract A,\n\n```\ncontract A {\n uint public target;\n}\n```\n\nAnd this is the example of contract B\n\n```\ncontract B {\n function edit_A_a() public {\n A.target = 1; // some kind of this\n }\n}\n```\n\nI want to modify the value of `target` variable from contract B. \n\nAlso, assuming that all operations are executed in a solidity contract level.\n\nThanks\n\n========================================\n\nTop Answer:\nNo, you can't directly edit a variable of a contract. That would be a security nightmare.\n\nYou can only use public/external functions provided by an external contract through interfaces. If that function itself is a `setter` and allows you to change a variable, only then it is possible.\n\nContract A:\n\n```\ncontract A {\n uint myVariable = 1\n\n function setMyVariable(uint _newVar) public {\n myVariable = _newVar;\n }\n}\n```\n\nContract B:\n\n```\ninterface A {\n function getMyVariable() view public returns(uint);\n}\n\nfunction setMyVariable(uint _newVar) public onlyOwner {\n A a = A([CONTRACT A ADDRESS HERE])\n a.setMyVariable(_newVar);\n}\n```\n\n========================================\n\nCode:\n```text\ncontract A {\n    uint public target;\n}\n```\n\n```text\ncontract B {\n    function edit_A_a() public {\n        A.target = 1;  // some kind of this\n    }\n}\n```\n\n```text\ntarget\n```\n\n```text\ncontract A {\n    uint public target;\n    function setTarget(uint _target) public {\n        target = _target;\n    }\n}\n\ncontract B {\n    A a = Test(0x123abc...);  // address of deployed A\n    function editA() public {\n        a.setTarget(1);\n    }\n}\n```\n\n```text\npublic\n```\n\n```text\ncontract A {\n    uint myVariable = 1\n\n    function setMyVariable(uint _newVar) public {\n        myVariable = _newVar;\n    }\n}\n```\n\n```text\ninterface A {\n    function getMyVariable() view public returns(uint);\n}\n\nfunction setMyVariable(uint _newVar) public onlyOwner {\n    A a = A([CONTRACT A ADDRESS HERE])\n    a.setMyVariable(_newVar);\n}\n```\n\n```text\nsetter\n```\n\n========================================\n\nComments:\n- Hello and welcome to Stack Overflow. Please take a moment to review the following how-to resources: How to Ask and Complete Examples.\n- @lavor Hi! Thank you for your feedback on the question. I added some content, what else can I add?\n- Good job adding the extra information. 👍\n- Thank you! It was really helpful answer :)","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":138,"estimatedTokens":648}}93{"id":"stack-71721805","source":"stackoverflow","questionId":71721805,"title":"Debugging \"Transaction simulation failed\" when sending program instruction (Solana Solidity)","tags":["solidity","solana","solana-web3js","phantom-wallet"],"text":"Title: Debugging \"Transaction simulation failed\" when sending program instruction (Solana Solidity)\nTags: solidity, solana, solana-web3js, phantom-wallet\nSource: Stack Overflow\n\nQuestion:\nWhen attempting to make a call to a program compiled with @solana/solidity, I'm getting the following error:\n\n```\nTransaction simulation failed: Error processing Instruction 0: Program failed to complete \n Program jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N invoke [1]\n Program log: pxKTQePwHC9MiR52J5AYaRtSLAtkVfcoGS3GaLD24YX\n Program log: sender account missing from transaction\n Program jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N consumed 200000 of 200000 compute units\n Program failed to complete: BPF program Panicked in solana.c at 285:0\n Program jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N failed: Program failed to complete\n```\n\n`jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N` is the program's public key and `pxKTQePwHC9MiR52J5AYaRtSLAtkVfcoGS3GaLD24YX` is the sender's public key.\n\nI'm using a fork of the @solana/solidity library that exposes the `Transaction` object so that it can be signed and sent by Phantom Wallet on the front end. The code that results in the error is as follows:\n\n```\n// Generate the transaction\nconst transaction = contract.transactions.send(...args);\n\n// Add recent blockhash and fee payer\nconst recentBlockhash = (await connection.getRecentBlockhash()).blockhash;\ntransaction.recentBlockhash = recentBlockhash;\ntransaction.feePayer = provider.publicKey;\n\n// Sign and send the transaction (throws an error)\nconst res = await provider.signAndSendTransaction(transaction);\n```\n\nI would attempt to debug this further myself, but I'm not sure where to start. Looking up the error message hasn't yielded any results and the error message isn't very descriptive. I'm not sure if this error is occurring within the program execution itself or if it's an issue with the composition of the transaction object. If it is an issue within the program execution, is there a way for me to add logs to my solidity code? If it's an issue with the transaction object, what could be missing? How can I better debug issues like this?\n\nThank you for any help.\n\nEdit: I'm getting a different error now, although I haven't changed any of the provided code. The error message is now the following:\n\n```\nPhantom - RPC Error: Transaction creation failed. {code: -32003, message: 'Transaction creation failed.'}\n```\n\nUnfortunately this error message is even less helpful than the last one. I'm not sure if Phantom Wallet was updated or if a project dependency was updated at some point, but given the vague nature of both of these error messages and the fact that none of my code has changed, I believe they're being caused by the same issue. Again, any help or debugging tips are appreciated.\n\n========================================\n\nCode:\n```text\nTransaction simulation failed: Error processing Instruction 0: Program failed to complete \n    Program jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N invoke [1]\n    Program log: pxKTQePwHC9MiR52J5AYaRtSLAtkVfcoGS3GaLD24YX\n    Program log: sender account missing from transaction\n    Program jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N consumed 200000 of 200000 compute units\n    Program failed to complete: BPF program Panicked in solana.c at 285:0\n    Program jdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N failed: Program failed to complete\n```\n\n```js\n// Generate the transaction\nconst transaction = contract.transactions.send(...args);\n\n// Add recent blockhash and fee payer\nconst recentBlockhash = (await connection.getRecentBlockhash()).blockhash;\ntransaction.recentBlockhash = recentBlockhash;\ntransaction.feePayer = provider.publicKey;\n\n// Sign and send the transaction (throws an error)\nconst res = await provider.signAndSendTransaction(transaction);\n```\n\n```text\nPhantom - RPC Error: Transaction creation failed. {code: -32003, message: 'Transaction creation failed.'}\n```\n\n```text\njdN1wZjg5P4xi718DG2HraGuxVx1mM7ebjXpxbJ5R3N\n```\n\n```text\npxKTQePwHC9MiR52J5AYaRtSLAtkVfcoGS3GaLD24YX\n```\n\n```text\nTransaction\n```\n\n```js\nconst signed = await provider.request({\n  method: 'signTransaction',\n  params: {\n    message: bs58.encode(transaction.serializeMessage()),\n  },\n});\n\nconst signature = bs58.decode(signed.signature);\ntransaction.addSignature(provider.publicKey, signature);\n\nawait connection.sendRawTransaction(transaction.serialize())\n```\n\n```text\n.signAndSendTransaction()\n```\n\n```text\nkeys\n```\n\n```text\nTransactionInstruction\n```\n\n```text\nTransaction\n```\n\n```text\nprovider.request({ method: 'signTransaction' })\n```\n\n```text\nconnection.sendRawTransaction(transaction)\n```\n\n```text\nprovider.signAndSendTransaction()\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":129,"estimatedTokens":1169}}94{"id":"stack-71159017","source":"stackoverflow","questionId":71159017,"title":"getting error when i deploy the NFT with ETH","tags":["ethereum","solidity","nft","hardhat","openzeppelin"],"text":"Title: getting error when i deploy the NFT with ETH\nTags: ethereum, solidity, nft, hardhat, openzeppelin\nSource: Stack Overflow\n\nQuestion:\nI am new in NFT, i am trying to create test NFT, when i am trying to deploy that NFT, i am getting this error,`insufficient funds for intrinsic transaction cost`, even though in my account have 1 ETH balance here i have attached my whole code of it, can anyone please help me, how to resolve this issue ?\nMyNFT.sol\n\n```\n//Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721)\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/utils/Counters.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol\";\n\ncontract MyNFT is ERC721URIStorage, Ownable { \n using Counters for Counters.Counter;\n Counters.Counter private _tokenIds;\n\n constructor() ERC721(\"MyNFT\", \"NFT\") {}\n\n function mintNFT(address recipient, string memory tokenURI)\n public onlyOwner\n returns (uint256)\n {\n _tokenIds.increment();\n\n uint256 newItemId = _tokenIds.current();\n _mint(recipient, newItemId);\n _setTokenURI(newItemId, tokenURI);\n\n return newItemId;\n }\n}\n```\n\nhardhat.config.js\n\n```\n/**\n\n* @type import('hardhat/config').HardhatUserConfig\n\n*/\n\nrequire('dotenv').config();\nrequire(\"@nomiclabs/hardhat-ethers\");\nconst { API_URL, PRIVATE_KEY } = process.env;\n//console.log(PRIVATE_KEY);\nmodule.exports = {\n solidity: \"0.8.1\",\n defaultNetwork: \"ropsten\",\n networks: {\n hardhat: {},\n ropsten: {\n url: API_URL,\n accounts: [`0x${PRIVATE_KEY}`]\n }\n },\n}\n```\n\ndeploy.js\n\n```\nasync function main() {\n const MyNFT = await ethers.getContractFactory(\"MyNFT\")\n \n // Start deployment, returning a promise that resolves to a contract object\n const myNFT = await MyNFT.deploy()\n await myNFT.deployed() \n console.log(\"Contract deployed to address:\", myNFT.address)\n }\n \n main()\n .then(() => process.exit(0))\n .catch((error) => {\n console.error(error)\n process.exit(1)\n })\n```\n\n========================================\n\nCode:\n```text\n//Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721)\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/utils/Counters.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol\";\n\ncontract MyNFT is ERC721URIStorage, Ownable {   \n    using Counters for Counters.Counter;\n    Counters.Counter private _tokenIds;\n\n    constructor() ERC721(\"MyNFT\", \"NFT\") {}\n\n    function mintNFT(address recipient, string memory tokenURI)\n        public onlyOwner\n        returns (uint256)\n    {\n        _tokenIds.increment();\n\n        uint256 newItemId = _tokenIds.current();\n        _mint(recipient, newItemId);\n        _setTokenURI(newItemId, tokenURI);\n\n        return newItemId;\n    }\n}\n```\n\n```text\n/**\n\n* @type import('hardhat/config').HardhatUserConfig\n\n*/\n\nrequire('dotenv').config();\nrequire(\"@nomiclabs/hardhat-ethers\");\nconst { API_URL, PRIVATE_KEY } = process.env;\n//console.log(PRIVATE_KEY);\nmodule.exports = {\n   solidity: \"0.8.1\",\n   defaultNetwork: \"ropsten\",\n   networks: {\n      hardhat: {},\n      ropsten: {\n         url: API_URL,\n         accounts: [`0x${PRIVATE_KEY}`]\n      }\n   },\n}\n```\n\n```text\nasync function main() {\n    const MyNFT = await ethers.getContractFactory(\"MyNFT\")\n  \n    // Start deployment, returning a promise that resolves to a contract object\n    const myNFT = await MyNFT.deploy()\n    await myNFT.deployed()      \n    console.log(\"Contract deployed to address:\", myNFT.address)\n  }\n  \n  main()\n    .then(() => process.exit(0))\n    .catch((error) => {\n      console.error(error)\n      process.exit(1)\n    })\n```\n\n```text\ninsufficient funds for intrinsic transaction cost\n```\n\n```text\nconst { API_URL, PRIVATE_KEY } = process.env;\n```\n\n```text\n// ASSUMING you pass correct private key here\nconst PRIVATE_KEY  = process.env.PRIVATE_KEY;\n```\n\n```text\nprocess.env\n```\n\n========================================\n\nComments:\n- This snippet is trying to deploy the contract to Ropsten testnet. Balance on one network does not affect balance on another. Can you confirm that you have the 1 ETH on the deployer address on Ropsten?\n- yes i have 4ETH alance\n- Did you get this resolved?\n- I tried this and the correct private key gets printed to the console. Can you offer any other insight?","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":185,"estimatedTokens":1155}}95{"id":"stack-54499116","source":"stackoverflow","questionId":54499116,"title":"How do you compare strings in Solidity?","tags":["ethereum","solidity"],"text":"Title: How do you compare strings in Solidity?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI would assume comparing strings would be as easy as doing:\n\n```\nfunction withStrs(string memory a, string memory b) internal {\n if (a == b) {\n // do something\n }\n}\n```\n\nBut doing so gives me an error `Operator == not compatible with types string memory and string memory`. \n\nWhat's the right way?\n\n========================================\n\nCode:\n```text\nfunction withStrs(string memory a, string memory b) internal {\n  if (a == b) {\n    // do something\n  }\n}\n```\n\n```text\nOperator == not compatible with types string memory and string memory\n```\n\n```text\nif (keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b))) {\n  // do something\n}\n```\n\n```text\nkeccak256\n```\n\n```text\nabi.encodePacked()\n```\n\n========================================\n\nComments:\n- Probably simple conversion to bytes (from another answer) is cheaper in terms of gas than `abi.encodePacked`. We have to check.","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":52,"estimatedTokens":249}}96{"id":"stack-58277234","source":"stackoverflow","questionId":58277234,"title":"Does Solidity supports floating point number","tags":["ethereum","solidity"],"text":"Title: Does Solidity supports floating point number\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI am new in solidity language. Have seen their documentation. Is there any `floating point` data type ?\n\n========================================\n\nTop Answer:\nThere is no native support for floating-point numbers in the core language, but they are available via libraries, such as ABDKMathQuad.\n\n========================================\n\nCode:\n```text\nfloating point\n```\n\n```text\ngwei\n```\n\n```text\n10^9\n```\n\n```text\nether\n```\n\n```text\n10^18\n```\n\n```text\n0.1 ether\n```\n\n```text\n100000000000000000\n```\n\n```text\n= 10^17 wei\n```\n\n```text\n1.00000000000000000000000001 ether\n```\n\n```text\nwei\n```\n\n========================================\n\nComments:\n- Unfortunately the library you link to looks like it's under copyright, so it cannot be used.\n- @Pro Q - true fact","metadata":{"transformedAt":"2026-08-18T18:33:36.118Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":60,"estimatedTokens":218}}97{"id":"stack-50772811","source":"stackoverflow","questionId":50772811,"title":"How can I get the same return value as solidity `abi.encodePacked` in Golang","tags":["go","ethereum","solidity"],"text":"Title: How can I get the same return value as solidity `abi.encodePacked` in Golang\nTags: go, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nHow can i run abi.encodePacked in golang?\n\nin solidity i use `keccak256(abi.encodePacked(a, b))` to calc the signature of the params.\n\nhere is my contract.\n\n```\npragma solidity ^0.4.24;\n\nimport \"openzeppelin-solidity/contracts/ECRecovery.sol\";\n\ncontract MyContract {\n using ECRecovery for bytes32;\n address permittedSinger;\n\n function doSomething(\n bytes32 id, uint256 amount, bytes sig\n ) {\n bytes32 hash = getHash(msg.sender, id, amount);\n address msgSigner = hash.recover(sig);\n require(msgSigner == permittedSinger);\n }\n\n function getMsgSigner(bytes32 proveHash, bytes sig) public pure returns (address) {\n return proveHash.recover(sig);\n }\n\n function getHash(\n address receiver, bytes32 id, uint256 amount\n ) pure returns (bytes32) {\n return keccak256(abi.encodePacked(receiver, id, amount));\n }\n}\n```\n\n========================================\n\nTop Answer:\nAs `Jakub N` is said in comments to accepted answer, `Go's arguments.Pack` returns as `abi.encode` and not `abi.encodePacked`. In your case it works because all packed values are 32 bytes, but if you also add some strings then the result will be different.\n\nHere is how to do it to be compatible with **tightly** packed encoding corresponding to `abi.encodePacked`:\n\n```\n// hash of packed byte array with arguments\n\nhash := crypto.Keccak256Hash(\n common.HexToAddress(\"0x0000000000000000000000000000000000000000\").Bytes(),\n [32]byte{'I','D','1'},\n common.LeftPadBytes(big.NewInt(42).Bytes(), 32),\n []byte(\"Some other string value\"),\n )\n\n// normally we sign prefixed hash\n// as in solidity with `ECDSA.toEthSignedMessageHash`\n\nprefixedHash := crypto.Keccak256Hash(\n []byte(fmt.Sprintf(\"\\x19Ethereum Signed Message:\\n%v\", len(hash))),\n hash.Bytes(),\n )\n\n// sign hash to validate later in Solidity\n\nsig, err := crypto.Sign(prefixedHash.Bytes(), privateKey)\n```\n\nIt is also more efficient as we don't pack and allocate additional memory for that. Hash function iterates over existing values.\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.24;\n\nimport \"openzeppelin-solidity/contracts/ECRecovery.sol\";\n\n\ncontract MyContract {\n    using ECRecovery for bytes32;\n    address permittedSinger;\n\n    function doSomething(\n    bytes32 id, uint256 amount, bytes sig\n    ) {\n        bytes32 hash = getHash(msg.sender, id, amount);\n        address msgSigner = hash.recover(sig);\n        require(msgSigner == permittedSinger);\n    }\n\n    function getMsgSigner(bytes32 proveHash, bytes sig) public pure returns (address) {\n        return proveHash.recover(sig);\n    }\n\n    function getHash(\n    address receiver, bytes32 id, uint256 amount\n    ) pure returns (bytes32) {\n        return keccak256(abi.encodePacked(receiver, id, amount));\n    }\n}\n```\n\n```text\nkeccak256(abi.encodePacked(a, b))\n```\n\n```text\npackage main\n\nimport (\n    \"math/big\"\n    \"github.com/ethereum/go-ethereum/common/hexutil\"\n    \"github.com/ethereum/go-ethereum/accounts/abi\"\n    \"log\"\n    \"github.com/ethereum/go-ethereum/common\"\n    \"github.com/ethereum/go-ethereum/crypto/sha3\"\n)\n\nfunc main() {\n    uint256Ty, _ := abi.NewType(\"uint256\")\n    bytes32Ty, _ := abi.NewType(\"bytes32\")\n    addressTy, _ := abi.NewType(\"address\")\n\n    arguments := abi.Arguments{\n        {\n            Type: addressTy,\n        },\n        {\n            Type: bytes32Ty,\n        },\n        {\n            Type: uint256Ty,\n        },\n    }\n\n    bytes, _ := arguments.Pack(\n        common.HexToAddress(\"0x0000000000000000000000000000000000000000\"),\n        [32]byte{'I','D','1'},\n        big.NewInt(42),\n    )\n\n    var buf []byte\n    hash := sha3.NewKeccak256()\n    hash.Write(bytes)\n    buf = hash.Sum(buf)\n\n    log.Println(hexutil.Encode(buf))\n    // output:\n    // 0x1f214438d7c061ad56f98540db9a082d372df1ba9a3c96367f0103aa16c2fe9a\n}\n```\n\n```golang\n// hash of packed byte array with arguments\n\nhash := crypto.Keccak256Hash(\n        common.HexToAddress(\"0x0000000000000000000000000000000000000000\").Bytes(),\n        [32]byte{'I','D','1'},\n        common.LeftPadBytes(big.NewInt(42).Bytes(), 32),\n        []byte(\"Some other string value\"),\n    )\n\n// normally we sign prefixed hash\n// as in solidity with `ECDSA.toEthSignedMessageHash`\n\nprefixedHash := crypto.Keccak256Hash(\n        []byte(fmt.Sprintf(\"\\x19Ethereum Signed Message:\\n%v\", len(hash))),\n        hash.Bytes(),\n    )\n\n// sign hash to validate later in Solidity\n\nsig, err := crypto.Sign(prefixedHash.Bytes(), privateKey)\n```\n\n```text\nJakub N\n```\n\n```text\nGo's arguments.Pack\n```\n\n```text\nabi.encode\n```\n\n```text\nabi.encodePacked\n```\n\n```text\nabi.encodePacked\n```\n\n========================================\n\nComments:\n- No, I need to build some params in Golang. If someone call the contract, I want to check these params are valid. So i have to calculate the signature of the params in Golang, then check it in Contract.\n- look here go-ethereum source code\n- The easiest thing to do would just be to call the smart contract's `getHash` from your Go code.\n- @ChihebNexus thanks\n- Unfortunately, it doesn't work the same for dynamic length types (like `bytes`). Go's `arguments.Pack` will return what you get from `abi.encode` not `abi.encodePacked`.\n- go-ethereum 1.9.7 has a few more args in `abi.NewType`. The above still work with `abi.NewType(\"uint256\", \"uint256\", nil)`\n- what if an array like two addresses?","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":208,"estimatedTokens":1360}}98{"id":"stack-48077773","source":"stackoverflow","questionId":48077773,"title":"Ethereum Solidity - Does require() use any gas?","tags":["blockchain","ethereum","solidity","smartcontracts"],"text":"Title: Ethereum Solidity - Does require() use any gas?\nTags: blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nGoogle has failed to give me an concrete answer, does using the `require()` function in `Solidity` use up any gas? Even if the statement in the function is evaluated as true?\n\n========================================\n\nTop Answer:\n`require` does not use gas in case of failure but uses if it is evaluated `true`. In case of failure, the state is reverted and \"UNUSED\" gas is returned. However, it does not return already consumed gas.\n\n```\nfunction test() public view {\n // some function logic;\n require(condition,\"\")\n}\n```\n\nIn this case if `require` fails, the gas that used to execute \"some function logic\" will not be reverted. That is why `require` is used at the beginning of the function.\n\n========================================\n\nCode:\n```text\nrequire()\n```\n\n```text\nSolidity\n```\n\n```text\ncontract GasUsage {\n    uint val;\n\n    function someFunc() public returns (bool) {\n        require(true);\n\n        delete val;\n    }\n}\n```\n\n```text\nREVERT\n```\n\n```text\nrequire()\n```\n\n```text\nrequire(true)\n```\n\n```text\nrequire\n```\n\n```text\nrequire\n```\n\n```text\nrequire()\n```\n\n```text\nassert()\n```\n\n```text\nREVERT\n```\n\n```text\nfunction test() public view {\n    // some function logic;\n    require(condition,\"\")\n}\n```\n\n```text\nrequire\n```\n\n```text\ntrue\n```\n\n```text\nrequire\n```\n\n```text\nrequire\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":98,"estimatedTokens":359}}99{"id":"stack-70019983","source":"stackoverflow","questionId":70019983,"title":"What is difference between internal and private in Solidity?","tags":["blockchain","solidity","smartcontracts"],"text":"Title: What is difference between internal and private in Solidity?\nTags: blockchain, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nIn Solidity we have four types of access. Two of them are `private` and `internal`.\nWhat is the difference if both of them can be used inside smart contract and both of them are not visible after deploying?\n\n========================================\n\nTop Answer:\n`internal` properties can be accessed from child contracts (but not from external contracts).\n\n`private` properties can't be accessed even from child contracts.\n\n```\npragma solidity ^0.8;\n\ncontract Parent {\n bool internal internalProperty;\n bool private privateProperty;\n}\n\ncontract Child is Parent {\n function foo() external {\n // ok\n internalProperty = true;\n \n // error, not visible\n privateProperty = true;\n }\n}\n```\n\nYou can find more info in the docs section Visibility and Getters.\n\n========================================\n\nCode:\n```text\nprivate\n```\n\n```text\ninternal\n```\n\n```text\npublic\n```\n\n```text\nexternal\n```\n\n```text\ninternal\n```\n\n```text\nprivate\n```\n\n```text\npragma solidity ^0.8;\n\ncontract Parent {\n    bool internal internalProperty;\n    bool private privateProperty;\n}\n\ncontract Child is Parent {\n    function foo() external {\n        // ok\n        internalProperty = true;\n        \n        // error, not visible\n        privateProperty = true;\n    }\n}\n```\n\n```text\ninternal\n```\n\n```text\nprivate\n```\n\n```text\npublic\n```\n\n```text\nprivate\n```\n\n```text\ninternal\n```\n\n```text\nexternal\n```\n\n```text\nexternal\n```\n\n```text\npublic\n```\n\n```text\nexternal\n```\n\n```text\npublic\n```\n\n```text\ninternal\n```\n\n```text\nexternal\n```\n\n```text\nprivate\n```\n\n```text\npublic\n```\n\n========================================\n\nComments:\n- By `not visible after deploying` you mean they are not visible (and cannot be used) by a user or another smart contract.\n- This was better than the soildity docs","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":143,"estimatedTokens":474}}100{"id":"stack-48877910","source":"stackoverflow","questionId":48877910,"title":"How can I return an array of struct in solidity?","tags":["algorithm","data-structures","ethereum","solidity","smartcontracts"],"text":"Title: How can I return an array of struct in solidity?\nTags: algorithm, data-structures, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI am designing a solution for an ethereum smart contract that does **bidding**. The use-case includes reserving a name eg. \"myName\" and assigning to an address. And then, people can bid for that name (in this case myName). There can be **multiple such biddings happening for multiple names**.\n\n```\nstruct Bid {\n address bidOwner;\n uint bidAmount;\n bytes32 nameEntity;\n}\n\nmapping(bytes32 => Bid[]) highestBidder;\n```\n\nSo, as you can see above, Bid struct holds data for one bidder, similarly, the key (eg. myName) in the mapping highestBidder points to an array of such bidders.\n\n**Now, I am facing a problem when I try to return something like highestBidder[myName]**.\n\nApparently, solidity does not support returning an array of structs (dynamic data). I either need to rearchitect my solution or find some workaround to make it work.\n\nIf you guys have any concerns regarding the question, please let me know, I will try to make it clear.\n\nI am stuck here any help would be appreciated.\n\n========================================\n\nTop Answer:\n**Return an array of struct in solidity?**\n\nIn below function **getBid** returns array of bid structure.\n\n```\ncontract BidHistory {\n struct Bid {\n address bidOwner;\n uint bidAmount;\n bytes32 nameEntity;\n }\n mapping (uint => Bid) public bids;\n uint public bidCount;\n\n constructor() public {\n bidCount = 0;\n storeBid(\"address0\",0,0);\n storeBid(\"address1\",1,1);\n }\n function storeBid(address memory _bidOwner, uint memory _bidAmount, bytes32 memory _nameEntity) public {\n bids[tripcount] = Bid(_bidOwner, _bidAmount,_nameEntity);\n bidCount++;\n }\n //return Array of structure\n function getBid() public view returns (Bid[] memory){\n Bid[] memory lBids = new Bid[](tripcount);\n for (uint i = 0; i < bidCount; i++) {\n Bid storage lBid = bids[i];\n lBids[i] = lBid;\n }\n return lBids;\n }\n}\n```\n\n========================================\n\nCode:\n```text\nstruct Bid {\n  address bidOwner;\n  uint bidAmount;\n  bytes32 nameEntity;\n}\n\nmapping(bytes32 => Bid[]) highestBidder;\n```\n\n```text\nfunction getBidCount(bytes32 name) public constant returns (uint) {\n    return highestBidder[name].length;\n}\n\nfunction getBid(bytes32 name, uint index) public constant returns (address, uint, bytes32) {\n    Bid storage bid = highestBidder[name][index];\n\n    return (bid.bidOwner, bid.bidAmount, bid.nameEntity);\n}\n```\n\n```text\nstorage\n```\n\n```text\nmemory\n```\n\n```text\nstorage\n```\n\n```text\nuint[] x\n```\n\n```text\nBid bid\n```\n\n```text\ngetBid(\"foo\", 0)\n```\n\n```text\nBid memory bid\n```\n\n```text\ngetBid(\"foo\", 0)\n```\n\n```text\nBid storage bid\n```\n\n```text\nstorage\n```\n\n```text\npragma solidity ^0.4.13;\n\ncontract Project\n{\n    struct Person {\n        address addr;\n        uint funds;\n    }\n\n    Person[] people;\n\n    function getPeople(uint[] indexes)\n    public\n    returns (address[], uint[]) {\n        address[] memory addrs = new address[](indexes.length);\n        uint[]    memory funds = new uint[](indexes.length);\n\n        for (uint i = 0; i < indexes.length; i++) {\n            Person storage person = people[indexes[i]];\n            addrs[i] = person.addr;\n            funds[i] = person.funds;\n        }\n\n        return (addrs, funds);\n    }\n}\n```\n\n```text\ncontract BidHistory {\n  struct Bid {\n    address bidOwner;\n    uint bidAmount;\n    bytes32 nameEntity;\n  }\n  mapping (uint => Bid) public bids;\n  uint public bidCount;\n\n  constructor() public {\n    bidCount = 0;\n    storeBid(\"address0\",0,0);\n    storeBid(\"address1\",1,1);\n  }\n  function storeBid(address memory _bidOwner, uint memory _bidAmount, bytes32 memory _nameEntity) public  {\n    bids[tripcount] = Bid(_bidOwner, _bidAmount,_nameEntity);\n    bidCount++;\n  }\n  //return Array of structure\n  function getBid() public view returns (Bid[] memory){\n      Bid[] memory lBids = new Bid[](tripcount);\n      for (uint i = 0; i < bidCount; i++) {\n          Bid storage lBid = bids[i];\n          lBids[i] = lBid;\n      }\n      return lBids;\n  }\n}\n```\n\n========================================\n\nComments:\n- This solves my problem, Thanks! Just a small doubt why did you use \"Bid storage bid\" in your answer. We can use \"memory\", which will save some gas.\n- @AdamKipnis Which tool did you use to get the details for the screenshots above ? information like txn cost Vs execution cost and \"decoded input data\" is very useful.\n- It’s from the transaction results in Remix (remix.ethereum.org).\n- In 2022, it seems we can just return an array of struct straightforwardly. ethereum.stackexchange.com/questions/3589/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":197,"estimatedTokens":1162}}101{"id":"stack-43935520","source":"stackoverflow","questionId":43935520,"title":"who is the owner of the contracts deployed using truffle?","tags":["solidity","smartcontracts","truffle"],"text":"Title: who is the owner of the contracts deployed using truffle?\nTags: solidity, smartcontracts, truffle\nSource: Stack Overflow\n\nQuestion:\nI am using testrpc and truffle to test my contract.\n\nWhen I type `truffle migrate` , this will deploy my contract to the testrpc network.\n\nMy question is , which account (from testrpc accounts) has been used to deploy the contract.\n\nIn other word, whose the contract owner?\n\nThank you in advance\n\n========================================\n\nCode:\n```text\ntruffle migrate\n```\n\n```text\nmodule.exports = {\n  networks: {\n    development: {\n      host: \"localhost\",\n      port: 8545,\n      network_id: \"*\",\n      from: \"0xda9b1a939350dc7198165ff84c43ce77a723ef73\"\n    }\n  }\n};\n```\n\n```text\naccounts[0]\n```\n\n========================================\n\nComments:\n- @Crema thanks for the answer. I am also wandering how to set the custom account to execute transaction? For example in truffle console i have something like Hello.deployed().then(function(){h = instance}), and then h.exetuceTransaction() will burn gas from the accounts[0] by default. How can I specify the account from which I want to send this transaction (for example accouts[1])?\n- @brankoterzic I think you just have to specify the `from`parameter when calling `executeTransaction({\"from\" : \"0x...\" })` check The doc","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":44,"estimatedTokens":329}}102{"id":"stack-69013697","source":"stackoverflow","questionId":69013697,"title":"Get events from a transaction receipt in hardhat","tags":["javascript","solidity","ethers.js","hardhat"],"text":"Title: Get events from a transaction receipt in hardhat\nTags: javascript, solidity, ethers.js, hardhat\nSource: Stack Overflow\n\nQuestion:\nI have an `ethers` contract that I've made a transaction with:\n\n```\nconst randomSVG = new ethers.Contract(RandomSVG.address, RandomSVGContract.interface, signer)\nlet tx = await randomSVG.create()\n```\n\nI have an event with this transaction:\n\n```\nfunction create() public returns (bytes32 requestId) {\n requestId = requestRandomness(keyHash, fee);\n emit requestedRandomSVG(requestId);\n }\n```\n\nHowever, I can't see the logs in the transaction receipt.](https://docs.ethers.io/v5/api/providers/types/#providers-TransactionReceipt)\n\n```\n// This returns undefined\nconsole.log(tx.logs)\n```\n\n========================================\n\nCode:\n```js\nconst randomSVG = new ethers.Contract(RandomSVG.address, RandomSVGContract.interface, signer)\nlet tx = await randomSVG.create()\n```\n\n```js\nfunction create() public returns (bytes32 requestId) {\n        requestId = requestRandomness(keyHash, fee);\n        emit requestedRandomSVG(requestId);\n    }\n```\n\n```text\n// This returns undefined\nconsole.log(tx.logs)\n```\n\n```text\nethers\n```\n\n```js\nconst randomSVG = new ethers.Contract(RandomSVG.address, RandomSVGContract.interface, signer)\nconst tx = await randomSVG.create()\n// Wait until the tx has been confirmed (default is 1 confirmation)\nconst receipt = await tx.wait()\n// Receipt should now contain the logs\nconsole.log(receipt.logs)\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":60,"estimatedTokens":366}}103{"id":"stack-66678463","source":"stackoverflow","questionId":66678463,"title":"Cannot find module 'fs-extra' when testing with Truffle","tags":["npm","node-modules","solidity","truffle"],"text":"Title: Cannot find module 'fs-extra' when testing with Truffle\nTags: npm, node-modules, solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nI am reading the tutorial on Ethereum Pet Shop -- Your First DApp, everything seems ok until I test with `truffle test` with below error:\n\n```\nError: Cannot find module 'fs-extra'\nat Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)\nat Function.Module._load (internal/modules/cjs/loader.js:562:25)\nat Module.require (internal/modules/cjs/loader.js:690:17)\nat require (internal/modules/cjs/helpers.js:25:18)\nat Object.call (/Users/.npm-global/lib/node_modules/truffle/node_modules/@truffle/debugger/dist/external \"fs-extra\":1:18)\nat r (/Users/.npm-global/lib/node_modules/truffle/node_modules/@truffle/debugger/dist/webpack/bootstrap:19:22)\n[...]\nTruffle v5.2.4 (core: 5.2.4)\nNode v10.16.0\n```\n\nI have tried some suggestions as in Module is extraneous npm, but the `Error: Cannot find module 'fs-extra'` insists.\n\n========================================\n\nTop Answer:\n*fs-extra*-package should be delivered as part of *truffle* and I would not recommend installing it to the project.\n\nTo fix it on Ubuntu these steps:\n\n```\n# stop apps/tools that using truffle - ganache-cli, etc.\n\n# uninstall truffle\nsudo npm uninstall -g truffle\n\n# install truffle again\nsudo npm install -g truffle\n\n# check that fs-extra packaged installed\nls -lh /usr/local/lib/node_modules/truffle/node_modules | grep fs-extra\n```\n\n========================================\n\nCode:\n```text\nError: Cannot find module 'fs-extra'\nat Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)\nat Function.Module._load (internal/modules/cjs/loader.js:562:25)\nat Module.require (internal/modules/cjs/loader.js:690:17)\nat require (internal/modules/cjs/helpers.js:25:18)\nat Object.call (/Users/.npm-global/lib/node_modules/truffle/node_modules/@truffle/debugger/dist/external \"fs-extra\":1:18)\nat r (/Users/.npm-global/lib/node_modules/truffle/node_modules/@truffle/debugger/dist/webpack/bootstrap:19:22)\n[...]\nTruffle v5.2.4 (core: 5.2.4)\nNode v10.16.0\n```\n\n```text\ntruffle test\n```\n\n```text\nError: Cannot find module 'fs-extra'\n```\n\n```text\nnpm install --save fs-extra\n```\n\n```text\n\"dependencies\": {\n    \"fs-extra\": \"^9.1.0\"\n}\n```\n\n```text\nnpm install\n```\n\n```text\npackage.json\n```\n\n```text\n--save\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json\n```\n\n```text\ndependencies\n```\n\n```sh\n# stop apps/tools that using truffle - ganache-cli, etc.\n\n# uninstall truffle\nsudo npm uninstall -g truffle\n\n# install truffle again\nsudo npm install -g truffle\n\n# check that fs-extra packaged installed\nls -lh  /usr/local/lib/node_modules/truffle/node_modules | grep fs-extra\n```\n\n========================================\n\nComments:\n- Thanks for your swift support! It worked: `TestAdoption ✓ testUserCanAdoptPet (138ms) ✓ testGetAdopterAddressByPetId (146ms) ✓ testGetAdopterAddressByPetIdInArray (182ms) 3 passing (12s)`\n- You should not use sudo with npm install","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":118,"estimatedTokens":748}}104{"id":"stack-70567465","source":"stackoverflow","questionId":70567465,"title":"Get token metadata inside the smart-contract for game functions","tags":["metadata","solidity","ipfs"],"text":"Title: Get token metadata inside the smart-contract for game functions\nTags: metadata, solidity, ipfs\nSource: Stack Overflow\n\nQuestion:\n### Context\n\nI'm working on my first Game working with a Smart contract and I have some question.\n\nOn my game I have characters and cards, and both player will duel each other using one character and 10 card each.\n\nFor that, no issue: All players and cards metadata are stored into an IPFS buckets, and some extra metadata (like experiences) are stored into the smart-contract to be updated by the game.\n\n### The problem\n\nNow I want to be able to create a duel function into my smart-contract. But I don't know how I can access to players and cards metadatas to be able to know you'll win.\n\n### \"Solutions\" I have in mind\n\n**#1:** I never saw any IPFS fetcher to get the metadata, nor JSON parser.. So it's probably not the good way to do it.\n\n**#2:** Do I have to implement a `mapping(uint => Players) private playersMetadata;` into my contract and load all metadata on it to be able to use it on the duel function ??\n\n- But **#2.1**: It'll enlarge the storage needed a lot !\n\n- And **#2.2**: How can I even load it ? By creating a function `setPlayer(uint idx, Players playerMetadata)` and mint 10k+ times this function ? It'll cost me so much !\n\n**#3:** Do not implement this function on the smart-contract and do it on my web-server.. But I don't like that because I want the user to be able to read the smart-contract code and trust it (but don't trust me). So if I do it on my server side, they'll not be able to trust the function.\n\nThank you for helping me ! Have all a good day\n\n========================================\n\nCode:\n```text\nmapping(uint => Players) private playersMetadata;\n```\n\n```text\nsetPlayer(uint idx, Players playerMetadata)\n```\n\n========================================\n\nComments:\n- If want user to win ETH after win a fight, so I think I have to use smart contract. If I can understand well, the best solution is to move all required metadata to my smart contract. But I do not understand what you say by \"Transfer the data\" ? Do I have to populate all existing metadata in the smart contract at the beginning (before fight) or do user have to transfer their own data when they're calling the fight function ? (And if it's the second case, how can I verify it ?) I also thinking about using Polygon network to reduce fees, it's like Ronin Chain for Axis Infinity right ?\n- And If I have to transfer all data at the beginning, what's the best way to populate that much data into the smart contract without paying large amount of fee?\n- @Arthur In order to calculate the fight result in a smart contract, all metadata (required for the fight) should be present in the smart contract. So yes, you should populate the contract before the fight - or better each time a player updates their fighting skills (loads new equipment, etc). Othwerwise, if you let the players to control the logic (submit fight data) themselves, the contract could not verify it and that would open the game to cheating.\n- A cheap way to populate large amount of data into a contract is to create a merkle tree, publish its root to the contract, and let each player claim their metadata providing the proof to the merkle tree (e.g. their address).\n- Okay, I understand everything. Merkle tree look to complicated for me, but thank you for all your answer =]\n- Also, you talk about Axis Infinity, so If i understand well they are using the solution to push all metadata on their smart contract right ?\n- @Arthur Thats correct. But also, they use a L2 sidechain so that the fees are lower compared to the main Ethereum chain.","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":52,"estimatedTokens":915}}105{"id":"stack-50746393","source":"stackoverflow","questionId":50746393,"title":"How to initialize a struct from Javascript when testing a Solidity contract?","tags":["javascript","testing","struct","solidity","truffle"],"text":"Title: How to initialize a struct from Javascript when testing a Solidity contract?\nTags: javascript, testing, struct, solidity, truffle\nSource: Stack Overflow\n\nQuestion:\n**How can I initialize the `Item` struct and assign to a variable?**\n\n```\ncontract ArbitrableBlacklist {\n\n enum ItemStatus {\n Absent, \n Cleared, \n }\n\n struct Item {\n ItemStatus status; \n uint lastAction; \n\n }\n}\n```\n\nTesting above (simplified for question) contract using Truffle but I couldn't find the way to initialize the `Item` struct.\n\nI have tried:\n\n```\nlet x = ArbitrableBlacklist.Item({\n status: 0,\n lastAction: 0\n });\n```\n\nAnd got \n\n TypeError: ArbitrableBlacklist.Item is not a function\n\n**Edit: Forgot to mention, I'm writing tests from Javascript**.\n\n========================================\n\nCode:\n```text\ncontract ArbitrableBlacklist {\n\n    enum ItemStatus {\n        Absent,                     \n        Cleared,                      \n    }\n\n    struct Item {\n        ItemStatus status;       \n        uint lastAction;         \n\n    }\n}\n```\n\n```text\nlet x = ArbitrableBlacklist.Item({\n        status: 0,\n        lastAction: 0\n      });\n```\n\n```text\nItem\n```\n\n```text\nItem\n```\n\n```text\npragma solidity ^0.4.22;\n\ncontract ArbitrableBlacklist {\n\n    enum ItemStatus {\n        Absent,                     \n        Cleared                    \n    }\n\n    struct Item {\n        ItemStatus status;       \n        uint lastAction;         \n\n    }\n\n}\n\ncontract test{\n\n    ArbitrableBlacklist.Item public item;\n\n    function create() public {\n        item = ArbitrableBlacklist.Item({\n           status: ArbitrableBlacklist.ItemStatus.Absent,\n           lastAction: 0\n        });\n    }\n\n}\n```\n\n```text\nfunction create(ArbitrableBlacklist.ItemStatus _status, uint _action) public {\n        item = ArbitrableBlacklist.Item({\n           status: _status,\n           lastAction: _action\n        });\n    }\n```\n\n========================================\n\nComments:\n- I'm writing tests in Javascript, so yes trying to initialize from javascript. Sorry for not mentioning that.\n- @ferit, then you can not directly pass a struct object, instead pass struct member data types like integer/string/bool etc ..then in the contract using the parameters, create struct instance.\n- So we need a function that initializes the struct in the contract, to be able to initialize the struct by calling that function from Javascript test, right?\n- @ferit, yes as of now. As Javascript has not idea about your struct","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":122,"estimatedTokens":616}}106{"id":"stack-70731492","source":"stackoverflow","questionId":70731492,"title":"The transaction declared chain ID 5777, but the connected node is on 1337","tags":["python","ethereum","solidity","smartcontracts","ganache"],"text":"Title: The transaction declared chain ID 5777, but the connected node is on 1337\nTags: python, ethereum, solidity, smartcontracts, ganache\nSource: Stack Overflow\n\nQuestion:\nI am trying to deploy my SimpleStorage.sol contract to a ganache local chain by making a transaction using python. It seems to have trouble connecting to the chain.\n\n```\nfrom solcx import compile_standard\nfrom web3 import Web3\nimport json\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nwith open(\"./SimpleStorage.sol\", \"r\") as file:\n simple_storage_file = file.read()\n\ncompiled_sol = compile_standard(\n {\n \"language\": \"Solidity\",\n \"sources\": {\"SimpleStorage.sol\": {\"content\": simple_storage_file}},\n \"settings\": {\n \"outputSelection\": {\n \"*\": {\"*\": [\"abi\", \"metadata\", \"evm.bytecode\", \"evm.sourceMap\"]}\n }\n },\n },\n solc_version=\"0.6.0\",\n)\n\nwith open(\"compiled_code.json\", \"w\") as file:\n json.dump(compiled_sol, file)\n\n# get bytecode\nbytecode = compiled_sol[\"contracts\"][\"SimpleStorage.sol\"][\"SimpleStorage\"][\"evm\"][\n \"bytecode\"\n][\"object\"]\n\n# get ABI\nabi = compiled_sol[\"contracts\"][\"SimpleStorage.sol\"][\"SimpleStorage\"][\"abi\"]\n\n# to connect to ganache blockchain\nw3 = Web3(Web3.HTTPProvider(\"HTTP://127.0.0.1:7545\"))\nchain_id = 5777\nmy_address = \"0xca1EA31e644F13E3E36631382686fD471c62267A\"\nprivate_key = os.getenv(\"PRIVATE_KEY\")\n\n# create the contract in python\n\nSimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)\n\n# get the latest transaction\nnonce = w3.eth.getTransactionCount(my_address)\n\n# 1. Build a transaction\n# 2. Sign a transaction\n# 3. Send a transaction\n\ntransaction = SimpleStorage.constructor().buildTransaction(\n {\"chainId\": chain_id, \"from\": my_address, \"nonce\": nonce}\n)\nprint(transaction)\n```\n\nIt seems to be connected to the ganache chain because it prints the nonce, but when I build and try to print the transaction\nhere is the entire traceback call I am receiving\n\n```\nTraceback (most recent call last):\nFile \"C:\\Users\\evens\\demos\\web3_py_simple_storage\\deploy.py\", line \n52, in \ntransaction = SimpleStorage.constructor().buildTransaction(\nFile \"C:\\Python310\\lib\\site-packages\\eth_utils\\decorators.py\", line \n18, in _wrapper\nreturn self.method(obj, *args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\contract.py\", line 684, in buildTransaction\nreturn fill_transaction_defaults(self.web3, built_transaction)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\_utils\\transactions.py\", line 114, in \nfill_transaction_defaults\ndefault_val = default_getter(web3, transaction)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\_utils\\transactions.py\", line 60, in \n'gas': lambda web3, tx: web3.eth.estimate_gas(tx),\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\eth.py\", line 820, in estimate_gas\nreturn self._estimate_gas(transaction, block_identifier)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\module.py\", line 57, in caller\nresult = w3.manager.request_blocking(method_str,\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\manager.py\", line 197, in request_blocking\nresponse = self._make_request(method, params)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\manager.py\", line 150, in _make_request\nreturn request_func(method, params)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\formatting.py\", line 76, in \napply_formatters\nresponse = make_request(method, params)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\gas_price_strategy.py\", line 90, in \nmiddleware\nreturn make_request(method, params)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\formatting.py\", line 74, in \napply_formatters\nresponse = make_request(method, formatted_params)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\attrdict.py\", line 33, in middleware\nresponse = make_request(method, params)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\formatting.py\", line 74, in \napply_formatters\nresponse = make_request(method, formatted_params)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\formatting.py\", line 73, in \napply_formatters\nformatted_params = formatter(params)\nFile \"cytoolz/functoolz.pyx\", line 503, in \ncytoolz.functoolz.Compose.__call__\nret = PyObject_Call(self.first, args, kwargs)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Python310\\lib\\site-packages\\eth_utils\\decorators.py\", line \n91, in wrapper\nreturn ReturnType(result) # type: ignore\nFile \"C:\\Python310\\lib\\site-packages\\eth_utils\\applicators.py\", line \n22, in apply_formatter_at_index\nyield formatter(item)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Python310\\lib\\site-packages\\eth_utils\\applicators.py\", line \n72, in apply_formatter_if\nreturn formatter(value)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\validation.py\", line 57, in \nvalidate_chain_id\nraise ValidationError(\nweb3.exceptions.ValidationError: The transaction declared chain ID \n5777, but the connected node is on 1337\n```\n\n========================================\n\nTop Answer:\nthis line of code is wrong\n\n```\nchain_id = 5777\n```\n\nGanache chain id is not 5777. This is network id. Network id is used by nodes to transfer data between nodes that are on the same network. Network id is not included in blocks and it is not used for signing transactions or mining blocks.\n\n```\nchain_id = 1377\n```\n\nChain ID is not included in blocks either, but it is used during the transaction signing and verification process.\n\n========================================\n\nCode:\n```text\nfrom solcx import compile_standard\nfrom web3 import Web3\nimport json\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nwith open(\"./SimpleStorage.sol\", \"r\") as file:\n    simple_storage_file = file.read()\n\ncompiled_sol = compile_standard(\n    {\n        \"language\": \"Solidity\",\n        \"sources\": {\"SimpleStorage.sol\": {\"content\": simple_storage_file}},\n        \"settings\": {\n            \"outputSelection\": {\n                \"*\": {\"*\": [\"abi\", \"metadata\", \"evm.bytecode\", \"evm.sourceMap\"]}\n            }\n        },\n    },\n    solc_version=\"0.6.0\",\n)\n\nwith open(\"compiled_code.json\", \"w\") as file:\n    json.dump(compiled_sol, file)\n\n\n# get bytecode\nbytecode = compiled_sol[\"contracts\"][\"SimpleStorage.sol\"][\"SimpleStorage\"][\"evm\"][\n    \"bytecode\"\n][\"object\"]\n\n\n# get ABI\nabi = compiled_sol[\"contracts\"][\"SimpleStorage.sol\"][\"SimpleStorage\"][\"abi\"]\n\n# to connect to ganache blockchain\nw3 = Web3(Web3.HTTPProvider(\"HTTP://127.0.0.1:7545\"))\nchain_id = 5777\nmy_address = \"0xca1EA31e644F13E3E36631382686fD471c62267A\"\nprivate_key = os.getenv(\"PRIVATE_KEY\")\n\n\n# create the contract in python\n\nSimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)\n\n# get the latest transaction\nnonce = w3.eth.getTransactionCount(my_address)\n\n# 1. Build a transaction\n# 2. Sign a transaction\n# 3. Send a transaction\n\n\ntransaction = SimpleStorage.constructor().buildTransaction(\n    {\"chainId\": chain_id, \"from\": my_address, \"nonce\": nonce}\n)\nprint(transaction)\n```\n\n```text\nTraceback (most recent call last):\nFile \"C:\\Users\\evens\\demos\\web3_py_simple_storage\\deploy.py\", line \n52, in <module>\ntransaction = SimpleStorage.constructor().buildTransaction(\nFile \"C:\\Python310\\lib\\site-packages\\eth_utils\\decorators.py\", line \n18, in _wrapper\nreturn self.method(obj, *args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\contract.py\", line 684, in buildTransaction\nreturn fill_transaction_defaults(self.web3, built_transaction)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\_utils\\transactions.py\", line 114, in \nfill_transaction_defaults\ndefault_val = default_getter(web3, transaction)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\_utils\\transactions.py\", line 60, in <lambda>\n'gas': lambda web3, tx: web3.eth.estimate_gas(tx),\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\eth.py\", line 820, in estimate_gas\nreturn self._estimate_gas(transaction, block_identifier)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\module.py\", line 57, in caller\nresult = w3.manager.request_blocking(method_str,\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\manager.py\", line 197, in request_blocking\nresponse = self._make_request(method, params)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\manager.py\", line 150, in _make_request\nreturn request_func(method, params)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\formatting.py\", line 76, in \napply_formatters\nresponse = make_request(method, params)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\gas_price_strategy.py\", line 90, in \nmiddleware\nreturn make_request(method, params)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\formatting.py\", line 74, in \napply_formatters\nresponse = make_request(method, formatted_params)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\attrdict.py\", line 33, in middleware\nresponse = make_request(method, params)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\formatting.py\", line 74, in \napply_formatters\nresponse = make_request(method, formatted_params)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\formatting.py\", line 73, in \napply_formatters\nformatted_params = formatter(params)\nFile \"cytoolz/functoolz.pyx\", line 503, in \ncytoolz.functoolz.Compose.__call__\nret = PyObject_Call(self.first, args, kwargs)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Python310\\lib\\site-packages\\eth_utils\\decorators.py\", line \n91, in wrapper\nreturn ReturnType(result)  # type: ignore\nFile \"C:\\Python310\\lib\\site-packages\\eth_utils\\applicators.py\", line \n22, in apply_formatter_at_index\nyield formatter(item)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Python310\\lib\\site-packages\\eth_utils\\applicators.py\", line \n72, in apply_formatter_if\nreturn formatter(value)\nFile \"cytoolz/functoolz.pyx\", line 250, in \ncytoolz.functoolz.curry.__call__\nreturn self.func(*args, **kwargs)\nFile \"C:\\Users\\evens\\AppData\\Roaming\\Python\\Python310\\site- \npackages\\web3\\middleware\\validation.py\", line 57, in \nvalidate_chain_id\nraise ValidationError(\nweb3.exceptions.ValidationError: The transaction declared chain ID \n5777, but the connected node is on 1337\n```\n\n```text\ntransaction = \n SimpleStorage.constructor().buildTransaction( {\n    \"gasPrice\": w3.eth.gas_price, \n    \"chainId\": chain_id, \n    \"from\": my_address, \n    \"nonce\": nonce, \n})\nprint(transaction)\n```\n\n```text\nchain_id = 5777\n```\n\n```text\nchain_id = 1377\n```\n\n```text\nSimpleStorage.constructor().buildTransaction( {\n    \"gasPrice\": w3.eth.gas_price, \n    \"chainId\": chain_id, \n    \"from\": my_address, \n    \"nonce\": nonce,\n```\n\n```text\ntransaction = SimpleStorage.constructor().buildTransaction(\n{\n    \"gasPrice\": w3.eth.gas_price,\n    \"chainId\": w3.eth.chain_id,\n    \"from\": my_address,\n    \"nonce\": nonce,\n}\n```\n\n```text\ntransaction = SimpleStorage.constructor().buildTransaction({ \"gasPrice\": w3.eth.gas_price, \"chainId\" : chain_id, \"from\": my_address, \"nonce\": nonce})\nprint(transaction)\n```\n\n```text\n\"gasPrice\": w3.eth.gas_price\n```\n\n```text\ntransaction = SimpleStorage.constructor().buildTransaction(\n{\n    \"gasPrice\": w3.eth.gas_price,\n    \"chainId\": int(chain_id),\n    \"from\": my_address,\n    \"nonce\": nonce,\n}\n```\n\n```text\nconst chainId = await wallet.getChainId();\nconsole.log(\"chain Id\",chainId);\n```\n\n========================================\n\nComments:\n- Awesome changed the ChainId on ganache and it worked!! Thanks\n- you're the man, I'm also working through the exact same solidity course atm! I was getting stuck in the next step already and then I saw your comment about the gas price. Thank you!\n- @DeltaChief this is a great resource for issues on the course github.com/smartcontractkit/full-blockchain-solidity-course-&zwnj;&#8203;py/&hellip; The Eth stack exchange is also good. It gets to a point where every section on the course becomes a battle to get stuff working... stay strong!\n- In case someone is confused, there is a typo above, it should be `chain_id = 1337`\n- is there a place in some setting where I Can actually > that the chain id is 1337 ?\n- @iosifv Chain ID is usually used as an identification of the network. you use chain id to tell metamask which network you are going to communicate with. you cannot change the chain id of ganache\n- I see! I thought it's similar to those cases where you choose which port is used by an app","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":421,"estimatedTokens":3635}}107{"id":"stack-48045784","source":"stackoverflow","questionId":48045784,"title":"Solidity setting a mapping to empty","tags":["ethereum","solidity","smartcontracts"],"text":"Title: Solidity setting a mapping to empty\nTags: ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a smart contract using Solidity 0.4.4.\n\nI was wondering if there is a way to set a mapping with some values already entered to an empty one?\n\nFor example:\n\nThis initailises a new mappping\n\n`mapping (uint => uint) map;`\n\nHere I add some values\n\n`map[0] = 1;`\n\n`map[1] = 2;`\n\nHow can I set the map back to empty without iterating through all the keys?\n\n**I have tried delete but my contract does not compile**\n\n========================================\n\nTop Answer:\nI believe there is another way to handle this problem.\n\nIf you define your mapping with a second key, you can increment that key to essentially reset your mapping.\n\nFor example, if you wanted to your mapping to reset every year, you could define it like this:\n\n```\nuint256 private _year = 2021;\nmapping(uint256 => mapping(address => uint256)) private _yearlyBalances;\n```\n\nAdding and retrieving values works just like normal, with an extra key:\n\n```\n_yearlyBalances[_year][0x9101910191019101919] = 1;\n_yearlyBalances[_year][0x8101810181018101818] = 2;\n```\n\nWhen it's time to reset everything, you just call\n\n```\n_year += 1\n```\n\n========================================\n\nCode:\n```text\nmapping (uint => uint) map;\n```\n\n```text\nmap[0] = 1;\n```\n\n```text\nmap[1] = 2;\n```\n\n```text\nuint256 private _year = 2021;\nmapping(uint256 => mapping(address => uint256)) private _yearlyBalances;\n```\n\n```text\n_yearlyBalances[_year][0x9101910191019101919] = 1;\n_yearlyBalances[_year][0x8101810181018101818] = 2;\n```\n\n```text\n_year += 1\n```\n\n```text\nmapping(address => FarmingData) public farmingData;\naddress[] public farmers;\n\nfunction addFarmer() external {\n    farmers.push(user);\n    FarmingData storage data = farmingData[user];\n    // ...\n}\n\n\nfunction _endFarmingPeriod() internal {\n    // Reset farming data for each user\n    for (uint i = 0; i < farmers.length; ) {\n        address user = farmers[i];\n        delete farmingData[user];\n        unchecked {\n            ++i;\n        }\n    }\n    delete farmers; // Reset the list of farmers\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":104,"estimatedTokens":534}}108{"id":"stack-55345063","source":"stackoverflow","questionId":55345063,"title":"How to return array of address in solidity?","tags":["solidity","smartcontracts"],"text":"Title: How to return array of address in solidity?\nTags: solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI am creating a smart contract in solidity ^0.5.1 in which I get the following error:\n\n```\ndata location must be a memory for the return parameter in the function, but none was given.\n```\n\nIn the below function I am getting error.\n\n```\nfunction getCitizen()public returns(address[]){\n return citizenArray;\n}\n```\n\nThe smart contract that I have tried so far.\n\n```\npragma solidity ^0.5.1;\n\ncontract Citizen{\n \n \n struct Citizens{\n \n uint age;\n string fName;\n string lName;\n \n }\n \n mapping(address => Citizens) citizenMap;\n \n address [] citizenArray;\n \n function setCitizen(address _address,uint _age,string memory _fName,string memory _lName) public{\n \n //creating the object of the structure in solidity \n Citizens storage citizen=citizenMap[_address];\n \n \n citizen.age=_age;\n citizen.fName=_fName;\n citizen.lName=_lName;\n \n citizenArray.push(_address) -1;\n \n }\n \n function getCitizen(address _address) public pure returns(uint,string memory ,string memory ){\n return(citizenMap[_address].age,citizenMap[_address].fName,citizenMap[_address].lName);\n \n }\n \n function getCitizenAddress()public returns(address[]){\n return citizenArray;\n }\n \n}\n```\n\nHow can I return the array of addresses?\n\n========================================\n\nTop Answer:\n```\n// SPDX-License-Identifier: MIT\n\n// Version\npragma solidity >=0.8.0 Customer) public myClientes;\n\n address[] public listClientes;\n\n function registrationApp(string memory _name, string memory _id, string memory _email) public {\n Customer memory customer = Customer(_name, _id, _email);\n myClientes[msg.sender] = customer; \n listClientes.push(msg.sender);\n }\n\n function retornarArrat() public view returns (address[] memory) {\n return listClientes;\n }\n\n}\n```\n\n========================================\n\nCode:\n```none\ndata location must be a memory for the return parameter in the function, but none was given.\n```\n\n```text\nfunction getCitizen()public returns(address[]){\n    return citizenArray;\n}\n```\n\n```text\npragma solidity ^0.5.1;\n\ncontract Citizen{\n    \n    \n    struct Citizens{\n        \n        uint age;\n        string fName;\n        string lName;\n        \n    }\n    \n    mapping(address => Citizens) citizenMap;\n    \n    address [] citizenArray;\n    \n    function setCitizen(address _address,uint _age,string memory _fName,string memory _lName) public{\n        \n        //creating the object of the structure in solidity \n         Citizens storage citizen=citizenMap[_address];\n        \n        \n        citizen.age=_age;\n        citizen.fName=_fName;\n        citizen.lName=_lName;\n        \n        citizenArray.push(_address) -1;\n        \n    }\n    \n    function getCitizen(address _address) public pure returns(uint,string memory ,string memory ){\n        return(citizenMap[_address].age,citizenMap[_address].fName,citizenMap[_address].lName);\n        \n    }\n    \n    function getCitizenAddress()public returns(address[]){\n        return citizenArray;\n    }\n    \n}\n```\n\n```text\nfunction getCitizenAddress()public view returns( address  [] memory){\n    return citizenArray;\n}\n```\n\n```text\nfunction getCitizen(address _address) public pure returns(uint,string memory ,string memory ){\n            return(citizenMap[_address].age,citizenMap[_address].fName,citizenMap[_address].lName);\n}\n```\n\n```text\nfunction getCitizen(address _address) public view returns(uint,string memory ,string memory ){\n    return(citizenMap[_address].age,citizenMap[_address].fName,citizenMap[_address].lName);\n\n}\n```\n\n```text\nstorage\n```\n\n```text\ncitizenArray\n```\n\n```text\nmemory\n```\n\n```text\nmemory\n```\n\n```text\nview\n```\n\n```text\npure\n```\n\n```text\npure\n```\n\n```text\nview\n```\n\n```text\nview\n```\n\n```text\npure\n```\n\n```text\ngetCitizen\n```\n\n```text\nreturn\n```\n\n```text\nview\n```\n\n```text\npure\n```\n\n```html\n// SPDX-License-Identifier: MIT\n\n// Version\npragma solidity >=0.8.0 < 0.9.0;\n\ncontract EstructuraDeDatos {\n\n    struct Customer {\n        string nameCustomer; \n        string idCustomer; \n        string emailCustomer;\n    }\n\n    mapping(address => Customer) public myClientes;\n\n    address[] public listClientes;\n\n    function registrationApp(string memory _name, string memory _id, string memory _email) public {\n        Customer memory customer = Customer(_name, _id, _email);\n        myClientes[msg.sender] = customer; \n        listClientes.push(msg.sender);\n    }\n\n    function retornarArrat() public view returns (address[] memory) {\n        return listClientes;\n    }\n\n}\n```\n\n```text\n// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.7.0 <0.9.0;\ncontract Citizen {\n  struct Citizens {\n    uint age;\n    string fName;\n    string lName;\n  }\n    \n  mapping(address => Citizens) citizenMap;\n    \n  address [] citizenArray;\n    \n  function setCitizen(address _address,uint _age,string memory _fName,string memory _lName) public {\n    // Citizens storage citizen=citizenMap[_address];\n    //creating the object of the structure in solidity \n    Citizens storage citizen;\n    citizen = citizenMap[_address];\n        \n    citizen.age=_age;\n    citizen.fName=_fName;\n    citizen.lName=_lName;\n    citizenArray.push(_address);\n  }\n    \n  function getCitizen(address _address) public view returns(uint,string memory ,string memory) {\n    return (citizenMap[_address].age,citizenMap[_address].fName,citizenMap[_address].lName);\n  }\n    \n  // function getCitizenAddress()public returns(address[]) {\n  //   return citizenArray;\n  // }\n}\n```\n\n```text\n// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.7.0 <0.9.0;\ncontract Citizen{\n    \n    \n    struct Citizens{\n        \n        uint age;\n        string fName;\n        string lName;\n        \n    }\n    \n    mapping(address => Citizens) citizenMap;\n    \n    address [] citizenArray;\n    \n    function setCitizen(address _address,uint _age,string memory _fName,string memory _lName) public{\n        // Citizens storage citizen=citizenMap[_address];\n        //creating the object of the structure in solidity \n         Citizens storage citizen;\n      citizen = citizenMap[_address];\n        \n        citizen.age=_age;\n        citizen.fName=_fName;\n        citizen.lName=_lName;\n        citizenArray.push(_address);\n\n    }\n    \n    function getCitizen(address _address) public view returns(uint,string memory ,string memory ){\n        return(citizenMap[_address].age,citizenMap[_address].fName,citizenMap[_address].lName);\n        \n    }\n    \n    function getCitizenAddress()public view returns(address[] memory){\n         return citizenArray;\n    }\n}\n```\n\n========================================\n\nComments:\n- Do you have information on how to evaluate gas used for return array with elements? Gas used by block is limited, for really big dataset in storage we might face with issue there is not enough gas in a whole block to execute this tx.\n- Your answer could be improved by adding more information on what the code does and how it helps the OP.\n- This function returns the array of addresses: ``` function retornarArrat() public view returns (address[] memory) { return listClientes; } ```","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":340,"estimatedTokens":1773}}109{"id":"stack-70104101","source":"stackoverflow","questionId":70104101,"title":"ValueError: Method eth_maxPriorityFeePerGas not supported, web3.py with ganache","tags":["python","ethereum","solidity","ganache"],"text":"Title: ValueError: Method eth_maxPriorityFeePerGas not supported, web3.py with ganache\nTags: python, ethereum, solidity, ganache\nSource: Stack Overflow\n\nQuestion:\nI'm running the following code with `web3.py`:\n\n```\ntransaction = SimpleStorage.constructor().buildTransaction(\n {\"chainId\": chain_id, \"from\": my_address, \"nonce\": nonce}\n)\n```\n\nAnd I am running into the following error:\n\n```\nTraceback (most recent call last):\n File \"/Users/patrick/code/web3_py_simple_storage/deploy.py\", line 64, in \n transaction = SimpleStorage.constructor().buildTransaction(\n File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/eth_utils/decorators.py\", line 18, in _wrapper\n return self.method(obj, *args, **kwargs)\n File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/contract.py\", line 684, in buildTransaction\n return fill_transaction_defaults(self.web3, built_transaction)\n File \"cytoolz/functoolz.pyx\", line 250, in cytoolz.functoolz.curry.__call__\n File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/_utils/transactions.py\", line 121, in fill_transaction_defaults\n default_val = default_getter(web3, transaction)\n File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/_utils/transactions.py\", line 71, in \n web3.eth.max_priority_fee + (2 * web3.eth.get_block('latest')['baseFeePerGas'])\n File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/eth.py\", line 549, in max_priority_fee\n return self._max_priority_fee()\n File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/module.py\", line 57, in caller\n result = w3.manager.request_blocking(method_str,\n File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/manager.py\", line 198, in request_blocking\n return self.formatted_response(response,\n File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/manager.py\", line 171, in formatted_response\n raise ValueError(response[\"error\"])\nValueError: {'message': 'Method eth_maxPriorityFeePerGas not supported.', 'code': -32000, 'data': {'stack': 'Error: Method eth_maxPriorityFeePerGas not supported.\\n at GethApiDouble.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/subproviders/geth_api_double.js:70:16)\\n at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\\n at GethDefaults.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/subproviders/gethdefaults.js:15:12)\\n at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\\n at SubscriptionSubprovider.FilterSubprovider.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/subproviders/filters.js:89:7)\\n at SubscriptionSubprovider.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/subproviders/subscriptions.js:137:49)\\n at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\\n at DelayedBlockFilter.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/subproviders/delayedblockfilter.js:31:3)\\n at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\\n at RequestFunnel.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/subproviders/requestfunnel.js:32:12)\\n at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\\n at Web3ProviderEngine._handleAsync (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:123:3)\\n at Timeout._onTimeout (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:107:12)\\n at listOnTimeout (internal/timers.js:531:17)\\n at processTimers (internal/timers.js:475:7)', 'name': 'Error'}}\n```\n\nHow do I fix this?\n\n========================================\n\nCode:\n```py\ntransaction = SimpleStorage.constructor().buildTransaction(\n    {\"chainId\": chain_id, \"from\": my_address, \"nonce\": nonce}\n)\n```\n\n```py\nTraceback (most recent call last):\n  File \"/Users/patrick/code/web3_py_simple_storage/deploy.py\", line 64, in <module>\n    transaction = SimpleStorage.constructor().buildTransaction(\n  File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/eth_utils/decorators.py\", line 18, in _wrapper\n    return self.method(obj, *args, **kwargs)\n  File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/contract.py\", line 684, in buildTransaction\n    return fill_transaction_defaults(self.web3, built_transaction)\n  File \"cytoolz/functoolz.pyx\", line 250, in cytoolz.functoolz.curry.__call__\n  File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/_utils/transactions.py\", line 121, in fill_transaction_defaults\n    default_val = default_getter(web3, transaction)\n  File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/_utils/transactions.py\", line 71, in <lambda>\n    web3.eth.max_priority_fee + (2 * web3.eth.get_block('latest')['baseFeePerGas'])\n  File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/eth.py\", line 549, in max_priority_fee\n    return self._max_priority_fee()\n  File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/module.py\", line 57, in caller\n    result = w3.manager.request_blocking(method_str,\n  File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/manager.py\", line 198, in request_blocking\n    return self.formatted_response(response,\n  File \"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/manager.py\", line 171, in formatted_response\n    raise ValueError(response[\"error\"])\nValueError: {'message': 'Method eth_maxPriorityFeePerGas not supported.', 'code': -32000, 'data': {'stack': 'Error: Method eth_maxPriorityFeePerGas not supported.\\n    at GethApiDouble.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/subproviders/geth_api_double.js:70:16)\\n    at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\\n    at GethDefaults.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/subproviders/gethdefaults.js:15:12)\\n    at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\\n    at SubscriptionSubprovider.FilterSubprovider.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/subproviders/filters.js:89:7)\\n    at SubscriptionSubprovider.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/subproviders/subscriptions.js:137:49)\\n    at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\\n    at DelayedBlockFilter.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/subproviders/delayedblockfilter.js:31:3)\\n    at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\\n    at RequestFunnel.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/subproviders/requestfunnel.js:32:12)\\n    at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\\n    at Web3ProviderEngine._handleAsync (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:123:3)\\n    at Timeout._onTimeout (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:107:12)\\n    at listOnTimeout (internal/timers.js:531:17)\\n    at processTimers (internal/timers.js:475:7)', 'name': 'Error'}}\n```\n\n```text\nweb3.py\n```\n\n```py\ntransaction = SimpleStorage.constructor().buildTransaction(\n    {\"chainId\": chain_id, \"gasPrice\": w3.eth.gas_price, \"from\": my_address, \"nonce\": nonce}\n)\n```\n\n```text\ngasPrice\n```\n\n========================================\n\nComments:\n- Wow, what a coincidence that I am watching your Youtube video and have met the same problem. It seems that this is caused by a recent update.\n- Amazing, we are all following chain.link youtube hahahahah","metadata":{"transformedAt":"2026-08-18T18:33:36.119Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":93,"estimatedTokens":2339}}110{"id":"stack-67893318","source":"stackoverflow","questionId":67893318,"title":"Solidity: How to represent bytes32 as string","tags":["ethereum","solidity"],"text":"Title: Solidity: How to represent bytes32 as string\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nThis may be simple in other languages but I can't figure out how to do it in Solidity.\n\nI have a `bytes32` like this `0x05416460deb76d57af601be17e777b93592d8d4d4a4096c57876a91c84f4a712`.\n\nI *don't* want to convert the bytes to a string, rather I just want to represent the whole thing as a string, like \"0x05416460deb76d57af601be17e777b93592d8d4d4a4096c57876a91c84f4a712\".\n\nHow can this be done in Solidity?\n\nUpdate:\n\nWhy I need to do this: Basically I connect to an oracle, which does some work off-chain and finally uploads a file to IPFS. I need to get the content identifier into my contract from the oracle. The oracle can only send `bytes32` as a response, so I convert it to a multihash and send only the `digest` as `bytes32` from oracle to contract.\n\nSo far so good, I can recreate the multihash in my contract. The problem is that after this I create an `ERC721` (NFT) token and I have to store some reference to the IPFS file in the metadata, which can only be in `string` format. This is where I'm stuck at the moment.\n\n========================================\n\nTop Answer:\nFunction `bytes32ToString` turns a bytes32 to hex string\n\n```\nfunction bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {\n uint8 i = 0;\n bytes memory bytesArray = new bytes(64);\n for (i = 0; i > 4);\n\n bytesArray[i] = toByte(_f);\n i = i + 1;\n bytesArray[i] = toByte(_l);\n }\n return string(bytesArray);\n}\n\nfunction toByte(uint8 _uint8) public pure returns (byte) {\n if(_uint8 < 10) {\n return byte(_uint8 + 48);\n } else {\n return byte(_uint8 + 87);\n }\n}\n```\n\n========================================\n\nCode:\n```text\nbytes32\n```\n\n```text\n0x05416460deb76d57af601be17e777b93592d8d4d4a4096c57876a91c84f4a712\n```\n\n```text\nbytes32\n```\n\n```text\ndigest\n```\n\n```text\nbytes32\n```\n\n```text\nERC721\n```\n\n```text\nstring\n```\n\n```text\nfunction toHex16 (bytes16 data) internal pure returns (bytes32 result) {\n    result = bytes32 (data) & 0xFFFFFFFFFFFFFFFF000000000000000000000000000000000000000000000000 |\n          (bytes32 (data) & 0x0000000000000000FFFFFFFFFFFFFFFF00000000000000000000000000000000) >> 64;\n    result = result & 0xFFFFFFFF000000000000000000000000FFFFFFFF000000000000000000000000 |\n          (result & 0x00000000FFFFFFFF000000000000000000000000FFFFFFFF0000000000000000) >> 32;\n    result = result & 0xFFFF000000000000FFFF000000000000FFFF000000000000FFFF000000000000 |\n          (result & 0x0000FFFF000000000000FFFF000000000000FFFF000000000000FFFF00000000) >> 16;\n    result = result & 0xFF000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000 |\n          (result & 0x00FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF0000) >> 8;\n    result = (result & 0xF000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000) >> 4 |\n          (result & 0x0F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F00) >> 8;\n    result = bytes32 (0x3030303030303030303030303030303030303030303030303030303030303030 +\n           uint256 (result) +\n           (uint256 (result) + 0x0606060606060606060606060606060606060606060606060606060606060606 >> 4 &\n           0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F) * 7);\n}\n\nfunction toHex (bytes32 data) public pure returns (string memory) {\n    return string (abi.encodePacked (\"0x\", toHex16 (bytes16 (data)), toHex16 (bytes16 (data << 128))));\n}\n```\n\n```text\nresult = bytes32 (data) & 0xFFFFFFFFFFFFFFFF000000000000000000000000000000000000000000000000 |\n      (bytes32 (data) & 0x0000000000000000FFFFFFFFFFFFFFFF00000000000000000000000000000000) >> 64;\n```\n\n```text\n0123456789abcdeffedcba9876543210\n\\______________/\\______________/\n       |               |\n       |               +---------------+\n ______V_______                  ______V_______\n/              \\                /              \\\n0123456789abcdef0000000000000000fedcba9876543210\n```\n\n```text\nresult = result & 0xFFFFFFFF000000000000000000000000FFFFFFFF000000000000000000000000 |\n      (result & 0x00000000FFFFFFFF000000000000000000000000FFFFFFFF0000000000000000) >> 32;\n```\n\n```text\n0123456789abcdef0000000000000000fedcba9876543210\n\\______/\\______/                \\______/\\______/\n   |       |                       |       |\n   |       +-------+               |       +-------+\n __V___          __V___          __V___          __V___\n/      \\        /      \\        /      \\        /      \\\n012345670000000089abcdef00000000fedcba980000000076543210\n```\n\n```text\nresult = result & 0xFFFF000000000000FFFF000000000000FFFF000000000000FFFF000000000000 |\n      (result & 0x0000FFFF000000000000FFFF000000000000FFFF000000000000FFFF00000000) >> 16;\n```\n\n```text\n012345670000000089abcdef00000000fedcba980000000076543210\n\\__/\\__/        \\__/\\__/        \\__/\\__/        \\__/\\__/\n |   |           |   |           |   |           |   |\n |   +---+       |   +---+       |   +---+       |   +---+\n V_      V_      V_      V_      V_      V_      V_      V_\n/  \\    /  \\    /  \\    /  \\    /  \\    /  \\    /  \\    /  \\\n012300004567000089ab0000cdef0000fedc0000ba980000765400003210\n```\n\n```text\nresult = result & 0xFF000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000 |\n      (result & 0x00FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF0000) >> 8;\n```\n\n```text\n012300004567000089ab0000cdef0000fedc0000ba980000765400003210\n\\/\\/    \\/\\/    \\/\\/    \\/\\/    \\/\\/    \\/\\/    \\/\\/    \\/\\/\n| |     | |     | |     | |     | |     | |     | |     | |\n| +-+   | +-+   | +-+   | +-+   | +-+   | +-+   | +-+   | +-+\nV   V   V   V   V   V   V   V   V   V   V   V   V   V   V   V\n/\\  /\\  /\\  /\\  /\\  /\\  /\\  /\\  /\\  /\\  /\\  /\\  /\\  /\\  /\\  /\\\n01002300450067008900ab00cd00ef00fe00dc00ba00980076005400320010\n```\n\n```text\nresult = (result & 0xF000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000) >> 4 |\n      (result & 0x0F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F00) >> 8;\n```\n\n```text\n01002300450067008900ab00cd00ef00fe00dc00ba00980076005400320010\n|\\  |\\  |\\  |\\  |\\  |\\  |\\  |\\  |\\  |\\  |\\  |\\  |\\  |\\  |\\  |\\\n\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\\n \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\\n | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |\n V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V\n000102030405060708090a0b0c0d0e0f0f0e0d0c0b0a09080706050403020100\n```\n\n```text\nx` = x < 10 ? '0' + x : 'A' + (x - 10)\n```\n\n```text\nx` = ('0' + x) + (x < 10 ? 0 : 'A' - '0' - 10)\nx` = ('0' + x) + (x < 10 ? 0 : 1) * ('A' - '0' - 10)\n```\n\n```text\nx` = ('0' + x) + ((x + 6) >> 4) * ('A' - '0' - 10)\nx` = (0x30 + x) + ((x + 0x06) >> 4) * 7\n```\n\n```text\nresult = bytes32 (0x3030303030303030303030303030303030303030303030303030303030303030 +\n       uint256 (result) +\n       (uint256 (result) + 0x0606060606060606060606060606060606060606060606060606060606060606 >> 4 &\n       0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F) * 7);\n```\n\n```text\n0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F\n```\n\n```text\ntoHex16\n```\n\n```text\nbytes16\n```\n\n```text\nbytes32\n```\n\n```text\ntoHex\n```\n\n```text\nbytes32\n```\n\n```text\nbytes16\n```\n\n```text\ntoHex16\n```\n\n```text\n0x\n```\n\n```text\nabi.encodePacked\n```\n\n```text\ntoHex16\n```\n\n```text\nx\n```\n\n```text\n(x < 10 ? 0 : 1)\n```\n\n```text\n((x + 6) >> 4)\n```\n\n```text\nfunction bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {\n    uint8 i = 0;\n    bytes memory bytesArray = new bytes(64);\n    for (i = 0; i < bytesArray.length; i++) {\n\n        uint8 _f = uint8(_bytes32[i/2] & 0x0f);\n        uint8 _l = uint8(_bytes32[i/2] >> 4);\n\n        bytesArray[i] = toByte(_f);\n        i = i + 1;\n        bytesArray[i] = toByte(_l);\n    }\n    return string(bytesArray);\n}\n\nfunction toByte(uint8 _uint8) public pure returns (byte) {\n    if(_uint8 < 10) {\n        return byte(_uint8 + 48);\n    } else {\n        return byte(_uint8 + 87);\n    }\n}\n```\n\n```text\nbytes32ToString\n```\n\n```text\nfunction getKeccak256(string memory _text) public pure returns(bytes32) {\n    // bytes32\n    // example: _text = hello_world\n    // result:  0x5b07e077a81ffc6b47435f65a8727bcc542bc6fc0f25a56210efb1a74b88a5ae\n    bytes32 hexBytes = keccak256(abi.encodePacked(_text));\n    \n    // uint256\n    // result: 41174386367651647791915356226295557979724762511302101813587183743367440278958\n    uint256 numHex = uint256(hexBytes); \n    console.log(\"the numHex is : \", numHex); \n\n    // string\n    // result: \"0x5b07e077a81ffc6b47435f65a8727bcc542bc6fc0f25a56210efb1a74b88a5ae\"\n    string memory hexString = Strings.toHexString(numHex);\n    console.log(\"the hexString is : \", hexString); \n\n    return keccak256(abi.encodePacked(_text)); \n}\n```\n\n```text\nuint256(bytes32Data)\n```\n\n```text\nimport \"hardhat/console.sol\";\n```\n\n========================================\n\nComments:\n- There's currently no easy way, because string is also a byte array. So you'd have to write a converter, that would create a 64-length byte array (that would later be converted to string) and fill it with each value somehow transformed to the ascii value representing the byte half. Example: half-byte `0` becomes `0x30`, half-byte `5` becomes `0x35`, half-byte `d` becomes `0x64`, etc. And then you can convert this new byte array to string... What is the reason behind the converting to string? Maybe a event log would be sufficient (so that an off-chain app could convert it more easily)?\n- Thanks for your answer! I updated my question to include why I have to do this. This indeed seems too complex for a relatively simple task, and I can only imagine how much gas this would consume... so I'm open to alternative solutions too.\n- Amazing Job at explaining that. I cam confirm to everyone that this is working in Solidity v 0.8.7 . Other functions that use byte tend to fail even when you fix the deprecation error of byte --> bytes1\n- Such an ingenious transformation, beautiful!","metadata":{"transformedAt":"2026-08-18T18:33:36.120Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":41,"totalLines":317,"estimatedTokens":2489}}111{"id":"stack-62920079","source":"stackoverflow","questionId":62920079,"title":"Does Solidity have HTTP request function?","tags":["http","request","blockchain","ethereum","solidity"],"text":"Title: Does Solidity have HTTP request function?\nTags: http, request, blockchain, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI am making a project using Ethereum.\n\nIn this project , I am making a contract called \"A\".\n\nWhen I send a message to \"A\", I want \"A\" to make a web request.\n\nIs it possible that Solidity requests using http (method GET/POST )?\n\n========================================\n\nComments:\n- Solidity cannot interact with external services. You'd need a Oracle for interacting with external API's. You could look into docs.provable.xyz/#ethereum-quick-start\n- Bonus info: Oracles are utilized for other consensus purposes. For example a random value. Blockchain nodes cannot randomly generate the same value, let alone doing it again any time they need to validate the data later on. Also, randomization can be predictable and is you have access to hardware, manipulatable. So they use trusted oracles","metadata":{"transformedAt":"2026-08-18T18:33:36.120Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":18,"estimatedTokens":232}}112{"id":"stack-67511692","source":"stackoverflow","questionId":67511692,"title":"How to receive and send USDT in a smart contract?","tags":["ethereum","solidity"],"text":"Title: How to receive and send USDT in a smart contract?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nIs there any guide or code that can serve as an example to implement the functionality where a smart contract receives and sends USDT to other addresses.\n\nI appreciate your help\n\n========================================\n\nTop Answer:\nWhen I use the code above, I got an error\n\nError: Transaction reverted: function selector was not recognized and there's no fallback function\n\nand I have no idea why\n\n```\npragma solidity ^0.8.0;\n\nimport \"hardhat/console.sol\";\n\ninterface IERC20 {\n function transfer(address _to, uint256 _value) external returns (bool);\n}\n\ncontract Greeter {\n\n string greeting;\n\n constructor(string memory _greeting) {\n console.log(\"Deploying a Greeter with greeting:\", _greeting);\n greeting = _greeting;\n }\n\n function sendUSDT(address _to, uint256 _amount) external {\n // This is the mainnet USDT contract address\n // Using on other networks (rinkeby, local, ...) would fail\n // - there's no contract on this address on other networks\n IERC20 usdt = IERC20(address(0x5FbDB2315678afecb367f032d93F642f64180aa3));\n \n // transfers USDT that belong to your contract to the specified address\n usdt.transfer(_to, _amount);\n }\n}\n```\n\nI deployed the USDT(TetherToken.sol) to my ethereum dev node.\n\n```\nconst TetherToken = artifacts.require(\"TetherToken\"); \n\ncontract('TetherToken',accounts => {\n before(async () => {\n let tetherToken = await TetherToken.at(\"0x5FbDB2315678afecb367f032d93F642f64180aa3\");\n //this address is the same as signers[1].address in hardhat\n tetherToken.transfer(\"0x70997970c51812dc3a010c7d01b50e0d17dc79c8\", web3.utils.toBN(\"1000000000\"));\n let b = await tetherToken.balanceOf(\"0x70997970c51812dc3a010c7d01b50e0d17dc79c8\")\n console.log(b.toString());\n });\n\n});\n```\n\nThe transfer method works pretty good with truffle test,\nbut when test the contract with hardhat, it failed.\n\n```\nconst { ethers, upgrades } = require(\"hardhat\");\n\nasync function main() {\n\n const signers = await ethers.getSigners();\n\n const Greeter = await hre.ethers.getContractFactory(\"Greeter\");\n const greeter = await Greeter.deploy(\"Hello, Hardhat!\");\n\n await greeter.deployed();\n\n let overrides = {\n\n // The maximum units of gas for the transaction to use\n gasLimit: 2100000,\n\n // The price (in wei) per unit of gas\n gasPrice: ethers.utils.parseUnits('8.0', 'gwei')\n\n };\n\n await greeter.connect(signers[1]).sendUSDT(signers[2].address, ethers.utils.parseUnits('100.00', 'mwei'), overrides);\n}\n\n// We recommend this pattern to be able to use async/await everywhere\n// and properly handle errors.\nmain()\n .then(() => process.exit(0))\n .catch((error) => {\n console.error(error);\n process.exit(1);\n });\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.8;\n\ninterface IERC20 {\n    function transfer(address _to, uint256 _value) external returns (bool);\n    \n    // don't need to define other functions, only using `transfer()` in this case\n}\n\ncontract MyContract {\n    // Do not use in production\n    // This function can be executed by anyone\n    function sendUSDT(address _to, uint256 _amount) external {\n         // This is the mainnet USDT contract address\n         // Using on other networks (rinkeby, local, ...) would fail\n         //  - there's no contract on this address on other networks\n        IERC20 usdt = IERC20(address(0xdAC17F958D2ee523a2206206994597C13D831ec7));\n        \n        // transfers USDT that belong to your contract to the specified address\n        usdt.transfer(_to, _amount);\n    }\n}\n```\n\n```text\napprove\n```\n\n```text\ntransfer\n```\n\n```text\nfallback()\n```\n\n```text\ntransferFrom()\n```\n\n```text\nTransfer()\n```\n\n```text\npragma solidity ^0.8.0;\n\nimport \"hardhat/console.sol\";\n\ninterface IERC20 {\n    function transfer(address _to, uint256 _value) external returns (bool);\n}\n\ncontract Greeter {\n\n  string greeting;\n\n  constructor(string memory _greeting) {\n    console.log(\"Deploying a Greeter with greeting:\", _greeting);\n    greeting = _greeting;\n  }\n\n  function sendUSDT(address _to, uint256 _amount) external {\n         // This is the mainnet USDT contract address\n         // Using on other networks (rinkeby, local, ...) would fail\n         //  - there's no contract on this address on other networks\n    IERC20 usdt = IERC20(address(0x5FbDB2315678afecb367f032d93F642f64180aa3));\n        \n        // transfers USDT that belong to your contract to the specified address\n    usdt.transfer(_to, _amount);\n  }\n}\n```\n\n```text\nconst TetherToken = artifacts.require(\"TetherToken\"); \n\ncontract('TetherToken',accounts => {\n    before(async () => {\n        let tetherToken = await TetherToken.at(\"0x5FbDB2315678afecb367f032d93F642f64180aa3\");\n        //this address is the same as signers[1].address in hardhat\n        tetherToken.transfer(\"0x70997970c51812dc3a010c7d01b50e0d17dc79c8\", web3.utils.toBN(\"1000000000\"));\n        let b = await tetherToken.balanceOf(\"0x70997970c51812dc3a010c7d01b50e0d17dc79c8\")\n        console.log(b.toString());\n    });\n\n});\n```\n\n```text\nconst { ethers, upgrades } = require(\"hardhat\");\n\nasync function main() {\n\n  const signers = await ethers.getSigners();\n\n  const Greeter = await hre.ethers.getContractFactory(\"Greeter\");\n  const greeter = await Greeter.deploy(\"Hello, Hardhat!\");\n\n  await greeter.deployed();\n\n  let overrides = {\n\n    // The maximum units of gas for the transaction to use\n    gasLimit: 2100000,\n\n    // The price (in wei) per unit of gas\n    gasPrice: ethers.utils.parseUnits('8.0', 'gwei')\n\n  };\n\n  await greeter.connect(signers[1]).sendUSDT(signers[2].address, ethers.utils.parseUnits('100.00', 'mwei'), overrides);\n}\n\n// We recommend this pattern to be able to use async/await everywhere\n// and properly handle errors.\nmain()\n  .then(() => process.exit(0))\n  .catch((error) => {\n    console.error(error);\n    process.exit(1);\n  });\n```\n\n========================================\n\nComments:\n- hi Petr, thanks for the help. Trying to execute the code, I have an error and it is the following: \"ParserError: Only state variables or file-level variables can have a docstring.\" This error about the variable \"usdt\"\n- Oh I used the multi-line comment block to split the comment for better readability in an IDE that doesn't check docblocks by default (Remix). If you remove the comment, the error will disappear.\n- hi Petr, but if I comment the line of the error the problem would pass, but then in what way can I send funds\n- I meant remove the multi-line comment starting with `&#47;**` and ending with `*&#47;` - or replace it with single-line comments like I just did in the question.\n- \" - there's no contract on this address on other networks\" Is it possible to use usdt tx in testnet's ?\n- @NikolaLukic There's no official USDT contract on testnets, so keep in mind that you need to use a copy of it that is deployed on a different address.\n- @PetrHejda ANy suggest : stackoverflow.com/questions/71603899/&hellip;\n- @PetrHejda If we want to use USDT token when deploying smart contract payment, do we use Transfer or transferFrom ? and do we need to get the approval from the address of the USDT in order to use USDT as payment? thanks\n- @DavidJay You can use `transfer()` from your contract only if you're transferring tokens from your contract address. If you want to transfer tokens from the user address, they need to `approve()` your contract as spender first, and then you can use `transferFrom()`.\n- If I understand well, with an ERC20 token using a real USDT address inside a payment function we need to implement approve then transferFrom. So Basically this line is not enough \"token.transferFrom(subscriber, plan.merchant, plan.amount)\" even by using ERC20 token like USDT or USDC. please check the pay function through this link ethereum.stackexchange.com/questions/127865/&hellip;. Do you think in my pay function I need to approve first?\n- @DavidJay The `transferFrom()` is sufficient on the side of your contract. However, before executing this function, the `subscriber` also needs to execute `approve(yourContract, amount)` on the `token` contract directly (not through your contract as an intemediary).\n- @PetrHejda for safety I wanted to use safeTransferFrom function from safeERC20 instead of transferFrom in this the smart contract I shared with you above.I Imported safeERC20 and changed \"token.transferFrom(subscriber, plan.merchant, plan.amount)\" with safeTransferFrom(token, subscriber, plan.merchant, plan.amount) and I got an error(\"Member \"safeTransferFrom\" not found or not visible after argument-dependent lookup in contract IERC20\"). Am I implementing safeTransferFrom wrong ?\n- @DavidJay It seems that your `token` variable is of type `IERC20` that does not define the `safeTransferFrom()` function... You need to change your `token` variable to type `safeERC20` that defines this function.\n- @PetrHejda When you say that the subscriber also needs to execute approve(yourContract, amount) on the token contract directly (not through your contract as an intemediary). do you mean that I should include approve(address(this), amount) inside pay function before excuting transform from ? Thanks a lot\n- @DavidJay I'm not sure what `pay` function you mean, however the user needs to invoke the `approve()` function directly - so for example through your UI. Not through your contract.\n- If I understand well I should include token.approve(address(this), amout) inside the smart contract but in the UI I should called it first I use await for this one to be confirmed then token.transferFrom will be triggered? I shared a post that describes my error in detail if you could help. thanks a lot @PetrHejda ethereum.stackexchange.com/questions/130290/&hellip;\n- @DavidJay Do not invoke the `token.approve()` from your smart contract - only from the UI. In other words, the `approve()` function needs to be executed by the user directly, not through your contract.\n- If you are using USDT(BEP20), deploy to Binance Testnet. Otherwise if it is USDT(ERC20), deploy to Ethereum Testnet.","metadata":{"transformedAt":"2026-08-18T18:33:36.123Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":251,"estimatedTokens":2507}}113{"id":"stack-52994467","source":"stackoverflow","questionId":52994467,"title":"Is it possible to store images on the Ethereum blockchain?","tags":["blockchain","ethereum","solidity","smartcontracts"],"text":"Title: Is it possible to store images on the Ethereum blockchain?\nTags: blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI'm ramping up on learning Solidity, and have some ideas. At the moment I am curious if files/images can be put on the blockchain. I'm thinking an alternative would be some hybrid approach where some stuff is on the blockchain, and some stuff is in a more traditional file storage and uses address references to grab it. One issue I foresee is gas price of file uploads.\n\n========================================\n\nTop Answer:\nNote: I tried to store that +10,000 long base64 string of a 100kb image, but it did't accept. but when i tried 1kb image, it worked.\n\nyes. This is the solidity code to do it:-\n\n```\n// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.0 string[]) public base64_images;\n function push(string memory base64_img) public {\n base64_images[i].push(base64_img);\n i++; \n }\n function returnImage(uint n) public view returns(string[] memory){\n return base64_images[n];\n }\n}\n```\n\nworking code image:\nhttps://i.sstatic.net/nmz8a.png\n\nYou can convert image to base64 and vise versa online.\nHere is NodeJS code to convert image to base64 string:\n\n```\nconst imageToBase64 = require('image-to-base64');\nconst fs=require('fs')\nimageToBase64(\"img/1kb.png\") \n .then(data => {fs.writeFile('1kb_png.md',data, (err)=>{console.log(err)})})\n .catch(err =>console.log(err))\n```\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.0 <0.9.0;\ncontract ImgStorage {\n    uint i=0;\n    mapping(uint => string[]) public base64_images;\n    function push(string memory  base64_img) public {\n        base64_images[i].push(base64_img);\n        i++;        \n    }\n    function returnImage(uint n) public view returns(string[] memory){\n        return base64_images[n];\n    }\n}\n```\n\n```text\nconst imageToBase64 = require('image-to-base64');\nconst fs=require('fs')\nimageToBase64(\"img/1kb.png\") \n    .then(data => {fs.writeFile('1kb_png.md',data, (err)=>{console.log(err)})})\n    .catch(err =>console.log(err))\n```\n\n========================================\n\nComments:\n- The same topic has been discussed on this other post \"Storing and Retrieving Data in Ethereum Blockchain\". There they are suggesting to use a distributed technology IPFS + Swarm.\n- I am wondering what could be the use case? May be user images. Other than that....?\n- I don't know you're use case, but for something like an NFT, it's more common to store a hash of the image data rather than the image itself, which can be used to prove the association to a specific image stored off-chain","metadata":{"transformedAt":"2026-08-18T18:33:36.123Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":74,"estimatedTokens":666}}114{"id":"stack-48973168","source":"stackoverflow","questionId":48973168,"title":"Solidity Syntax error - SENT","tags":["solidity"],"text":"Title: Solidity Syntax error - SENT\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI'm learning Solidity from official documentation and stack on an exercise where I create simple coin:\n\n```\npragma solidity ^0.4.20; // should actually be 0.4.21\n\n contract Coin {\n // The keyword \"public\" makes those variables\n // readable from outside.\n address public minter;\n mapping (address => uint) public balances;\n\n // Events allow light clients to react on\n // changes efficiently.\n event Sent(address from, address to, uint amount);\n\n // This is the constructor whose code is\n // run only when the contract is created.\n function Coin() public {\n minter = msg.sender;\n }\n\n function mint(address receiver, uint amount) public {\n if (msg.sender != minter) return;\n balances[receiver] += amount;\n }\n\n function send(address receiver, uint amount) public {\n if (balances[msg.sender] When i try to compile i got a syntax error on the last line:\n **emit Sent(msg.sender, receiver, amount);**\n\nI tried to compile it in Remix and VS Code but got the same error message.\n\nCan somebody help me pls?\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.20; // should actually be 0.4.21\n\n   contract Coin {\n    // The keyword \"public\" makes those variables\n    // readable from outside.\n    address public minter;\n    mapping (address => uint) public balances;\n\n    // Events allow light clients to react on\n    // changes efficiently.\n    event Sent(address from, address to, uint amount);\n\n    // This is the constructor whose code is\n    // run only when the contract is created.\n    function Coin() public {\n        minter = msg.sender;\n    }\n\n    function mint(address receiver, uint amount) public {\n        if (msg.sender != minter) return;\n        balances[receiver] += amount;\n    }\n\n    function send(address receiver, uint amount) public {\n        if (balances[msg.sender] < amount) return;\n        balances[msg.sender] -= amount;\n        balances[receiver] += amount;\n        emit Sent(msg.sender, receiver, amount);\n    }\n}\n```\n\n```text\nemit\n```\n\n```text\nSent(msg.sender, receiver, amount);\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.123Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":82,"estimatedTokens":529}}115{"id":"stack-66432758","source":"stackoverflow","questionId":66432758,"title":"Execution reverted when calling a method of my contract in NodeJs","tags":["node.js","solidity","web3js"],"text":"Title: Execution reverted when calling a method of my contract in NodeJs\nTags: node.js, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to do my own token in **Solidity** and use **Web3** to transfer a token from one account to another using `NodeJS/ExpressJS`.\n\nI have been using `Infura` with `rinkeby`.\n\nI can call my method `balanceOf`, but I cannot call `transferFrom`\n\nError:\n\nReturned error: execution reverted\n\n```\nconst express = require('express');\nconst app = express();\nconst web3 = require('web3');\n\nconst INFURA_BASE_URL = 'https://rinkeby.infura.io/v3/';\nconst INFURA_API_KEY = '........';\nweb3js = new web3(new web3.providers.HttpProvider(INFURA_BASE_URL + INFURA_API_KEY));\n\n/*\n Sender & Receiver keys\n */\nconst SENDER_PUBLIC_KEY = '........';\nconst SENDER_PRIVATE_KEY = '.......';\nconst RECEIVER_PUBLIC_KEY = '......';\n\n/*\n Contract ABI.\n */\nconst CONTRACT_ABI = [\n {\n \"constant\": true,\n \"inputs\": [],\n \"name\": \"name\",\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"string\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"constant\": false,\n \"inputs\": [\n {\n \"name\": \"_spender\",\n \"type\": \"address\"\n },\n {\n \"name\": \"_value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"approve\",\n \"outputs\": [\n {\n \"name\": \"success\",\n \"type\": \"bool\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"constant\": true,\n \"inputs\": [],\n \"name\": \"totalSupply\",\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"constant\": false,\n \"inputs\": [\n {\n \"name\": \"_from\",\n \"type\": \"address\"\n },\n {\n \"name\": \"_to\",\n \"type\": \"address\"\n },\n {\n \"name\": \"_value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"transferFrom\",\n \"outputs\": [\n {\n \"name\": \"success\",\n \"type\": \"bool\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"constant\": true,\n \"inputs\": [],\n \"name\": \"decimals\",\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint8\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"constant\": false,\n \"inputs\": [\n {\n \"name\": \"_value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"burn\",\n \"outputs\": [\n {\n \"name\": \"success\",\n \"type\": \"bool\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"constant\": true,\n \"inputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"balanceOf\",\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"constant\": false,\n \"inputs\": [\n {\n \"name\": \"_from\",\n \"type\": \"address\"\n },\n {\n \"name\": \"_value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"burnFrom\",\n \"outputs\": [\n {\n \"name\": \"success\",\n \"type\": \"bool\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"constant\": true,\n \"inputs\": [],\n \"name\": \"symbol\",\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"string\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"constant\": false,\n \"inputs\": [\n {\n \"name\": \"_to\",\n \"type\": \"address\"\n },\n {\n \"name\": \"_value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"transfer\",\n \"outputs\": [\n {\n \"name\": \"success\",\n \"type\": \"bool\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"constant\": false,\n \"inputs\": [\n {\n \"name\": \"_spender\",\n \"type\": \"address\"\n },\n {\n \"name\": \"_value\",\n \"type\": \"uint256\"\n },\n {\n \"name\": \"_extraData\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"approveAndCall\",\n \"outputs\": [\n {\n \"name\": \"success\",\n \"type\": \"bool\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"constant\": true,\n \"inputs\": [\n {\n \"name\": \"\",\n \"type\": \"address\"\n },\n {\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"allowance\",\n \"outputs\": [\n {\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"name\": \"initialSupply\",\n \"type\": \"uint256\"\n },\n {\n \"name\": \"tokenName\",\n \"type\": \"string\"\n },\n {\n \"name\": \"tokenSymbol\",\n \"type\": \"string\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"name\": \"from\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"name\": \"value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"Transfer\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"name\": \"_owner\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"name\": \"_spender\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"name\": \"_value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"Approval\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"name\": \"from\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"name\": \"value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"Burn\",\n \"type\": \"event\"\n }\n];\nconst CONTRACT_ABI_ADDRESS = '............';\n\n/*\n A controller listening at: http://localhost:3000/send\n */\napp.get('/send', async function (req, apiResponse) {\n\n // Creating contract object\n const contract = new web3js.eth.Contract(CONTRACT_ABI, CONTRACT_ABI_ADDRESS, {from: SENDER_PUBLIC_KEY});\n\n // Check the balance (working good)\n await contract.methods.balanceOf(RECEIVER_PUBLIC_KEY)\n .call()\n .then(res => {\n const str = web3.utils.fromWei(res);\n console.log('balance: ', str);\n })\n .catch(err => {\n console.log(err);\n });\n\n // Set the allowance (working)\n await contract.methods.approve(SENDER_PUBLIC_KEY, 1)\n .call()\n .then(res => {\n console.log('approve: ', res);\n })\n .catch(err => {\n console.log('Error [approve]', err);\n });\n\n // Initiate a transfer (not working)\n await contract.methods.transferFrom(SENDER_PUBLIC_KEY, RECEIVER_PUBLIC_KEY, 1)\n .call()\n .then(res => {\n console.log('transferFrom: ', res);\n })\n .catch(err => {\n console.log('Error [transferFrom]', err);\n });\n\n});\n\napp.listen(3000, () => {\n console.log(`Example app listening at http://localhost:3000`)\n})\n```\n\nMy code in Solidity here.\n\nI have been struggling for days without any progress. Cannot see where the issue is.\n\nMy goal is to transfer a token from one account to another one in NodeJS.\n\n========================================\n\nTop Answer:\nIt also revert when the caller is not owner, Also check the owner of the contract.\n\n========================================\n\nCode:\n```text\nconst express = require('express');\nconst app = express();\nconst web3 = require('web3');\n\nconst INFURA_BASE_URL = 'https://rinkeby.infura.io/v3/';\nconst INFURA_API_KEY = '........';\nweb3js = new web3(new web3.providers.HttpProvider(INFURA_BASE_URL + INFURA_API_KEY));\n\n/*\n  Sender & Receiver keys\n */\nconst SENDER_PUBLIC_KEY = '........';\nconst SENDER_PRIVATE_KEY = '.......';\nconst RECEIVER_PUBLIC_KEY = '......';\n\n/*\n  Contract ABI.\n */\nconst CONTRACT_ABI = [\n  {\n    \"constant\": true,\n    \"inputs\": [],\n    \"name\": \"name\",\n    \"outputs\": [\n      {\n        \"name\": \"\",\n        \"type\": \"string\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"view\",\n    \"type\": \"function\"\n  },\n  {\n    \"constant\": false,\n    \"inputs\": [\n      {\n        \"name\": \"_spender\",\n        \"type\": \"address\"\n      },\n      {\n        \"name\": \"_value\",\n        \"type\": \"uint256\"\n      }\n    ],\n    \"name\": \"approve\",\n    \"outputs\": [\n      {\n        \"name\": \"success\",\n        \"type\": \"bool\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"nonpayable\",\n    \"type\": \"function\"\n  },\n  {\n    \"constant\": true,\n    \"inputs\": [],\n    \"name\": \"totalSupply\",\n    \"outputs\": [\n      {\n        \"name\": \"\",\n        \"type\": \"uint256\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"view\",\n    \"type\": \"function\"\n  },\n  {\n    \"constant\": false,\n    \"inputs\": [\n      {\n        \"name\": \"_from\",\n        \"type\": \"address\"\n      },\n      {\n        \"name\": \"_to\",\n        \"type\": \"address\"\n      },\n      {\n        \"name\": \"_value\",\n        \"type\": \"uint256\"\n      }\n    ],\n    \"name\": \"transferFrom\",\n    \"outputs\": [\n      {\n        \"name\": \"success\",\n        \"type\": \"bool\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"nonpayable\",\n    \"type\": \"function\"\n  },\n  {\n    \"constant\": true,\n    \"inputs\": [],\n    \"name\": \"decimals\",\n    \"outputs\": [\n      {\n        \"name\": \"\",\n        \"type\": \"uint8\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"view\",\n    \"type\": \"function\"\n  },\n  {\n    \"constant\": false,\n    \"inputs\": [\n      {\n        \"name\": \"_value\",\n        \"type\": \"uint256\"\n      }\n    ],\n    \"name\": \"burn\",\n    \"outputs\": [\n      {\n        \"name\": \"success\",\n        \"type\": \"bool\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"nonpayable\",\n    \"type\": \"function\"\n  },\n  {\n    \"constant\": true,\n    \"inputs\": [\n      {\n        \"name\": \"\",\n        \"type\": \"address\"\n      }\n    ],\n    \"name\": \"balanceOf\",\n    \"outputs\": [\n      {\n        \"name\": \"\",\n        \"type\": \"uint256\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"view\",\n    \"type\": \"function\"\n  },\n  {\n    \"constant\": false,\n    \"inputs\": [\n      {\n        \"name\": \"_from\",\n        \"type\": \"address\"\n      },\n      {\n        \"name\": \"_value\",\n        \"type\": \"uint256\"\n      }\n    ],\n    \"name\": \"burnFrom\",\n    \"outputs\": [\n      {\n        \"name\": \"success\",\n        \"type\": \"bool\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"nonpayable\",\n    \"type\": \"function\"\n  },\n  {\n    \"constant\": true,\n    \"inputs\": [],\n    \"name\": \"symbol\",\n    \"outputs\": [\n      {\n        \"name\": \"\",\n        \"type\": \"string\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"view\",\n    \"type\": \"function\"\n  },\n  {\n    \"constant\": false,\n    \"inputs\": [\n      {\n        \"name\": \"_to\",\n        \"type\": \"address\"\n      },\n      {\n        \"name\": \"_value\",\n        \"type\": \"uint256\"\n      }\n    ],\n    \"name\": \"transfer\",\n    \"outputs\": [\n      {\n        \"name\": \"success\",\n        \"type\": \"bool\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"nonpayable\",\n    \"type\": \"function\"\n  },\n  {\n    \"constant\": false,\n    \"inputs\": [\n      {\n        \"name\": \"_spender\",\n        \"type\": \"address\"\n      },\n      {\n        \"name\": \"_value\",\n        \"type\": \"uint256\"\n      },\n      {\n        \"name\": \"_extraData\",\n        \"type\": \"bytes\"\n      }\n    ],\n    \"name\": \"approveAndCall\",\n    \"outputs\": [\n      {\n        \"name\": \"success\",\n        \"type\": \"bool\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"nonpayable\",\n    \"type\": \"function\"\n  },\n  {\n    \"constant\": true,\n    \"inputs\": [\n      {\n        \"name\": \"\",\n        \"type\": \"address\"\n      },\n      {\n        \"name\": \"\",\n        \"type\": \"address\"\n      }\n    ],\n    \"name\": \"allowance\",\n    \"outputs\": [\n      {\n        \"name\": \"\",\n        \"type\": \"uint256\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"view\",\n    \"type\": \"function\"\n  },\n  {\n    \"inputs\": [\n      {\n        \"name\": \"initialSupply\",\n        \"type\": \"uint256\"\n      },\n      {\n        \"name\": \"tokenName\",\n        \"type\": \"string\"\n      },\n      {\n        \"name\": \"tokenSymbol\",\n        \"type\": \"string\"\n      }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"nonpayable\",\n    \"type\": \"constructor\"\n  },\n  {\n    \"anonymous\": false,\n    \"inputs\": [\n      {\n        \"indexed\": true,\n        \"name\": \"from\",\n        \"type\": \"address\"\n      },\n      {\n        \"indexed\": true,\n        \"name\": \"to\",\n        \"type\": \"address\"\n      },\n      {\n        \"indexed\": false,\n        \"name\": \"value\",\n        \"type\": \"uint256\"\n      }\n    ],\n    \"name\": \"Transfer\",\n    \"type\": \"event\"\n  },\n  {\n    \"anonymous\": false,\n    \"inputs\": [\n      {\n        \"indexed\": true,\n        \"name\": \"_owner\",\n        \"type\": \"address\"\n      },\n      {\n        \"indexed\": true,\n        \"name\": \"_spender\",\n        \"type\": \"address\"\n      },\n      {\n        \"indexed\": false,\n        \"name\": \"_value\",\n        \"type\": \"uint256\"\n      }\n    ],\n    \"name\": \"Approval\",\n    \"type\": \"event\"\n  },\n  {\n    \"anonymous\": false,\n    \"inputs\": [\n      {\n        \"indexed\": true,\n        \"name\": \"from\",\n        \"type\": \"address\"\n      },\n      {\n        \"indexed\": false,\n        \"name\": \"value\",\n        \"type\": \"uint256\"\n      }\n    ],\n    \"name\": \"Burn\",\n    \"type\": \"event\"\n  }\n];\nconst CONTRACT_ABI_ADDRESS = '............';\n\n/*\n  A controller listening at: http://localhost:3000/send\n */\napp.get('/send', async function (req, apiResponse) {\n\n  // Creating contract object\n  const contract = new web3js.eth.Contract(CONTRACT_ABI, CONTRACT_ABI_ADDRESS, {from: SENDER_PUBLIC_KEY});\n\n  // Check the balance (working good)\n  await contract.methods.balanceOf(RECEIVER_PUBLIC_KEY)\n    .call()\n    .then(res => {\n      const str = web3.utils.fromWei(res);\n      console.log('balance: ', str);\n    })\n    .catch(err => {\n      console.log(err);\n    });\n\n  // Set the allowance (working)\n  await contract.methods.approve(SENDER_PUBLIC_KEY, 1)\n  .call()\n  .then(res => {\n     console.log('approve: ', res);\n   })\n  .catch(err => {\n     console.log('Error [approve]', err);\n   });\n\n  // Initiate a transfer (not working)\n  await contract.methods.transferFrom(SENDER_PUBLIC_KEY, RECEIVER_PUBLIC_KEY, 1)\n    .call()\n    .then(res => {\n      console.log('transferFrom: ', res);\n    })\n    .catch(err => {\n      console.log('Error [transferFrom]', err);\n    });\n\n});\n\napp.listen(3000, () => {\n  console.log(`Example app listening at http://localhost:3000`)\n})\n```\n\n```text\nNodeJS/ExpressJS\n```\n\n```text\nInfura\n```\n\n```text\nrinkeby\n```\n\n```text\nbalanceOf\n```\n\n```text\ntransferFrom\n```\n\n```text\ncontract.methods.somFunc().send({from: ....})\n```\n\n```text\n_value <= allowance[_from][msg.sender]\n```\n\n```text\nallowance\n```\n\n```text\ntransferFrom()\n```\n\n```text\napprove()\n```\n\n```text\ntransfer()\n```\n\n```text\ncall()\n```\n\n```text\n.send({from: <senderAddress>})\n```\n\n========================================\n\nComments:\n- Thanks for your reply. I have tried to call `approve()` before `transferFrom`, but I received the same error message. Check my question edited with the use of `approve()`. Something about the `send()`, I'm not sure if I should use it on my three methods in my NodeJs code. Tried to use it only with `transferFrom` but received a different error. Can you give check again and give me another hand?\n- Yes, you should use the `send({from: ...})` instead of the `call()`... The naming is a bit unfortunate, but I'll try to simply describe: `call()` in JS is used for read-only. Whenever you need to write data to the blockchain (using external or public function of a contract), you need to send an Ethereum transaction - which is done using the `send()` function in JS.\n- Got it. I have used `.send({from: SENDER_PUBLIC_KEY})` on my three calls, but the `transferFrom()` method returns `The method eth_sendTransaction does not exist&#47;is not available`. Weird since I don't have a method in my contract with that name. Do you know how can I workaround this new error? Thanks for all your help by the way.\n- You're on the right path. `eth_sendTransaction` is a JSON-RPC method of the node that you're calling (in your case some of Infura's nodes). Which means, the flow has gone through the JS code, generated Ethereum tx, submit the tx to the node, and now the node refuses it... This is already out of my expertise, but my guess is that you have some incorrect credentials connecting to the node (since Infura is widely-used provider and it's unlikely they would have restricted this).\n- Apparently, Infura don't allow to send an unsigned transaction. A topic here. Seems that there is a lot of work that I need to do, sign, serialize and send. I'm not sure in what part of my code should I do this, I suppose it's before calling the `transferFrom()` method? I don't understand the correct steps and what need to be done first.\n- It should be enough to set the private key (or mnemonic phrase and key index) and pass it to web3 as the default account. See github.com/ChainSafe/web3.js/issues/1527#issuecomment-395987&zwnj;&#8203;528 ... Web3 then should be able to sign the transaction with this key automatically.\n- Nice. We are in the right path now. I have tried it and received an error saying `gas is missing` so, I added it and now I receives the error `Please pass numbers as string or BN objects to avoid precision errors`. I'm passing the gas as `string` so, don't understand the error. Could you check my code updated here at line 354 to 370? Maybe I'm missing something that I don't see.\n- I'm guessing the \"gas is missing\" is related to the transactions sent by `send()` functions on lines 374, 385 and 395. Unfortunately I don't have the capacity to debug the whole thing right now, but I'm glad that we've solved the original issue and that you're making progress.\n- Thanks for your help to fix the original issue. Now I am in the right path.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:36.123Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":872,"estimatedTokens":4262}}116{"id":"stack-70027236","source":"stackoverflow","questionId":70027236,"title":"Type address is not implicitly convertible to expected type address payable. owner = msg.sender","tags":["solidity"],"text":"Title: Type address is not implicitly convertible to expected type address payable. owner = msg.sender\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI'm getting this error when compiling. I know it's related to v8 and I need to make them payable, and I did but still doesn't work. can a good samaritan help?\n\n```\ncontract FundMe {\n \n mapping(address =>uint256) public addressToAmountFunded;\n \n address payable[] public funders;\n \n address payable public owner;\n \n constructor() public {\n owner = msg.sender; //LINE WITH ERROR\n }\n \n function fund() public payable {\n uint256 minimumUSD = 50 * 10 ** 18; \n \n require(getConversionRate(msg.value) >= minimumUSD, \"you need to spend more ETH my friend\");\n \n addressToAmountFunded[msg.sender] += msg.value;\n \n funders.push(msg.sender); //ERROR AS WELL\n \n }\n```\n\n========================================\n\nCode:\n```text\ncontract FundMe {\n    \n    mapping(address =>uint256) public addressToAmountFunded;\n    \n    address payable[] public funders;\n    \n    address payable public owner;\n    \n    constructor() public {\n        owner = msg.sender; //LINE WITH ERROR\n    }\n    \n    function fund() public payable {\n        uint256 minimumUSD = 50 * 10 ** 18; \n        \n        require(getConversionRate(msg.value) >= minimumUSD, \"you need to spend more ETH my friend\");\n        \n        addressToAmountFunded[msg.sender] += msg.value;\n        \n        funders.push(msg.sender); //ERROR AS WELL\n        \n    }\n```\n\n```text\npayable(msg.sender)\n```\n\n========================================\n\nComments:\n- yes. that was it....thanks!\n- @NatSerrano Hi Nat, mind accepting this answer? Mark it as accepted would help people find it out easier.","metadata":{"transformedAt":"2026-08-18T18:33:36.123Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":69,"estimatedTokens":420}}117{"id":"stack-51664226","source":"stackoverflow","questionId":51664226,"title":"Solidity error: Expected identifier, got 'LParen'","tags":["solidity"],"text":"Title: Solidity error: Expected identifier, got 'LParen'\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI'm getting the error:\n\n```\nExpected identifier, got 'LParen'\n```\n\nProblem is, this code is from the Solidity docs! I have tried many thing for this error but to no avail. The link where I got the code is: https://solidity.readthedocs.io/en/latest/solidity-by-example.html\n\nI have an image attached with the error:\n\nhttps://i.sstatic.net/sJoHg.png\n\nCan someone explain to me what I'm doing wrong? I have the right version, as per below:\n\nkalyan@kalyan:/usr/bin$ truffle version\n\nTruffle v4.1.13 (core: 4.1.13)\n\nSolidity v0.4.24 (solc-js)\n\nThis is running on Ubuntu 18.04. Is there something else I should be doing?\n\n**EDIT**\n\nThe code before constructor is:\n\n```\n/// Modifiers are a convenient way to validate inputs to\n/// functions. `onlyBefore` is applied to `bid` below:\n/// The new function body is the modifier's body where\n/// `_` is replaced by the old function body.\nmodifier onlyBefore(uint _time) { require(now _time); _; }\n```\n\n========================================\n\nTop Answer:\nI have faced this problem with the constructor in solidity too this can be solved really easily\n\nif you are running your code in ***VSCODE*** than you may have installed a extension \n**Solidity Extended**\n\n### \n\nthen you have then \n**UNININSTALL** it and reload your vscode editor\n\n if you may have uinstalled and not reloaded your vs code than you will\n face same problem\n\n```\n> also set the pragma solidity version to pragma solidity >=0.4.21 this worked for me\n\n========================================\n\nCode:\n```text\nExpected identifier, got 'LParen'\n```\n\n```text\n/// Modifiers are a convenient way to validate inputs to\n/// functions. `onlyBefore` is applied to `bid` below:\n/// The new function body is the modifier's body where\n/// `_` is replaced by the old function body.\nmodifier onlyBefore(uint _time) { require(now < _time); _; }\nmodifier onlyAfter(uint _time) { require(now > _time); _; }\n```\n\n```text\nTruffle v4.1.14 (core: 4.1.14)\nSolidity v0.4.24 (solc-js)\n```\n\n```text\nsolc, the solidity compiler commandline interface\nVersion: 0.4.19+commit.e67f0147.Darwin.appleclang\n```\n\n```text\nbrew update\nbrew upgrade\nbrew tap ethereum/ethereum\nbrew install solidity\nbrew linkapps solidity\n```\n\n```text\ntruffle version\n```\n\n```text\nsolc --version\n```\n\n```text\n> also set the pragma solidity version to pragma solidity >=0.4.21 < 0.7.0;\n```\n\n========================================\n\nComments:\n- What is the code before the constructor in your file?\n- I put the code there. It's the `BlindAuction` class in the example docs.\n- Are you compiling via command line? Aside from the shadow declaration of `bid` (which they should fix), it works in Remix.\n- Yeah, I'm seeing the same as Adam. It works fine for me in remix and solc\n- Please provide the exact code that you are trying to compile in its entirety.\n- Can you show how to do that please?\n- I simply removed the Solidity Extended plugin and it asked the VS Code reload, which i did, and then it worked fine.","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":114,"estimatedTokens":767}}118{"id":"stack-62073437","source":"stackoverflow","questionId":62073437,"title":"How to make an API call in solidity?","tags":["ethereum","solidity","smartcontracts"],"text":"Title: How to make an API call in solidity?\nTags: ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI have a smart contract that I’m trying to make, it pays out the winners of my League of Legends tournament. However I’m running into an issue. I need to make an API call to get the winner of the match, I have a simple URL that I’ve make.\n\n```\n\"example-winner.com/winner\"\n```\n\nAnd it returns simple JSON with the address of the winner:\n\n```\n{\"winner\":\"0xa7D0.......\"}\n```\n\nHowever, I’m not sure how to make the API call to the outside function. I know I need to use some sort of oracle technology.\n\nAny thoughts? Below is my code:\n\n```\npragma solidity ^0.4.24;\ncontract LeagueWinners{\n address public manager;\n address[] public players;\n uint256 MINIMUM = 1000000000000000;\n constructor() public{\n manager = msg.sender;\n }\n function enter() public payable{\n assert(msg.value > MINIMUM);\n players.push(msg.sender);\n }\n function getWinner() public{\n assert(msg.sender == manager);\n // TODO\n // Get the winner from the API call\n result = 0; // the result of the API call\n players[result].transfer(address(this).balance);\n // returns an adress object\n // all units of transfer are in wei\n players = new address[](0);\n // this empties the dynamic array\n }\n}\n```\n\n========================================\n\nTop Answer:\nYou cannot. The vm does not have any I/O outside of the blockchain itself. Instead you will need to tell your smart contract who the winner is and then the smart contract can just read the value of that variable.\n\nThis design pattern is also known as the \"oracle\". Google \"Ethereum oracle\" for more info.\n\nBasically your web server can call your smart contract. Your smart contract cannot call your web server. If you need your smart contract to access a 3rd party service then your web server will need to make the request then forward the result to solidity by calling a function in your smart contract.\n\n========================================\n\nCode:\n```text\n\"example-winner.com/winner\"\n```\n\n```text\n{\"winner\":\"0xa7D0.......\"}\n```\n\n```text\npragma solidity ^0.4.24;\ncontract LeagueWinners{\n    address public manager;\n    address[] public players;\n    uint256 MINIMUM = 1000000000000000;\n    constructor() public{\n        manager = msg.sender;\n    }\n    function enter() public payable{\n        assert(msg.value > MINIMUM);\n        players.push(msg.sender);\n    }\n    function getWinner() public{\n        assert(msg.sender == manager);\n        // TODO\n        // Get the winner from the API call\n        result = 0; // the result of the API call\n        players[result].transfer(address(this).balance);\n        // returns an adress object\n        // all units of transfer are in wei\n        players = new address[](0);\n        // this empties the dynamic array\n    }\n}\n```\n\n```text\nfunction getWinner() \n    public\n    onlyOwner\n  {\n    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);\n    req.add(\"get\", \"example-winner.com/winner\");\n    req.add(\"path\", \"winner\");\n    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);\n  }\n```\n\n```text\naddress ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;\nbytes32 JOB= \"c179a8180e034cf5a341488406c32827\";\n```\n\n```text\npragma solidity ^0.6.0;\n\nimport \"github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol\";\n\n\ncontract GetData is ChainlinkClient {\n    uint256 indexOfWinner;\n    address public manager;\n    address payable[] public players;\n    uint256 MINIMUM = 1000000000000000;\n  \n  // The address of an oracle \n    address ORACLE=0x83F00b902cbf06E316C95F51cbEeD9D2572a349a;\n    //bytes32 JOB= \"93fedd3377a54d8dac6b4ceadd78ac34\";\n    bytes32 JOB= \"c179a8180e034cf5a341488406c32827\";\n    uint256 ORACLE_PAYMENT = 1 * LINK;\n\n  constructor() public {\n    setPublicChainlinkToken();\n    manager = msg.sender;\n  }\n\nfunction getWinnerAddress() \n    public\n    onlyOwner\n  {\n    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);\n    req.add(\"get\", \"example-winner.com/winner\");\n    req.add(\"path\", \"winner\");\n    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);\n  }\n\n  // When the URL finishes, the response is routed to this function\n  function fulfill(bytes32 _requestId, uint256 _index)\n    public\n    recordChainlinkFulfillment(_requestId)\n  {\n    indexOfWinner = _index;\n    assert(msg.sender == manager);\n    players[indexOfWinner].transfer(address(this).balance);\n    players = new address payable[](0);\n  }\n  \n  function enter() public payable{\n        assert(msg.value > MINIMUM);\n        players.push(msg.sender);\n    } \n    \n  modifier onlyOwner() {\n    require(msg.sender == manager);\n    _;\n  }\n    \n    // Allows the owner to withdraw their LINK on this contract\n  function withdrawLink() external onlyOwner() {\n    LinkTokenInterface _link = LinkTokenInterface(chainlinkTokenAddress());\n    require(_link.transfer(msg.sender, _link.balanceOf(address(this))), \"Unable to transfer\");\n  }\n  \n  \n}\n```\n\n```text\nfunction bytes32ToStr(bytes32 _bytes32) public pure returns (string memory) {\n     bytes memory bytesArray = new bytes(32);\n     for (uint256 i; i < 32; i++) {\n         bytesArray[i] = _bytes32[i];\n         }\n     return string(bytesArray);\n     }\n```\n\n```text\nuint256\n```\n\n```text\nhttp.get\n```\n\n```text\nuint256\n```\n\n```text\npragma solidity ^0.4.24;\ncontract LeagueWinners{\n    address public manager;\n    //address[] public players;\n    uint256 MINIMUM = 1000000000000000;\n    constructor() public{\n        manager = msg.sender;\n    }\n\n    struct Player {\n        address playerAddress;\n        uint score;\n    }\n\n    Player[] public players;\n\n\n    // i prefer passing arguments this way\n    function enter(uint value) public payable{\n        assert(msg.value > MINIMUM);\n        players.push(Player(msg.sender, value));\n    }\n\n    //call this to get the address of winner\n    function winningPlayer() public view\n            returns (address winner)\n    {\n        uint winningScore = 0;\n        for (uint p = 0; p < players.length; p++) {\n            if (players[p].score > winningScore) {\n                winningScore = players[p].score;\n                winner = players[p].playerAddress;\n            }\n        }\n    }\n\n    // call this to transfer fund\n    function getWinner() public{\n        require(msg.sender == manager, \"Only a manager is allowed to perform this operation\");\n        // TODO\n\n        address winner = winningPlayer();\n        // Get the winner from the API call\n        //uint result = 0; // the result of the API call\n        winner.transfer(address(this).balance);\n        // returns an adress object\n        // all units of transfer are in wei\n        delete players;\n        // this empties the dynamic array\n    }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":251,"estimatedTokens":1693}}119{"id":"stack-45364197","source":"stackoverflow","questionId":45364197,"title":"How to detect if an Ethereum address is an ERC20 token contract?","tags":["ethereum","solidity","erc20"],"text":"Title: How to detect if an Ethereum address is an ERC20 token contract?\nTags: ethereum, solidity, erc20\nSource: Stack Overflow\n\nQuestion:\nIf I only get an Ethereum address from the input, is there a way to find out whether it matches the ERC20 token standard?\n\n========================================\n\nTop Answer:\nIf you are asking about off-chain, so use these functions:\n\n```\ngetContract(url, smartContractAddress){\n const Web3Eth = require('web3-eth');\n\n const abi_ = this.getABI();\n const web3Eth = new Web3Eth(Web3Eth.givenProvider || url);\n return new web3Eth.Contract(abi_, smartContractAddress);\n}\n\nasync getERCtype(contract){\n const is721 = await contract.methods.supportsInterface('0x80ac58cd').call();\n if(is721){\n return \"ERC721\";\n }\n const is1155 = await contract.methods.supportsInterface('0xd9b67a26').call();\n if(is1155){\n return \"ERC1155\";\n }\n return undefined;\n}\n\ngetABI(){\n return [ \n {\"constant\":true,\"inputs\": [\n {\"internalType\":\"bytes4\",\"name\": \"\",\"type\": \"bytes4\"}],\n \"name\": \"supportsInterface\",\n \"outputs\": [{\"internalType\":\"bool\",\"name\": \"\",\"type\": \"bool\"}],\n \"payable\": false,\"stateMutability\":\"view\",\"type\": \"function\"} \n ];\n}\n```\n\nlike this:\n\n```\nconst contract = getContract(url, smartContractAddress);\nconst type = await getERCtype(contract);\nconsole.log(type);\n```\n\n========================================\n\nCode:\n```text\nbytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;\n/*\n * 0x80ac58cd ===\n *   bytes4(keccak256('balanceOf(address)')) ^\n *   bytes4(keccak256('ownerOf(uint256)')) ^\n *   bytes4(keccak256('approve(address,uint256)')) ^\n *   bytes4(keccak256('getApproved(uint256)')) ^\n *   bytes4(keccak256('setApprovalForAll(address,bool)')) ^\n *   bytes4(keccak256('isApprovedForAll(address,address)')) ^\n *   bytes4(keccak256('transferFrom(address,address,uint256)')) ^\n *   bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^\n *   bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))\n */\n```\n\n```text\n// you can call this in your contracts\nIERC721(contractAddress).supportsInterface(0x80ac58cd)\n```\n\n```text\nbytes4\n```\n\n```text\neth.call({to:contractAddress, data:web3.sha3(\"balanceOf(address)\")})\n```\n\n```text\n0x\n```\n\n```text\nuint\n```\n\n```text\ntotalSupply()\n```\n\n```text\ngetContract(url, smartContractAddress){\n    const Web3Eth = require('web3-eth');\n\n    const abi_ = this.getABI();\n    const web3Eth = new Web3Eth(Web3Eth.givenProvider || url);\n    return new web3Eth.Contract(abi_, smartContractAddress);\n}\n\nasync getERCtype(contract){\n    const is721 = await contract.methods.supportsInterface('0x80ac58cd').call();\n    if(is721){\n        return \"ERC721\";\n    }\n    const is1155 = await contract.methods.supportsInterface('0xd9b67a26').call();\n    if(is1155){\n        return \"ERC1155\";\n    }\n    return undefined;\n}\n\ngetABI(){\n    return [         \n        {\"constant\":true,\"inputs\": [\n                {\"internalType\":\"bytes4\",\"name\": \"\",\"type\": \"bytes4\"}],\n            \"name\": \"supportsInterface\",\n            \"outputs\": [{\"internalType\":\"bool\",\"name\": \"\",\"type\": \"bool\"}],\n            \"payable\": false,\"stateMutability\":\"view\",\"type\": \"function\"}         \n    ];\n}\n```\n\n```text\nconst contract = getContract(url, smartContractAddress);\nconst type = await getERCtype(contract);\nconsole.log(type);\n```\n\n```text\nERC165\n```\n\n========================================\n\nComments:\n- Please post what you have tried already. Is this intended to work on-chain (inside a smart contract) or off chain (maybe using web3js)?\n- I am thinking what is eth here?\n- @MrHash I think the OP was asking for a way to do this in solidity.","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":144,"estimatedTokens":899}}120{"id":"stack-59448336","source":"stackoverflow","questionId":59448336,"title":"Check that object is null in solidity mapping","tags":["ethereum","solidity"],"text":"Title: Check that object is null in solidity mapping\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI have this solidity mapping\n\n```\nmapping (string => Ticket) public myMapping;\n```\n\nI want to check if `myMapping[key]` exists or not. How can I check?\n\n========================================\n\nTop Answer:\nThere is no direct method to check whether the mapping has particular key. But you can check if mapping property has value or not. The following example considered that the `Ticket` is the struct with some property. \n\n```\npragma solidity >=0.4.21 Ticket) myMapping;\n\n function isExists(string memory key) public view returns (bool) {\n\n if(myMapping[key].seatNumber != 0){\n return true;\n } \n return false;\n }\n\n function add(string memory key, uint seatNumber) public returns (bool){ \n myMapping[key].seatNumber = seatNumber; \n return true;\n }\n}\n```\n\n========================================\n\nCode:\n```text\nmapping (string => Ticket) public myMapping;\n```\n\n```text\nmyMapping[key]\n```\n\n```text\npragma solidity >=0.4.21 <0.6.0;\n\ncontract Test {\n\n    struct Ticket {\n       uint seatNumber;\n    }\n\n    mapping (string => Ticket) myMapping;\n\n    function isExists(string memory key) public view returns (bool) {\n\n        if(myMapping[key].seatNumber != 0){\n            return true;\n        } \n        return false;\n    }\n\n    function add(string memory key, uint seatNumber) public returns (bool){            \n        myMapping[key].seatNumber = seatNumber;            \n        return true;\n    }\n}\n```\n\n```text\nTicket\n```\n\n```text\npragma solidity ^0.8.0;\ncontract BookLibNew{\n\n    address public owner;\n\n    constructor() public{\n        owner = msg.sender;\n    }\n    modifier onlyOwner(){\n        require(msg.sender == owner);\n        _;\n    }\n\n    struct bookDet{\n        uint bookId;\n        string bookTitle;\n        string bookAuthor;\n    }\n\n    mapping (uint8 => bookDet) public bookLib;\n    function addBookLib(uint8 _bookId, string memory _bookTitle, string memory _bookAuthor) \n    public onlyOwner {\n        require(bookLib(_bookId) == false, \"Error: Book already exists\");\n        bookLib[_bookId].bookTitle = _bookTitle;\n        bookLib[_bookId].bookAuthor = _bookAuthor;\n    }\n\n    function readBookDetails(uint8 _bookId) public view returns(string memory, string memory){\n        return(bookLib[_bookId].bookTitle, bookLib[_bookId].bookAuthor);\n    }\n}\n```\n\n========================================\n\nComments:\n- I am getting type error in this is line of code \"require(bookLib(_bookId) == false, \"Error: Book already exists\");\" here i trying to check whether the book has already added or not. How can i check here?\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":116,"estimatedTokens":731}}121{"id":"stack-71254497","source":"stackoverflow","questionId":71254497,"title":"Documentation for ethers.getContractAt()","tags":["solidity","web3js","ethers.js","hardhat"],"text":"Title: Documentation for ethers.getContractAt()\nTags: solidity, web3js, ethers.js, hardhat\nSource: Stack Overflow\n\nQuestion:\nCan somebody please point me to the documentation (official or otherwise ) that explains the function `ethers.getContractAt():`\n\nthe original context of this is as follows:\n\n```\nvrfCoordinator = await ethers.getContractAt('VRFCoordinatorMock', VRFCoordinatorMock.address, signer)\n```\n\nand the full code can be found here...\nhttps://github.com/PatrickAlphaC/all-on-chain-generated-nft/blob/main/deploy/02_Deploy_RandomSVG.js\n\nIn the absence of such documentation, an explanation would be much appreciated. Thank you!\n\n========================================\n\nTop Answer:\nBasically, it is doing the same thing, that `attach` do but in one line. i.e you can actually interact with an already deployed contract.\n\nFor reference below is the code if you are using `attach`\n\n```\nlet xyzContract = await hre.ethers.getContractFactory(\"Name of the contract\");\nlet xyzContractInstance = xyzContract.attach('Address of the contract');\n```\n\nYou can accomplish the same thing in one line via `getContractAt()` when using hardhat\n\n```\nlet xyzContractInstance = await hre.ethers.getContractAt(\n \"Contract Name\",\n deployed contract address\n );\n```\n\n========================================\n\nCode:\n```text\nvrfCoordinator = await ethers.getContractAt('VRFCoordinatorMock', VRFCoordinatorMock.address, signer)\n```\n\n```text\nethers.getContractAt():\n```\n\n```text\ngetContractAt()\n```\n\n```text\nhardhat-ethers\n```\n\n```text\nethers\n```\n\n```text\nlet xyzContract = await hre.ethers.getContractFactory(\"Name of the contract\");\nlet xyzContractInstance = xyzContract.attach('Address of the contract');\n```\n\n```text\nlet xyzContractInstance = await hre.ethers.getContractAt(\n        \"Contract Name\",\n        deployed contract address\n    );\n```\n\n```text\nattach\n```\n\n```text\nattach\n```\n\n```text\ngetContractAt()\n```\n\n========================================\n\nComments:\n- will hit this issue after added this line `Module not found: Can't resolve 'async_hooks' in 'C:\\Users\\nick_\\VSCodeProjects\\xxx\\nft\\node_modules\\undici\\l&zwnj;&#8203;ib\\api'`.\n- should be await hre.ethers.getContractAt( \"Contract Name\", deployed contract address );","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":91,"estimatedTokens":557}}122{"id":"stack-53795971","source":"stackoverflow","questionId":53795971,"title":"Solidity - Solidity code to Input JSON Description","tags":["npm","ethereum","solidity","smartcontracts"],"text":"Title: Solidity - Solidity code to Input JSON Description\nTags: npm, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI want to compile my ethereum HelloWorld.sol smart contract. In all the tutorials is that you do it like this:\n\n```\nvar solc = require('solc');\nvar compiledContract = solc.compile(fs.readFileSync('HelloWorld.sol').toString();\n```\n\nwhere HelloWorld.sol is:\n\n```\npragma solidity ^0.5.1;\n\ncontract HelloWorld {\n bytes32 message;\n constructor(bytes32 myMessage) public {\n message = myMessage;\n }\n\n function getMessage() public view returns(bytes32){\n return message;\n }\n}\n```\n\nIn other words, I put my raw Solidity contract code into the solc.compile() method. But this process gives me this error in `compiledContract`:\n\n```\n'{\"errors\":[{\"component\":\"general\",\"formattedMessage\":\"* Line 1, Column 1\\\\n Syntax error: value, object or array expected.\\\\n* Line 1, Column 2\\\\n Extra non-whitespace after JSON value.\\\\n\",\"message\":\"* Line 1, Column 1\\\\n Syntax error: value, object or array expected.\\\\n* Line 1, Column 2\\\\n Extra non-whitespace after JSON value.\\\\n\",\"severity\":\"error\",\"type\":\"JSONError\"}]}'\n```\n\nI was looking for a solution for quite a long time, but the only thing I found is that\n\n\"The high-level API consists of a single method, compile, which\nexpects the Compiler Standard Input and Output JSON.\"\n\n(link). The standard input JSON looks like some combination of JSON and this solidity code. So my question is -\n\nHow to transfer the solidity contract code into a compiler standard input JSON?\n\nAm I correct that this is the only way how to compile the contract?\n\n========================================\n\nTop Answer:\nAlternatively, you can run the solc (command line tool) with the below command and with input data\n\n```\nsolc --standard-json -o outputDirectory --bin --ast --asm HelloWorld.sol\n```\n\nWhere in the above command when --standard-json expects a input json file that you can give.\n\nYou can find an example of how an input file should be in the below link. \n\nSource: https://solidity.readthedocs.io/en/v0.4.24/using-the-compiler.html\n\n========================================\n\nCode:\n```text\nvar solc = require('solc');\nvar compiledContract = solc.compile(fs.readFileSync('HelloWorld.sol').toString();\n```\n\n```text\npragma solidity ^0.5.1;\n\ncontract HelloWorld {\n    bytes32 message;\n    constructor(bytes32 myMessage) public {\n        message = myMessage;\n    }\n\n    function getMessage() public view returns(bytes32){\n        return message;\n    }\n}\n```\n\n```text\n'{\"errors\":[{\"component\":\"general\",\"formattedMessage\":\"* Line 1, Column 1\\\\n  Syntax error: value, object or array expected.\\\\n* Line 1, Column 2\\\\n  Extra non-whitespace after JSON value.\\\\n\",\"message\":\"* Line 1, Column 1\\\\n  Syntax error: value, object or array expected.\\\\n* Line 1, Column 2\\\\n  Extra non-whitespace after JSON value.\\\\n\",\"severity\":\"error\",\"type\":\"JSONError\"}]}'\n```\n\n```text\ncompiledContract\n```\n\n```text\nconst solc = require('solc')\nconst fs = require('fs')\n\nconst CONTRACT_FILE = 'HelloWorld.sol'\n\nconst content = fs.readFileSync(CONTRACT_FILE).toString()\n\nconst input = {\n  language: 'Solidity',\n  sources: {\n    [CONTRACT_FILE]: {\n      content: content\n    }\n  },\n  settings: {\n    outputSelection: {\n      '*': {\n        '*': ['*']\n      }\n    }\n  }\n}\n\nconst output = JSON.parse(solc.compile(JSON.stringify(input)))\n\nfor (const contractName in output.contracts[CONTRACT_FILE]) {\n  console.log(output.contracts[CONTRACT_FILE][contractName].evm.bytecode.object)\n}\n```\n\n```text\ncontract HelloWorld {\n    bytes32 message;\n    constructor(bytes32 myMessage) public {\n        message = myMessage;\n    }\n\n    function getMessage() public view returns(bytes32){\n        return message;\n    }\n}\n```\n\n```text\nsolc --standard-json   -o outputDirectory --bin --ast --asm HelloWorld.sol\n```\n\n```text\nconst solc = require(\"solc\");\n\n// file system - read and write files to your computer\nconst fs = require(\"fs\");\n\n// reading the file contents of the smart  contract\nconst fileContent = fs.readFileSync(\"HelloWorld.sol\").toString();\n\n// create an input structure for my solidity compiler\nvar input = {\n  language: \"Solidity\",\n  sources: {\n    \"HelloWorld.sol\": {\n      content: fileContent,\n    },\n  },\n\n  settings: {\n    outputSelection: {\n      \"*\": {\n        \"*\": [\"*\"],\n      },\n    },\n  },\n};\n\nvar output = JSON.parse(solc.compile(JSON.stringify(input)));\n// console.log(\"Output: \", output);\n\nconst ABI = output.contracts[\"HelloWorld.sol\"][\"Demo\"].abi;\nconst byteCode = output.contracts[\"HelloWorld.sol\"][\"Demo\"].evm.bytecode.object;\n\n// console.log(\"abi: \",ABI)\n// console.log(\"byte code: \",byteCode)\n\nnpm run yorfilename.js\n```\n\n========================================\n\nComments:\n- Thanks. This is basically what i wanted to do, but is there some way, how to create the content of the input automatically? Something like solc.CreateJSON(CONTRACT_FILE)?\n- hey maybe you can advise? `const appPath = path.resolve(__dirname, 'contracts', 'inbox.sol');` `const source = fs.readFileSync(appPath, 'utf8').toString();` getting the file in a very similar manner, but got `Invalid input source specified` error\n- Do you modify your content file anyhow before passing it here?\n- Try `const appPath = path.resolve(__dirname, '.&#47;contracts&#47;inbox.sol');` and maybe remove `''utf8''` in `fs.readFileSync()`. I didn't modify `content`\n- yeah i tried hardcoded paths and removing `utf-8` - same\n- Ok i got it, you forget to include json key `content` in your answer and i overlook it in doc. it must be: `[CONTRACT_FILE]: { content: content }`\n- Sorry about that, if key and value are same, you can write just one word, you can know more here ariya.io/2013/02/&hellip;. Thanks for your feedback, will do my examples more readable next time =)\n- I re-cheked, code above with single `content` works on Node.js v8.12.0","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":190,"estimatedTokens":1463}}123{"id":"stack-68073689","source":"stackoverflow","questionId":68073689,"title":"Solidity: Data location must be \"memory\" or \"calldata\" for return parameter in function","tags":["ethereum","solidity"],"text":"Title: Solidity: Data location must be \"memory\" or \"calldata\" for return parameter in function\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI am learning Ethereum dev in Solidity and trying to run a simple HelloWorld program but ran into the following error:\n\nData location must be \"memory\" or \"calldata\" for return parameter in function, but none was given.\n\nMy code:\n\n```\npragma solidity ^0.8.5;\n\ncontract HelloWorld {\n string private helloMessage = \"Hello world\";\n\n function getHelloMessage() public view returns (string){\n return helloMessage;\n }\n}\n```\n\n========================================\n\nTop Answer:\nFor those reading this who have similar code, 'memory' may not necessarily be the correct word to use for you. You may need to use the words 'calldata' or 'storage' instead. Here is an explanation:\n\n**Memory, calldata (and storage)** refer to how Solidity variables store values.\n\nFor example:\n\n**1. Memory:** here is an example using the word 'memory':\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport 'hardhat/console.sol'; // to use console.log\n\ncontract MemoryExample {\n uint[] public values;\n\n function doSomething() public\n {\n values.push(5);\n values.push(10);\n\n console.log(values[0]); // logged as: 5\n\n modifyArray(values);\n }\n\n function modifyArray(uint[] memory arrayToModify) pure private {\n arrayToModify[0] = 8888;\n\n console.log(arrayToModify[0]) // logged as: 8888 \n console.log(values[0]) // logged as: 5 (unchanged)\n }\n}\n```\n\nNotice how the 'values' array was not changed in the private function because 'arrayToModify' is a **copy of the array** and does not reference (or point to the array that was passed in to the private function.\n\n**2. Calldata** is different and can be used to pass a variable as read-only:\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\ncontract CallDataExample {\n uint[] public values;\n\n function doSomething() public\n {\n values.push(5);\n values.push(10);\n\n modifyArray(values);\n }\n\n function modifyArray(uint[] calldata arrayToModify) pure private {\n arrayToModify[0] = 8888; // you will get an error saying the array is read only\n }\n}\n```\n\n**3. Storage:** a third option here is to use the 'storage' keyword:\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport 'hardhat/console.sol'; // to use console.log\n\ncontract MemoryExample {\n uint[] public values;\n\n function doSomething() public\n {\n values.push(5);\n values.push(10);\n\n console.log(values[0]); // logged as: 5\n\n modifyArray(values);\n }\n\n function modifyArray(uint[] storage arrayToModify) private {\n arrayToModify[0] = 8888;\n\n console.log(arrayToModify[0]) // logged as: 8888\n console.log(values[0]) // logged as: 8888 (modifed)\n }\n}\n```\n\nNotice how by using the memory keyword, **the arrayToModify variable references the array that was passed in and modifies it**.\n\n========================================\n\nCode:\n```text\npragma solidity ^0.8.5;\n\ncontract HelloWorld {\n  string private helloMessage = \"Hello world\";\n\n  function getHelloMessage() public view returns (string){\n    return helloMessage;\n  }\n}\n```\n\n```text\nfunction getHelloMessage() public view returns (string memory) {\n    return helloMessage;\n}\n```\n\n```text\nstring memory\n```\n\n```text\nstring\n```\n\n```text\nmemory\n```\n\n```text\nstring memory\n```\n\n```text\nstring\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport 'hardhat/console.sol'; // to use console.log\n\ncontract MemoryExample {\n    uint[] public values;\n\n    function doSomething() public\n    {\n        values.push(5);\n        values.push(10);\n\n        console.log(values[0]); // logged as: 5\n\n        modifyArray(values);\n    }\n\n    function modifyArray(uint[] memory arrayToModify) pure private {\n        arrayToModify[0] = 8888;\n\n        console.log(arrayToModify[0]) // logged as: 8888 \n        console.log(values[0]) // logged as: 5 (unchanged)\n    }\n}\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\ncontract CallDataExample {\n    uint[] public values;\n\n    function doSomething() public\n    {\n        values.push(5);\n        values.push(10);\n\n        modifyArray(values);\n    }\n\n    function modifyArray(uint[] calldata arrayToModify) pure private {\n        arrayToModify[0] = 8888; // you will get an error saying the array is read only\n    }\n}\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\nimport 'hardhat/console.sol'; // to use console.log\n\ncontract MemoryExample {\n    uint[] public values;\n\n    function doSomething() public\n    {\n        values.push(5);\n        values.push(10);\n\n        console.log(values[0]); // logged as: 5\n\n        modifyArray(values);\n    }\n\n    function modifyArray(uint[] storage arrayToModify) private {\n        arrayToModify[0] = 8888;\n\n        console.log(arrayToModify[0]) // logged as: 8888\n        console.log(values[0]) // logged as: 8888 (modifed)\n    }\n}\n```\n\n========================================\n\nComments:\n- The question is about memory type in returns of function not in the argument","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":241,"estimatedTokens":1253}}124{"id":"stack-50966458","source":"stackoverflow","questionId":50966458,"title":"Can we get transaction information recorded in the past block using Solidity in the Smart contract?","tags":["ethereum","blockchain","solidity","web3js","go-ethereum"],"text":"Title: Can we get transaction information recorded in the past block using Solidity in the Smart contract?\nTags: ethereum, blockchain, solidity, web3js, go-ethereum\nSource: Stack Overflow\n\nQuestion:\nI am studying blockchain with Ethereum, and I want to use past transaction data in the Smart contract using Solidity.\nIf I use Web3.js module in the program written in javascript, I can get these data easily.\nBut I can't get these data in the Smart contract using Solidity.\n\nReference of Solidity says that we can get current block number, blockhash, etc., by using \"block.number\" and \"block.blockhash(uint blockNumber)\" functions, but doesn't mention getting transaction data.\n(http://solidity.readthedocs.io/en/latest/units-and-global-variables.html#special-variables-and-functions)\n\nplease help me.\n\n========================================\n\nCode:\n```text\nblockhash\n```\n\n========================================\n\nComments:\n- Thank you very much for your prompt response. The means of using Oraclize is also very helpful. I am trying to develop a Smart contract to check the validity of new registration information from past transaction information, so I wanted to get transaction information on a Smart contract.","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":25,"estimatedTokens":304}}125{"id":"stack-51847788","source":"stackoverflow","questionId":51847788,"title":"Msg.sender does not work inside a \"view\" function, why? Is there a workaround?","tags":["blockchain","ethereum","solidity","smartcontracts","remix"],"text":"Title: Msg.sender does not work inside a \"view\" function, why? Is there a workaround?\nTags: blockchain, ethereum, solidity, smartcontracts, remix\nSource: Stack Overflow\n\nQuestion:\nI want to create a viewable function (needs to return a string to the user) that searches a mapping for msg.sender and if the senders value is x, I want the contract to proceed accordingly. It all does work inside remix but if I upload it to ropsten, it doesn't anymore. Is this a known issue? I have tried tx.origin as well, same result.\nThat's the problematic code I tried:\n\n```\nfunction getLink() public view returns(string){\n if(tokenBalances[msg.sender]>0){\n return link;\n }else{\n return \"You need to purchase a token at first...\";\n }\n}\n```\n\nEDIT: I think the problem is, that when using a viewable function there is no msg.sender because there is no actual transaction? Is there a way to return a value to the user without using the \"view\" functions?\n\n========================================\n\nCode:\n```text\nfunction getLink() public view returns(string){\n    if(tokenBalances[msg.sender]>0){\n        return link;\n    }else{\n        return \"You need to purchase a token at first...\";\n    }\n}\n```\n\n```text\nfunction getLink(address account) public view returns(string){\n    if(tokenBalances[account] > 0){\n        return link;\n    }else{\n        return \"You need to purchase a token at first...\";\n    }\n}\n```\n\n```text\nmsg.sender\n```\n\n```text\nview\n```\n\n```text\ncall\n```\n\n```text\nmsg.sender\n```\n\n```text\ncall\n```\n\n```text\nmsg.sender\n```\n\n========================================\n\nComments:\n- Are you setting `from` in the `call()` to the account you want to set `msg.sender` to?\n- @carver how do you mean that?\n- @carver Edited the post, that's the code I'm having problems with...\n- You'll need to show how you're calling the function (or tell us what tool). When calling a view function, the `from` address is optional, but if you provide it, `msg.sender` will have that value.\n- @smarx The function should be called directly from myetherwallet. But for some reason, the view functions can't get msg.sender, it's always 0x0000...\n- @smarx as long as I try inside remix, it's all fine but when I try to use it from myetherwallet (ropsten network), it doesn't work...\n- My guess would be that myetherwallet doesn't specify a `from` address. I haven't looked at their code.\n- @smarx is it possible to specify such settings for the contract?\n- I'm not sure what you're asking. If you're asking whether there's a way to get MyEtherWallet to specify a `from` address, I have no idea. (You'd probably get better results asking them.)\n- Well thank you, the problem really seems to be at myetherwallet, so theres not much I can do right now...\n- Thanks a lot, I wasn't really aware of the difference between a call and a transaction. I do know that hiding stuff behind msg.sender is pointless because of the visibility of, well, everything... I just needed this contract as a rather easy example. It seems like Myetherwallet doesn't get msg.sender in the call I made. I tested it with a simple return msg.sender call and indeed it just returns 0x000[...]. So again, thanks a lot for your extensive reply!","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":81,"estimatedTokens":795}}126{"id":"stack-65846335","source":"stackoverflow","questionId":65846335,"title":"How to send ERC20 token to smart contract balance?","tags":["javascript","ethereum","solidity","erc20"],"text":"Title: How to send ERC20 token to smart contract balance?\nTags: javascript, ethereum, solidity, erc20\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a smart contract and inherit some functions to swap ERC20 tokens,\n\nHere are my questions?\n\n**Question A:**\n**Is it possible to transfer ERC20 token to smart contract balance?**,\nPlease provide an example,\ni.e. We can create a function to send ETH to smart contract\n\n```\nfunction contribute() external payable {}\n\n//It will allow us to send ETH to smart contract balance,but how to send,for example, \"BAND\" token\n//to smart contract balance?\n```\n\n**Question B:**\nIf A is possible, **how to get contract's token balance?**\ni.e. We can get the contract ETH balance from this function:\n\n```\n// Get ETH balance\nfunction getBalance() external view returns(uint) {\n return address(this).balance; \n}\n\n// How to return contract's BAND balance, if A is possible ...\n```\n\n**Question C:**\n\nIf \"A\" is possible, How to make a swap to BAND/ETH liquidity pool, using Uniswap or Sushiswap API,\nIs it better to handle that process on server side proccesses using NodeJS, or implement it in solidity?\n\nFull smart contract code:\n\n```\npragma solidity ^0.5.11; \n\ncontract SwapTest {\n address public manager;\n \n constructor() public {\n manager = msg.sender;\n }\n \n modifier OnlyManager() {\n require(msg.sender == manager);\n _;\n }\n \n // Add funds to contract\n function contribute() external payable {}\n \n \n // Get ETH balance\n function getBalance() external view returns(uint) {\n return address(this).balance; \n } \n \n // Send provided amount of WEI to recipient\n function sendEther (address payable recipient, uint weiAmount) external OnlyManager{\n recipient.transfer(weiAmount); \n }\n \n // Send contract balance to recipient\n function withdrawBalance (address payable recipient) external OnlyManager{\n recipient.transfer(address(this).balance);\n }\n}\n```\n\nLooking forward to hearing back from you guys,\nThanks in advance.\n\n========================================\n\nCode:\n```text\nfunction contribute() external payable {}\n\n//It will allow us to send ETH to smart contract balance,but how to send,for example, \"BAND\" token\n//to smart contract balance?\n```\n\n```text\n// Get ETH balance\nfunction getBalance() external view returns(uint) {\n    return address(this).balance;    \n}\n\n// How to return contract's BAND balance, if A is possible ...\n```\n\n```text\npragma solidity ^0.5.11; \n\ncontract SwapTest {\n    address public manager;\n    \n    constructor() public {\n        manager = msg.sender;\n    }\n    \n    modifier OnlyManager() {\n        require(msg.sender == manager);\n        _;\n    }\n    \n    // Add funds to contract\n    function contribute() external payable {}\n    \n    \n    // Get ETH balance\n    function getBalance() external view returns(uint) {\n        return address(this).balance;    \n    } \n    \n    // Send provided amount of WEI to recipient\n    function sendEther (address payable recipient, uint weiAmount) external OnlyManager{\n        recipient.transfer(weiAmount);    \n    }\n    \n    // Send contract balance to recipient\n    function withdrawBalance (address payable recipient) external OnlyManager{\n        recipient.transfer(address(this).balance);\n    }\n}\n```\n\n```text\ninterface ERC20 {\n  function balanceOf(address owner) external view returns (unit);\n  function allowance(address owner, address spender) external view returns (unit);\n  function approve(address spender, uint value) external returns (bool);\n  function transfer(address to, uint value) external returns (bool);\n  function transferFrom(address from, address to, uint value) external returns (bool); \n}\n```\n\n```text\nfunction transferToMe(address _owner, address _token, unit _amount) public {\n  ERC20(_token).transferFrom(_owner, address(this), _amount);\n}\n```\n\n```text\nfunction getBalanceOfToken(address _address) public view returns (unit) {\n  return ERC20(_address).balanceOf(address(this));\n}\n```\n\n========================================\n\nComments:\n- For the StackOverflow Q&A format, I suggest you only add one question per question.\n- to create a Uniswav v2 pool you need to call Uniswap Factory contract with corresponding parameters. Download Uniswap sources and check it.\n- checked my DB of uniswap pairs. The pair you want to create already exists, the address is 0xf421c3f2e695C2D4C0765379cCace8adE4a480D9 . Also BAND token has another 16 pairs with other tokens: DIA, NMR,YFI, GEM,AXIA,DAI,BAT,USDC,YUNO,UNI,LINK,DREAM,AGI\n- Can you please inform how it could be tested? So I deploy contract on Rinkeby network, the question is how to get any ERC20 token to test it, since metamask doesn't allows swap on test networks\n- Ideally, I want to deploy contract on Rinkeby network and then send ERC20 tokens from Metamask and also call the swap functions later when I implement it, Thanks in advance\n- You can switch networks in Metamask when on app.uniswap.org/#/swap. Then you can swap some Rinkeby Ether for some ERC20 token and test out your functions.\n- You need a function to transfer the tokens out of the smart contract, otherwise those tokens will be lock there for ever. For this just use transfer as defined in the ERC20 interface. Also you can interface uniswap and directly provide liquidity.","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":167,"estimatedTokens":1308}}127{"id":"stack-65363074","source":"stackoverflow","questionId":65363074,"title":"How to convert 0x Protocol BigNumber to String in Javascript","tags":["javascript","ethereum","solidity"],"text":"Title: How to convert 0x Protocol BigNumber to String in Javascript\nTags: javascript, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI'm getting the market order and limit order's amount and price as a 0x Protocol BigNumber format. And I'm willing to save it as a numeric value to SQL database, so I need to convert BigNumber to String.\n\nI used this command:\n\n```\nBigNumber.toString()\n```\n\nBut I got 200000000000000000 while current BigNumber's value is 0.2.\n\nHow can I convert BigNumber to the correct numeric string?\n\n========================================\n\nTop Answer:\nDatabases are smart enough to do it on their own, so if you give them a string number and if you've defined it to be numeric value in the schema they can do it on their own. Database adapters also smart enough to give numeric values in string format while retrieving them from the database.\n\nIn short, you should not try to convert anything that is the point of it. You should rely on database, do all your math in the database.\n\n========================================\n\nCode:\n```text\nBigNumber.toString()\n```\n\n```text\nconst amountDecimal = tokenAmountInUnitsToBigNumber(amount, quoteTokenDecimal).toString();\n```\n\n```text\namount(BigNumber)\n```\n\n```text\ntokenAmountInUnitsToBigNumber\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":42,"estimatedTokens":317}}128{"id":"stack-49835663","source":"stackoverflow","questionId":49835663,"title":"Why does this Solidity function return a 0 after assert?","tags":["ethereum","solidity","remix"],"text":"Title: Why does this Solidity function return a 0 after assert?\nTags: ethereum, solidity, remix\nSource: Stack Overflow\n\nQuestion:\nI have written this function:\n\n```\n// Function to get an owned token's id by referencing the index of the user's owned tokens.\n// ex: user has 5 tokens, tokenOfOwnerByIndex(owner,3) will give the id of the 4th token.\nfunction tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint _tokenId) {\n // TODO: Make sure this works. Does not appear to throw when _indexWhen run with an _index of 2 and an _owner such that balanceOf(_owner) is 0, the function returns a 0 in the Remix IDE. My assumption was that it would not return anything. My questions are:\n\nA) Why does it return a 0 after failing an assert?\n\nB) How do I get this to not return a 0 when I run it with the above parameters?\n\nThanks,\nVaughn\n\n========================================\n\nCode:\n```text\n// Function to get an owned token's id by referencing the index of the user's owned tokens.\n// ex: user has 5 tokens, tokenOfOwnerByIndex(owner,3) will give the id of the 4th token.\nfunction tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint _tokenId) {\n    // TODO: Make sure this works. Does not appear to throw when _index<balanceOf(_owner), which violates\n    //       ERC721 compatibility.\n    assert(_index<balanceOf(_owner)); // throw if outside range\n    return ownedTokenIds[_owner][_index];\n}\n```\n\n```text\nfunction tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint, bool) {\n    bool success = _index < balanceOf(_owner);\n    return (ownedTokenIds[_owner][_index], success);\n}\n```\n\n```text\nview\n```\n\n```text\nview\n```\n\n```text\nuint\n```\n\n```text\nbool\n```\n\n```text\nview\n```\n\n========================================\n\nComments:\n- If you use this custom definition of `tokenOfOwnerByIndex()` then it would not be compatible with the published ERC-721 standard.","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":65,"estimatedTokens":483}}129{"id":"stack-68024206","source":"stackoverflow","questionId":68024206,"title":"run solidity code after every x amount of time","tags":["solidity","erc20"],"text":"Title: run solidity code after every x amount of time\nTags: solidity, erc20\nSource: Stack Overflow\n\nQuestion:\nI am creating a dev application in which after for example every 5 minutes would like to run some code from my erc20 token's smart contract. How can I call that function after every 5 minutes in solidity?\n\n========================================\n\nTop Answer:\nYou can use Gelato to schedule function calls in your smart contract. https://www.gelato.network/\nA very useful tool that takes a smart contract address, a function name and schedule to execute your chosen tasks.\n\n========================================\n\nCode:\n```text\nfunction sendTx() {\n   myContract.methods.myFunction().send();\n};\n\nsetInterval('sendTx', 5 * 1000 * 60);\n```\n\n```text\npragma solidity ^0.8;\n\ncontract MyContract {\n    uint256 lastRun;\n\n    function myFunction() external {\n        require(block.timestamp - lastRun > 5 minutes, 'Need to wait 5 minutes');\n\n        // TODO perform the action\n\n        lastRun = block.timestamp;\n    }\n}\n```\n\n========================================\n\nComments:\n- Appreciated. Say I want my token to be decentralised, I wouldn't want to call these functions by myself. Is there any industry accepted way for triggering them?\n- There are semi-decentralized oracle services that do the same thing as the off-chain app in my answer. For example Chainlink Alarm Clock - you can define your (contract) callback function in a way that keeps resetting the sleep interval to another 5 minutes after it's been executed. But each call (from Chainlink to your contract) costs 0.1 LINK, which can become costly to maintain.\n- You could also build a bounty into the smart contract that allows anyone to call the function and if enough time has passed it will pay out a reward to the caller, so long as its even slightly profitable there will probably be someone who puts a bot on it to collect the bounty every 5 minutes. May be able to get cheaper than 0.1 LINK with that solution.","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":46,"estimatedTokens":497}}130{"id":"stack-69868889","source":"stackoverflow","questionId":69868889,"title":"How can I get program author on solana?","tags":["rust","solidity","author","solana"],"text":"Title: How can I get program author on solana?\nTags: rust, solidity, author, solana\nSource: Stack Overflow\n\nQuestion:\nI'm curious if there is any way to get author of solana smart contract.\nIn the case of solidity, I have used save msg.sender in constructor to keep owner address of the contract.\n\n```\ncontract KeepOwner {\n address private _owner;\n constructor() {\n _owner = msg.sender;\n }\n\n function isOwner(address likeOwner) public view returns (bool) {\n return likeOwner == _owner;\n }\n}\n```\n\nBut I can't find any method to save and get author(who have sent deploy transaction) pubkey on solana.\nI have tried to get the information from AccountInfo of solana program but couldn't success.\n\n========================================\n\nTop Answer:\nThere are two ways of doing this, depending on what exactly you're looking for:\n\n- You can look at all past transaction signatures involving the program address using https://docs.solana.com/developing/clients/jsonrpc-api#getsignaturesforaddress followed by https://docs.solana.com/developing/clients/jsonrpc-api#gettransaction for each signature. Any instructions to the BPF Upgradeable Loader (`BPFLoaderUpgradeab1e11111111111111111111111`) or BPF Loader 2 (`BPFLoader2111111111111111111111111111111111`) programs will likely be signed by the program author.\n\n- If the program is associated with the upgradeable loader (`BPFLoaderUpgradeab1e11111111111111111111111`), then there may be an \"upgrade authority\" who can upgrade the program. This could be a good proxy for the \"author\" of the program. If you look at the stake pool program in the explorer, you'll see that `4SnSuUtJGKvk2GYpBwmEsWG53zTurVM8yXGsoiZQyMJn` is the upgrade authority: https://explorer.solana.com/address/SPoo1Ku8WFXoNDMHPsrGSTSG1Y47rzgn41SLUNakuHy\n\n========================================\n\nCode:\n```text\ncontract KeepOwner {\n    address private _owner;\n    constructor() {\n        _owner = msg.sender;\n    }\n\n    function isOwner(address likeOwner) public view returns (bool) {\n        return likeOwner == _owner;\n    }\n}\n```\n\n```text\nBPFLoaderUpgradeab1e11111111111111111111111\n```\n\n```text\nBPFLoader2111111111111111111111111111111111\n```\n\n```text\nBPFLoaderUpgradeab1e11111111111111111111111\n```\n\n```text\n4SnSuUtJGKvk2GYpBwmEsWG53zTurVM8yXGsoiZQyMJn\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":64,"estimatedTokens":570}}131{"id":"stack-76912605","source":"stackoverflow","questionId":76912605,"title":"hardhat .deployed() is not a function","tags":["solidity","hardhat"],"text":"Title: hardhat .deployed() is not a function\nTags: solidity, hardhat\nSource: Stack Overflow\n\nQuestion:\nWhen i tried running this command, I have previously ran `npx hardhat clean` and `npx hardhat compile`. I have the following error:\n\n```\nnpx hardhat run scripts/deployRoboPunksNFT.js --network sepolia\nTypeError: roboPunksNFT.deployed is not a function\n at main (/home/stanley/Documents/full-mint-website/scripts/deployRoboPunksNFT.js:7:22)\n at processTicksAndRejections (node:internal/process/task_queues:95:5)\n```\n\nand other times i have a connection timeout:\n\n```\nError: Socket connection timeout\n at new NodeError (node:internal/errors:399:5)\n at internalConnectMultiple (node:net:1099:20)\n at Timeout.internalConnectMultipleTimeout (node:net:1638:3)\n at listOnTimeout (node:internal/timers:575:11)\n at processTimers (node:internal/timers:514:7) {\n code: 'ERR_SOCKET_CONNECTION_TIMEOUT'\n}\n```\n\nMy deployRoboPunksNFT.js script\n\n```\nconst hre = require(\"hardhat\");\n\nasync function main() {\n const RoboPunksNFT = await hre.ethers.getContractFactory(\"RoboPunksNFT\");\n const roboPunksNFT = await RoboPunksNFT.deploy();\n\n await roboPunksNFT.deployed();\n\n console.log(\"RoboPunksNFT deployed to:\", roboPunksNFT.address);\n}\n\n// We recommend this pattern to be able to use async/await everywhere\n// and properly handle errors.\nmain()\n .then(() => process.exit(0))\n .catch((error) => {\n console.error(error);\n process.exit(1);\n });\n```\n\nMy hardhat config\n\n```\nrequire(\"@nomicfoundation/hardhat-toolbox\");\n\nconst dotenv = require(\"dotenv\");\ndotenv.config();\n\n/** @type import('hardhat/config').HardhatUserConfig */\nmodule.exports = {\n solidity: \"0.8.19\",\n networks: {\n sepolia: {\n url: process.env.REACT_APP_SEPOLIA_URL,\n accounts: [process.env.REACT_APP_PRIVATE_KEY],\n },\n },\n apiKey: process.env.REACT_APP_ETHERSCAN_KEY,\n};\n```\n\nHow do i solve this issue ?\n\n========================================\n\nTop Answer:\nI see that you are using the **@nomicfoundation/hardhat-toolbox**. In a recent update hardhat team migrated from hardhat-waffle to **@nomicfoundation/hardhat-toolbox**. So **deployed()** is no longer in use.\n\nTo make your code work replace **deployed()** with **waitForDeployment()**.\n\nYou can refer to this :Migration\n\n========================================\n\nCode:\n```text\nnpx hardhat run scripts/deployRoboPunksNFT.js --network sepolia\nTypeError: roboPunksNFT.deployed is not a function\n    at main (/home/stanley/Documents/full-mint-website/scripts/deployRoboPunksNFT.js:7:22)\n    at processTicksAndRejections (node:internal/process/task_queues:95:5)\n```\n\n```text\nError: Socket connection timeout\n    at new NodeError (node:internal/errors:399:5)\n    at internalConnectMultiple (node:net:1099:20)\n    at Timeout.internalConnectMultipleTimeout (node:net:1638:3)\n    at listOnTimeout (node:internal/timers:575:11)\n    at processTimers (node:internal/timers:514:7) {\n  code: 'ERR_SOCKET_CONNECTION_TIMEOUT'\n}\n```\n\n```text\nconst hre = require(\"hardhat\");\n\nasync function main() {\n  const RoboPunksNFT = await hre.ethers.getContractFactory(\"RoboPunksNFT\");\n  const roboPunksNFT = await RoboPunksNFT.deploy();\n\n  await roboPunksNFT.deployed();\n\n  console.log(\"RoboPunksNFT deployed to:\", roboPunksNFT.address);\n}\n\n// We recommend this pattern to be able to use async/await everywhere\n// and properly handle errors.\nmain()\n  .then(() => process.exit(0))\n  .catch((error) => {\n    console.error(error);\n    process.exit(1);\n  });\n```\n\n```text\nrequire(\"@nomicfoundation/hardhat-toolbox\");\n\nconst dotenv = require(\"dotenv\");\ndotenv.config();\n\n/** @type import('hardhat/config').HardhatUserConfig */\nmodule.exports = {\n  solidity: \"0.8.19\",\n  networks: {\n    sepolia: {\n      url: process.env.REACT_APP_SEPOLIA_URL,\n      accounts: [process.env.REACT_APP_PRIVATE_KEY],\n    },\n  },\n  apiKey: process.env.REACT_APP_ETHERSCAN_KEY,\n};\n```\n\n```text\nnpx hardhat clean\n```\n\n```text\nnpx hardhat compile\n```\n\n```text\nconsole.log(\"RoboPunksNFT deployed to:\", roboPunksNFT.address);\n```\n\n```text\nconsole.log(\"RoboPunksNFT deployed to:\",await roboPunksNFT.getAddress());\n```\n\n```text\ndeployed()\n```\n\n```text\naddress\n```\n\n```text\ndeployed()\n```\n\n```text\nwaitForDeployment()\n```\n\n========================================\n\nComments:\n- Which version of Hardhat are you using? They made a switch recently in their list of depencies - from `ethers` v5 to `ethers` v6, and it seems like it might be relevant.\n- this is the correct solution; tested on `solidity ^0.8.9` and `hardhat ^2.19.2`","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":182,"estimatedTokens":1119}}132{"id":"stack-57523392","source":"stackoverflow","questionId":57523392,"title":"How to filter by string parameter, web3 2.0.0-alpha.1 Solidity events?","tags":["node.js","ethereum","solidity","web3js"],"text":"Title: How to filter by string parameter, web3 2.0.0-alpha.1 Solidity events?\nTags: node.js, ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to filter some events, and I noticed since I updated the web3 to version 2.0.0-alpha 1 the event catch is a little bit different.\n\nI have a Smart Contract with this event:\n\n```\nevent catchMeIfYouCan (address indexed a, string indexed b, uint indexed c);\n```\n\nAnd I want to filter by its parameters, so far so good.\n\nBut when I try to filter by b ( the string indexed ), this is not working.\nI'm doing that in NodeJS with ExpressJS and the Web3 version mentioned above.\n\nIf I do that:\n\n```\nconst event = smartContract.events.catchMeIfYouCan({ filter : {\n a : accountAddress ,\n b : web3.utils.toHex(stringValue) ,\n c : web3.utils.toWei(\"\" + numberValue) } \n}, (error, event) => {\n // do some things\n});\n```\n\nI get:\n\n```\nNode error: {\"code\":-32602,\"message\":\"invalid argument 1: hex has invalid length 96 after decoding\"}\n```\n\nOtherwise, if I let the b parameter, in NodeJS event catch as:\n\n```\nb : stringValue,\n```\n\nIt doesn't catch the event anymore , same with c ( e.g : no more `web3.utils.toWei()` ).\n\nDo you have any idea how to filter the event by a string parameter in Web3 2.0.0-Alpha 1 version?\n\n========================================\n\nCode:\n```text\nevent catchMeIfYouCan (address indexed a, string indexed b, uint indexed c);\n```\n\n```text\nconst event = smartContract.events.catchMeIfYouCan({ filter : {\n a : accountAddress ,\n b : web3.utils.toHex(stringValue) ,\n c : web3.utils.toWei(\"\" + numberValue) } \n}, (error, event) => {\n // do some things\n});\n```\n\n```text\nNode error: {\"code\":-32602,\"message\":\"invalid argument 1: hex has invalid length 96 after decoding\"}\n```\n\n```text\nb : stringValue,\n```\n\n```text\nweb3.utils.toWei()\n```\n\n```js\ncontract.events.CatchMeIfYouCan({\n    topics: [, web3.utils.sha3(stringValue)], // first element is empty, because its place for `address` index\n    fromBlock: 2000000\n  }, (error, event) => {\n    console.log(event)\n  })\n```\n\n```text\nfilter\n```\n\n```text\ntopics\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.124Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":91,"estimatedTokens":520}}133{"id":"stack-53408632","source":"stackoverflow","questionId":53408632,"title":"Code not compiling in nodejs,throws out an unexpected error(Web3.js)","tags":["node.js","blockchain","solidity","web3js"],"text":"Title: Code not compiling in nodejs,throws out an unexpected error(Web3.js)\nTags: node.js, blockchain, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI tried following this repo:- \n\nBut I am getting the following error on compiling the code with :- \n\n```\ncode = fs.readFileSync('Voting.sol').toString()\nsolc = require('solc')\ncompiledCode = solc.compile(code)\n```\n\nIt throws out this error:-\n\n```\n'{\"errors\":[{\"component\":\"general\",\"formattedMessage\":\"* Line 1, Column 1\\\\n Syntax error: value, object or array expected.\\\\n* Line 1, Column 2\\\\n Extra non-whitespace after JSON value.\\\\n\",\"message\":\"* Line 1, Column 1\\\\n Syntax error: value, object or array expected.\\\\n* Line 1, Column 2\\\\n Extra non-whitespace after JSON value.\\\\n\",\"severity\":\"error\",\"type\":\"JSONError\"}]}'\n```\n\n========================================\n\nTop Answer:\nI found that if you put your input info into the JSON format per the solidity docs, then you are good regardless of the compiler. Before compiling \"stringify\" the file (JSON.stringify). After the file is compiled the object will be in string form, so then you may want to parse it (JSON.parse) to work with it from there. Here is a code sample with a console.log() of the contract in JSON form so you can see what you are working with.\n\n```\nconst path = require('path');\nconst fs = require('fs');\nconst solc = require('solc');\n\nconst inboxPath = path.resolve(__dirname, 'contracts', 'inbox.sol');\nconst source = fs.readFileSync(inboxPath, 'utf8');\n\nvar solcInput = {\n language: \"Solidity\",\n sources: { \n contract: {\n content: source\n }\n },\n settings: {\n optimizer: {\n enabled: true\n },\n evmVersion: \"byzantium\",\n outputSelection: {\n \"*\": {\n \"\": [\n \"legacyAST\",\n \"ast\"\n ],\n \"*\": [\n \"abi\",\n \"evm.bytecode.object\",\n \"evm.bytecode.sourceMap\",\n \"evm.deployedBytecode.object\",\n \"evm.deployedBytecode.sourceMap\",\n \"evm.gasEstimates\"\n ]\n },\n }\n }\n};\n\nsolcInput = JSON.stringify(solcInput);\nvar contractObject = solc.compile(solcInput);\ncontractObject = JSON.parse(contractObject);\n\nconsole.log(contractObject);\n```\n\n========================================\n\nCode:\n```text\ncode = fs.readFileSync('Voting.sol').toString()\nsolc = require('solc')\ncompiledCode = solc.compile(code)\n```\n\n```text\n'{\"errors\":[{\"component\":\"general\",\"formattedMessage\":\"* Line 1, Column 1\\\\n  Syntax error: value, object or array expected.\\\\n* Line 1, Column 2\\\\n  Extra non-whitespace after JSON value.\\\\n\",\"message\":\"* Line 1, Column 1\\\\n  Syntax error: value, object or array expected.\\\\n* Line 1, Column 2\\\\n  Extra non-whitespace after JSON value.\\\\n\",\"severity\":\"error\",\"type\":\"JSONError\"}]}'\n```\n\n```text\ncode = fs.readFileSync('Voting.sol', 'utf8');\n```\n\n```text\ncompiledCode = solc.compile(code, 1);\n```\n\n```text\nFile.sol\n```\n\n```text\nCompiler Standard Input JSON\n```\n\n```text\nsolc.compile()\n```\n\n```text\nconst path = require('path');\nconst fs = require('fs');\nconst solc = require('solc');\n\n\nconst inboxPath = path.resolve(__dirname, 'contracts', 'inbox.sol');\nconst source = fs.readFileSync(inboxPath, 'utf8');\n\nvar solcInput = {\n    language: \"Solidity\",\n    sources: { \n        contract: {\n            content: source\n        }\n     },\n    settings: {\n        optimizer: {\n            enabled: true\n        },\n        evmVersion: \"byzantium\",\n        outputSelection: {\n            \"*\": {\n              \"\": [\n                \"legacyAST\",\n                \"ast\"\n              ],\n              \"*\": [\n                \"abi\",\n                \"evm.bytecode.object\",\n                \"evm.bytecode.sourceMap\",\n                \"evm.deployedBytecode.object\",\n                \"evm.deployedBytecode.sourceMap\",\n                \"evm.gasEstimates\"\n              ]\n            },\n        }\n    }\n};\n\nsolcInput = JSON.stringify(solcInput);\nvar contractObject = solc.compile(solcInput);\ncontractObject = JSON.parse(contractObject);\n\nconsole.log(contractObject);\n```\n\n```text\npragma solidity ^0.4.18;\n```\n\n```text\nnpm install solc@0.4.18\n```\n\n========================================\n\nComments:\n- You better go on the repo to open an issue there. (I assume you already checked the opened issues)\n- Hey @Izio , i did open an issue but looks like the developer is inactive for few days. A fast help will be appreciated. Thanks\n- What is the `code` variable? If it's some sol file then how did you read it?\n- Also since the compilation is done by Solidity why don't you google google.com/&hellip;.\n- Hey @Molda, i have updated the code, please look into it. I did google it, but was not able to find an appropriate answer. Thanks\n- The compile function takes different arguments depending on which version you have. Make sure to check documentation github.com/ethereum/solc-js#readme\n- Have you solved it somehow? I have the same problem.\n- I have been busy since few days will resume today. No, i didn't get any solution for it yet.\n- Hey, @BananaCake i found the answer. Please check below.\n- @abhinayak Thank you, but can you be more specific about the npm and solc conflict?\n- @BananaCake go through this link :-github.com/maheshmurthy/ethereum_voting_dapp/issues/16\n- @abhinayak I'm not following the tutorial so I don't have any package.json file. I have only HelloWorld.sol with the Solidity code and I get this error whenever I want to compile it.\n- hey, @BananaCake, it's because of the package version problems. try matching the package version as shown in the tutorial.\n- @abhinayak I found another solution that works for me and solidity 0.5.1. Check my answer.\n- specifing the number of contract, gives out an AssertionError\n- This did the trick for me: it may take more code but no need to mess around with compiler versions.\n- This is the actual resolution for the error message. Both the versions of Solc and our pragma declaration in the contract should be same, or atleast compatable","metadata":{"transformedAt":"2026-08-18T18:33:36.125Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":180,"estimatedTokens":1450}}134{"id":"stack-67700882","source":"stackoverflow","questionId":67700882,"title":"Verify and Publish Contract on Etherscan with Imported OpenZeppelin file","tags":["ethereum","solidity","smartcontracts","cryptocurrency","etherscan"],"text":"Title: Verify and Publish Contract on Etherscan with Imported OpenZeppelin file\nTags: ethereum, solidity, smartcontracts, cryptocurrency, etherscan\nSource: Stack Overflow\n\nQuestion:\nI'm currently building a ERC721 compliant contract and have published the contract here: https://ropsten.etherscan.io/address/0xa513bc0a0d3af384fefcd8bbc1cc0c9763307c39 - I'm now attempting to verify and publish the contract source code\n\nThe start of my file looks like so:\n\n```\n// SPDX-License-Identifier: MIT\n\n// We will be using Solidity version 0.8.4\npragma solidity 0.8.4;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\n\ncontract ViperToken is ERC721 {\n```\n\nHowever, when attempting to verify and publish with a Solidity single file I have the following error appear:\n\n```\nParserError: Source \"@openzeppelin/contracts/token/ERC721/ERC721.sol\" not found: File import callback not supported\n --> myc:6:1:\n |\n6 | import \"@openzeppelin/contracts/token/ERC721/ERC721.sol\"\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n```\n\nCan anyone point me in the direction to either 1. Solve this problem or 2. Documentation on how to appropriately write a contract that has dependencies imported that can be verified with Etherscan. Right now this is just a single file contract.\n\n========================================\n\nTop Answer:\nIf you are compiling into REMIX IDE\n\nFrom REMIX IDE\n\nSearch for \"Flattener\" pluging\n\nRIght click the file -> Flatten yourcontract.sol\n\nCopy/Paste on Etherscan\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: MIT\n\n// We will be using Solidity version 0.8.4\npragma solidity 0.8.4;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\n\ncontract ViperToken is ERC721 {\n```\n\n```text\nParserError: Source \"@openzeppelin/contracts/token/ERC721/ERC721.sol\" not found: File import callback not supported\n --> myc:6:1:\n  |\n6 | import \"@openzeppelin/contracts/token/ERC721/ERC721.sol\"\n  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n```\n\n```text\nnpx hardhat flatten\n```\n\n```text\ntask(\"flat\", \"Flattens and prints contracts and their dependencies (Resolves licenses)\")\n  .addOptionalVariadicPositionalParam(\"files\", \"The files to flatten\", undefined, types.inputFile)\n  .setAction(async ({ files }, hre) => {\n    let flattened = await hre.run(\"flatten:get-flattened-sources\", { files });\n    \n    // Remove every line started with \"// SPDX-License-Identifier:\"\n    flattened = flattened.replace(/SPDX-License-Identifier:/gm, \"License-Identifier:\");\n    flattened = `// SPDX-License-Identifier: MIXED\\n\\n${flattened}`;\n\n    // Remove every line started with \"pragma experimental ABIEncoderV2;\" except the first one\n    flattened = flattened.replace(/pragma experimental ABIEncoderV2;\\n/gm, ((i) => (m) => (!i++ ? m : \"\"))(0));\n    console.log(flattened);\n  });\n```\n\n```text\nnpx hardhat flatten\n```\n\n```text\nhardhat.config.js\n```\n\n```text\nnpx hardhat flat contracts/ContractToFlatten.sol > Flattened.sol\n```\n\n========================================\n\nComments:\n- This was it! Thank you so much for writing down everything which lead you the right way.\n- There's actually a plugin named \"ETHERSCAN - CONTRACT VERIFICATION\" which works pretty well.\n- It looks like Remix already implemented this natively. I didnt install any pluggin and I was able to right click the file and flatten it :)","metadata":{"transformedAt":"2026-08-18T18:33:36.125Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":105,"estimatedTokens":841}}135{"id":"stack-56229313","source":"stackoverflow","questionId":56229313,"title":"Unable to deploy Solidity contract to Rinkeby network (Invalid asm.js: Invalid member of stdlib)","tags":["javascript","node.js","node-modules","ethereum","solidity"],"text":"Title: Unable to deploy Solidity contract to Rinkeby network (Invalid asm.js: Invalid member of stdlib)\nTags: javascript, node.js, node-modules, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI've been learning Solidity using this course by Stephen Grider and it's been going well until now, where I am trying to deploy my code to the Rinkeby test network. \n\nFor reference, I am using Node version 11.15.0 with npm version 6.7.0 with these dependencies:\n\n```\n\"dependencies\": {\n \"ganache-cli\": \"^6.4.3\",\n \"mocha\": \"^6.1.4\",\n \"nan\": \"^2.14.0\",\n \"scrypt\": \"^6.0.3\",\n \"solc\": \"^0.4.25\",\n \"truffle\": \"^4.1.15\",\n \"truffle-hdwallet-provider\": \"0.0.4\",\n \"web3\": \"^1.0.0-beta.35\" }\n```\n\nI have spent hours switching between versions of Node.js, npm, and all sorts of combinations of the dependencies, from the most current versions to the versions specified in the course. While I am getting a multitude of issues, the most prominent two seem to be\n\n```\n(node:32436) V8: C:\\Desktop\\solidity\\inbox\\node_modules\\solc\\soljson.js:3 Invalid asm.js: Invalid member of stdlib\n```\n\nand\n\n```\nC:\\Desktop\\solidity\\inbox\\node_modules\\solc\\soljson.js:1\nvar Module;if(!Module)Module=(typeof Module!==\"undefined\"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window===\"object\";var ENVIRONMENT_IS_WORKER=typeof importScripts===\"function\";var ENVIRONMENT_IS_NODE=typeof process===\"object\"&&typeof require===\"function\"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module[\"print\"])Module[\"print\"]=function print(x){process[\"stdout\"].write(x+\"\\n\")};if(!Module[\"printErr\"])Module[\"printErr\"]=function printErr(x){process[\"stderr\"].write(x+\"\\n\")};var nodeFS=require(\"fs\");var nodePath=require(\"path\");Module[\"read\"]=function read(filename,binary){filename=nodePath[\"normalize\"](filename);var ret=nodeFS[\"readFileSync\"](filename);if(!ret&&filename!=nodePath[\"resolve\"](filename)){filename=path.joi\n\nError: CONNECTION ERROR: Couldn't connect to node rinkeby.infura.io/v3/acb10732334e4450ba7dc55e618eb70a.\n at Object.InvalidConnection (C:\\Desktop\\solidity\\inbox\\node_modules\\truffle-hdwallet-provider\\node_modules\\web3\\lib\\web3\\errors.js:28:16)\n at HttpProvider.sendAsync (C:\\Desktop\\solidity\\inbox\\node_modules\\truffle-hdwallet-provider\\node_modules\\web3\\lib\\web3\\httpprovider.js:129:25)\n at Web3Subprovider.handleRequest (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\subproviders\\web3.js:13:17)\n at next (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:95:18)\n at FilterSubprovider.handleRequest (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\subproviders\\filters.js:87:7)\n at next (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:95:18)\n at HookedWalletSubprovider.handleRequest (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\subproviders\\hooked-wallet.js:109:7)\n at next (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:95:18)\n at Web3ProviderEngine._handleAsync (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:82:3)\n at Web3ProviderEngine._fetchBlock (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:191:8)\n at Web3ProviderEngine._fetchLatestBlock (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:167:8)\n at Web3ProviderEngine._startPolling (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:144:8)\n at Web3ProviderEngine.start (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:38:8)\n at new HDWalletProvider (C:\\Desktop\\solidity\\inbox\\node_modules\\truffle-hdwallet-provider\\index.js:46:15)\n at Object. (C:\\Desktop\\solidity\\inbox\\deploy.js:6:18)\n at Module._compile (internal/modules/cjs/loader.js:816:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)\n at Module.load (internal/modules/cjs/loader.js:685:32)\n at Function.Module._load (internal/modules/cjs/loader.js:620:12)\n at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)\n at internal/main/run_main_module.js:21:11\n```\n\nMy question would be are there any fixes for either of these issues based on my code, or is there a simpler way to deploy to the blockchain? Thank you in advance.\n\n========================================\n\nTop Answer:\nI am following the same tutorial as the OP. If you are using `node` v14.15.4 and `npm` v6.14.10, I would like to confirm that the following *package.json* solved the issue:\n\n```\n{\n \"name\": \"inbox\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"mocha\"\n },\n \"author\": \"\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"ganache-cli\": \"^6.4.3\",\n \"mocha\": \"^6.1.4\",\n \"solc\": \"^0.4.25\",\n \"truffle-hdwallet-provider\": \"0.0.4\",\n \"web3\": \"^1.0.0-beta.35\"\n }\n}\n```\n\nThen rebuild your dependencies by deleting your `node_modules` of your project, then run\n\n```\nnpm install\n```\n\n========================================\n\nCode:\n```text\n\"dependencies\": {\n    \"ganache-cli\": \"^6.4.3\",\n    \"mocha\": \"^6.1.4\",\n    \"nan\": \"^2.14.0\",\n    \"scrypt\": \"^6.0.3\",\n    \"solc\": \"^0.4.25\",\n    \"truffle\": \"^4.1.15\",\n    \"truffle-hdwallet-provider\": \"0.0.4\",\n    \"web3\": \"^1.0.0-beta.35\" }\n```\n\n```text\n(node:32436) V8: C:\\Desktop\\solidity\\inbox\\node_modules\\solc\\soljson.js:3 Invalid asm.js: Invalid member of stdlib\n```\n\n```text\nC:\\Desktop\\solidity\\inbox\\node_modules\\solc\\soljson.js:1\nvar Module;if(!Module)Module=(typeof Module!==\"undefined\"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window===\"object\";var ENVIRONMENT_IS_WORKER=typeof importScripts===\"function\";var ENVIRONMENT_IS_NODE=typeof process===\"object\"&&typeof require===\"function\"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module[\"print\"])Module[\"print\"]=function print(x){process[\"stdout\"].write(x+\"\\n\")};if(!Module[\"printErr\"])Module[\"printErr\"]=function printErr(x){process[\"stderr\"].write(x+\"\\n\")};var nodeFS=require(\"fs\");var nodePath=require(\"path\");Module[\"read\"]=function read(filename,binary){filename=nodePath[\"normalize\"](filename);var ret=nodeFS[\"readFileSync\"](filename);if(!ret&&filename!=nodePath[\"resolve\"](filename)){filename=path.joi\n\nError: CONNECTION ERROR: Couldn't connect to node rinkeby.infura.io/v3/acb10732334e4450ba7dc55e618eb70a.\n    at Object.InvalidConnection (C:\\Desktop\\solidity\\inbox\\node_modules\\truffle-hdwallet-provider\\node_modules\\web3\\lib\\web3\\errors.js:28:16)\n    at HttpProvider.sendAsync (C:\\Desktop\\solidity\\inbox\\node_modules\\truffle-hdwallet-provider\\node_modules\\web3\\lib\\web3\\httpprovider.js:129:25)\n    at Web3Subprovider.handleRequest (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\subproviders\\web3.js:13:17)\n    at next (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:95:18)\n    at FilterSubprovider.handleRequest (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\subproviders\\filters.js:87:7)\n    at next (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:95:18)\n    at HookedWalletSubprovider.handleRequest (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\subproviders\\hooked-wallet.js:109:7)\n    at next (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:95:18)\n    at Web3ProviderEngine._handleAsync (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:82:3)\n    at Web3ProviderEngine._fetchBlock (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:191:8)\n    at Web3ProviderEngine._fetchLatestBlock (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:167:8)\n    at Web3ProviderEngine._startPolling (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:144:8)\n    at Web3ProviderEngine.start (C:\\Desktop\\solidity\\inbox\\node_modules\\web3-provider-engine\\index.js:38:8)\n    at new HDWalletProvider (C:\\Desktop\\solidity\\inbox\\node_modules\\truffle-hdwallet-provider\\index.js:46:15)\n    at Object.<anonymous> (C:\\Desktop\\solidity\\inbox\\deploy.js:6:18)\n    at Module._compile (internal/modules/cjs/loader.js:816:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)\n    at Module.load (internal/modules/cjs/loader.js:685:32)\n    at Function.Module._load (internal/modules/cjs/loader.js:620:12)\n    at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)\n    at internal/main/run_main_module.js:21:11\n```\n\n```text\nError: CONNECTION ERROR: Couldn't connect to node rinkeby.infura.io/v3/acb10732334e4450ba7dc55e618eb70a.\n```\n\n```text\nhttps://rinkeby.infura.io/...\n```\n\n```text\nhttps://\n```\n\n```text\n{\n  \"name\": \"inbox\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"mocha\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"ganache-cli\": \"^6.4.3\",\n    \"mocha\": \"^6.1.4\",\n    \"solc\": \"^0.4.25\",\n    \"truffle-hdwallet-provider\": \"0.0.4\",\n    \"web3\": \"^1.0.0-beta.35\"\n  }\n}\n```\n\n```text\nnpm install\n```\n\n```text\nnode\n```\n\n```text\nnpm\n```\n\n```text\nnode_modules\n```\n\n```text\nnpm install solc\n```\n\n```text\nnpm\n```\n\n```text\n7.20.3\n```\n\n========================================\n\nComments:\n- That did the trick, thank you, I can't believe I didn't notice that. I'm still getting the invalid asm.js error, but it doesn't seem to affect the program because my program is returning a valid hash.\n- Were you able to solve the invalid asm.js error? What was the fix?","metadata":{"transformedAt":"2026-08-18T18:33:36.125Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":204,"estimatedTokens":2431}}136{"id":"stack-50495154","source":"stackoverflow","questionId":50495154,"title":"Why am I getting exceeds gas limit error when I specify the exact gas limit?","tags":["ethereum","solidity","truffle"],"text":"Title: Why am I getting exceeds gas limit error when I specify the exact gas limit?\nTags: ethereum, solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nI am deploying a contract using truffle, and when I specify the gas limit as the gas I want to use for the transaction I always get the exceeds gas limit error. Why does this happen?\n\nedit\nWhat I am trying to do is deploy the crypto kitties KittyCore.sol contract to my local devnet. I am using truffle to deploy it. \n\nFrom another page, How to deploy truffle contract to dev network when using inheritance?, I found that since there is a contract hierarchy, I need to deploy my contracts in order. I used this technique, and I am able to deploy 4 out of 7 contracts, with the fifth, KittyAuction, giving the following error: The contract code couldn't be stored, please check your gas amount \n\nPosted below is my truffle deployer script \n\n```\nvar KittyCore = artifacts.require(\"KittyCore\");\nvar KittyMinting = artifacts.require(\"KittyMinting\");\nvar KittyAuction = artifacts.require(\"KittyAuction\");\nvar KittyBreeding = artifacts.require(\"KittyBreeding\");\nvar KittyOwnership = artifacts.require(\"KittyOwnership\");\nvar KittyBase = artifacts.require(\"KittyBase\");\nvar KittyAccessControl = artifacts.require(\"KittyAccessControl\");\nvar SaleClockAuction = artifacts.require(\"SaleClockAuction\");\n\nmodule.exports = function (deployer) {\n deployer.deploy(KittyAccessControl).then(function () {\n return deployer.deploy(KittyBase).then(function () {\n return deployer.deploy(KittyOwnership).then(function () {\n return deployer.deploy(KittyBreeding).then(function () {\n return deployer.deploy(KittyAuction, {\n gas: 400000\n }).then(function () {\n return deployer.deploy(KittyMinting).then(function () {\n return deployer.deploy(KittyCore);\n })\n })\n })\n })\n })\n });\n};\n```\n\nMy gas limit is set to 18000000000. This gas number is produced by running the following function on the actual contract that fails to deploy\n\n```\nvar gasPrice;\nKittyAuction.web3.eth.getGasPrice(function (error, result) {\n gasPrice = Number(result);\n console.log(gasPrice);\n})\n```\n\nI have been fiddling with this number and nothing seems to work.\n\n========================================\n\nCode:\n```text\nvar KittyCore = artifacts.require(\"KittyCore\");\nvar KittyMinting = artifacts.require(\"KittyMinting\");\nvar KittyAuction = artifacts.require(\"KittyAuction\");\nvar KittyBreeding = artifacts.require(\"KittyBreeding\");\nvar KittyOwnership = artifacts.require(\"KittyOwnership\");\nvar KittyBase = artifacts.require(\"KittyBase\");\nvar KittyAccessControl = artifacts.require(\"KittyAccessControl\");\nvar SaleClockAuction = artifacts.require(\"SaleClockAuction\");\n\nmodule.exports = function (deployer) {\n    deployer.deploy(KittyAccessControl).then(function () {\n        return deployer.deploy(KittyBase).then(function () {\n            return deployer.deploy(KittyOwnership).then(function () {\n                return deployer.deploy(KittyBreeding).then(function () {\n                    return deployer.deploy(KittyAuction, {\n                        gas: 400000\n                    }).then(function () {\n                        return deployer.deploy(KittyMinting).then(function () {\n                            return deployer.deploy(KittyCore);\n                        })\n                    })\n                })\n            })\n        })\n    });\n};\n```\n\n```text\nvar gasPrice;\nKittyAuction.web3.eth.getGasPrice(function (error, result) {\n    gasPrice = Number(result);\n    console.log(gasPrice);\n})\n```\n\n========================================\n\nComments:\n- What's the smallest gas limit you can set and still have the transaction succeed?\n- Also, edit your question to include your contract code, the gas limit you're specifying, and how you came up with that number.\n- I'm trying to deploy the cryptokitties main contract to my local devnet. It's a lot of quote to post but it is freely available and I have not made any changes except adding the payable keyword to the Constructor","metadata":{"transformedAt":"2026-08-18T18:33:36.125Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":101,"estimatedTokens":996}}137{"id":"stack-69089799","source":"stackoverflow","questionId":69089799,"title":"How to locally unit-test Chainlink's Verifiable Random Function?","tags":["unit-testing","random","solidity","chainlink"],"text":"Title: How to locally unit-test Chainlink's Verifiable Random Function?\nTags: unit-testing, random, solidity, chainlink\nSource: Stack Overflow\n\nQuestion:\n### Context\n\nWhile trying to set up a basic self-hosted unit testing environment (and CI) that tests this Chainlink VRF random number contract, I am experiencing slight difficulties in how to simulate any relevant blockchains/testnets locally.\n\nFor example, I found this repository that tests Chainlinks VRF. However, for default deployment it suggests/requires a free `KOVAN_RPC_URL` e.g. from Infura's site and even for \"local deployment\" it suggests/requires a free `MAINNET_RPC_URL` from e.g. Alchemy's site.\n\n### Attempt/baseline\n\nI adopted a unit test environment from the waffle framework which is described as:\n\n### Filestructure\n\n```\nsrc____AmIRichAlready.sol\n |____RandomNumberConsumer.sol\n |\ntest____AmIRichAlready.test.ts\n |____mocha.opts\npackage.json\ntsconfig.json\nwaffle.json\nyarn.lock\n```\n\n### Filecontents\n\nAmIRichAlready.sol\n\n```\npragma solidity ^0.6.2;\n\ninterface IERC20 {\n function balanceOf(address account) external view returns (uint256);\n}\n\ncontract AmIRichAlready {\n IERC20 private tokenContract;\n uint public richness = 1000000 * 10 ** 18;\n\n constructor (IERC20 _tokenContract) public {\n tokenContract = _tokenContract;\n }\n\n function check() public view returns (bool) {\n uint balance = tokenContract.balanceOf(msg.sender);\n return balance > richness;\n }\n\n // IS THIS NEEDED???\n function setRichness(uint256 _richness) public {\n richness = _richness;\n }\n}\n```\n\nThe `RandomNumberConsumer.sol` filecontent is already on stackexange over here.\n\nAmIRichAlready.test.ts\n\n```\nimport {expect, use} from 'chai';\nimport {Contract, utils, Wallet} from 'ethers';\nimport {deployContract, deployMockContract, MockProvider, solidity} from 'ethereum-waffle';\n\nimport IERC20 from '../build/IERC20.json';\nimport AmIRichAlready from '../build/AmIRichAlready.json';\n\nuse(solidity);\n\ndescribe('Am I Rich Already', () => {\n let mockERC20: Contract;\n let contract: Contract;\n let vrfContract: Contract;\n let wallet: Wallet;\n\n beforeEach(async () => {\n [wallet] = new MockProvider().getWallets();\n mockERC20 = await deployMockContract(wallet, IERC20.abi);\n contract = await deployContract(wallet, AmIRichAlready, [mockERC20.address]);\n vrfContract = await deployContract(wallet, RandomNumberConsumer);\n });\n\n it('checks if contract called balanceOf with certain wallet on the ERC20 token', async () => {\n await mockERC20.mock.balanceOf\n .withArgs(wallet.address)\n .returns(utils.parseEther('999999'));\n await contract.check();\n expect('balanceOf').to.be.calledOnContractWith(mockERC20, [wallet.address]);\n });\n\n it('returns false if the wallet has less than 1000000 coins', async () => {\n await mockERC20.mock.balanceOf\n .withArgs(wallet.address)\n .returns(utils.parseEther('999999'));\n expect(await contract.check()).to.be.equal(false);\n });\n\n it('returns true if the wallet has at least 1000000 coins', async () => {\n await mockERC20.mock.balanceOf\n .withArgs(wallet.address)\n .returns(utils.parseEther('1000000'));\n expect(await contract.check()).to.be.equal(false);\n });\n});\n```\n\nmocha.opts\n\n```\n-r ts-node/register/transpile-only\n--timeout 50000\n--no-warnings\ntest/**/*.test.{js,ts}\n```\n\npackage.json\n\n```\n{\n \"name\": \"example-dynamic-mocking-and-testing-calls\",\n \"version\": \"1.0.0\",\n \"main\": \"index.js\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"test\": \"export NODE_ENV=test && mocha\",\n \"build\": \"waffle\",\n \"lint\": \"eslint '{src,test}/**/*.ts'\",\n \"lint:fix\": \"eslint --fix '{src,test}/**/*.ts'\"\n },\n \"devDependencies\": {\n \"@openzeppelin/contracts\": \"^4.3.1\",\n \"@types/chai\": \"^4.2.3\",\n \"@types/mocha\": \"^5.2.7\",\n \"@typescript-eslint/eslint-plugin\": \"^2.30.0\",\n \"@typescript-eslint/parser\": \"^2.30.0\",\n \"chai\": \"^4.3.4\",\n \"eslint\": \"^6.8.0\",\n \"eslint-plugin-import\": \"^2.20.2\",\n \"ethereum-waffle\": \"^3.4.0\",\n \"ethers\": \"^5.0.17\",\n \"mocha\": \"^7.2.0\",\n \"ts-node\": \"^8.9.1\",\n \"typescript\": \"^3.8.3\"\n }\n}\n```\n\ntsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"declaration\": true,\n \"esModuleInterop\": true,\n \"lib\": [\n \"ES2018\"\n ],\n \"module\": \"CommonJS\",\n \"moduleResolution\": \"node\",\n \"outDir\": \"dist\",\n \"resolveJsonModule\": true,\n \"skipLibCheck\": true,\n \"strict\": true,\n \"target\": \"ES2018\"\n }\n\n // custom test in vrfContract\n it('Tests if a random number is returned', async () => {\n expect(await vrfContract.getRandomNumber()).to.be.equal(7);\n });\n}\n```\n\nwaffle.json\n\n```\n{\n \"compilerType\": \"solcjs\",\n \"compilerVersion\": \"0.6.2\",\n \"sourceDirectory\": \"./src\",\n \"outputDirectory\": \"./build\"\n}\n```\n\nThe `yarn.lock` file content is a bit large, and it's auto-generated, so you can find it on the Waffle framework repository. Similarly, the `package.json` can be found here, in the same repository.\n\n### Commands\n\nOne can also simply clone the repo with the specified filestructure here, and run the tests with the following commands:\n\n```\ngit clone git@github.com:a-t-2/chainlink.git\ngit clone git@github.com:a-t-2/test_vrf3.git\ncd test_vrf3\nsudo apt install npm\nnpm install\nnpm audit fix\nnpm install --save-dev ethereum-waffle\nnpm install @openzeppelin/contracts -D\nnpm i chai -D\nnpm i mocha -D\nrm -r build\nnpx waffle\nnpx mocha\nnpm test\n```\n\n### Test Output\n\nThis will test the `AmIRichAlready.sol` file and output:\n\n```\nAm I Rich Already\n ✓ checks if contract called balanceOf with certain wallet on the ERC20 token (249ms)\n ✓ returns false if the wallet has less than 1000000 coins (190ms)\n ✓ returns true if the wallet has at least 1000000 coins (159ms)\n Tests if a random number is returned:\n Error: cannot estimate gas; transaction may fail or may require manual gas limit (error={\"name\":\"RuntimeError\",\"results\":{\"0x0a0b028de6cf6e8446853a300061305501136cefa5f5eb3e96afd95dbd73dd92\":{\"error\":\"revert\",\"program_counter\":609,\"return\":\"0x\"}},\"hashes\":[\"0x0a0b028de6cf6e8446853a300061305501136cefa5f5eb3e96afd95dbd73dd92\"],\"message\":\"VM Exception while processing transaction: revert\"}, tx={\"data\":\"0xdbdff2c1\",\"to\":{},\"from\":\"0x17ec8597ff92C3F44523bDc65BF0f1bE632917ff\",\"gasPrice\":{\"type\":\"BigNumber\",\"hex\":\"0x77359400\"},\"type\":0,\"nonce\":{},\"gasLimit\":{},\"chainId\":{}}, code=UNPREDICTABLE_GAS_LIMIT, version=abstract-signer/5.4.1)\n at Logger.makeError (node_modules/@ethersproject/logger/src.ts/index.ts:225:28)\n at Logger.throwError (node_modules/@ethersproject/logger/src.ts/index.ts:237:20)\n at /home/name/git/trucol/tested/new_test/test_vrf3/node_modules/@ethersproject/abstract-signer/src.ts/index.ts:301:31\n at process._tickCallback (internal/process/next_tick.js:68:7)\n\n 3 passing (4s)\n```\n\n### Question\n\nWhich set of files, file structure and commands do I need to automatically test whether the `getRandomNumber()` contract returns an integer if sufficient \"gas\" is provided, and an error otherwise?\n\n========================================\n\nTop Answer:\nto test locally you need to make use of mocks which can simulate having an oracle network. Because you're working locally, a Chainlink node doesn't know about your local blockchain, so you can't actually do proper VRF requests. Note you can try deploy a local Chainlink node and a local blockchain and have them talk, but it isn't fully supported yet so you may get mixed results. Anyway, as per the hardhat starter kit that you linked, you can set the defaultNetwork to be 'hardhat' in the hardhat.config.js file, then when you deploy and run the integration tests (yarn test-integration), it will use mocks to mock up the VRF node, and to test the requesting of a random number. See the test here, and the mock contracts and linktoken get deployed here\n\n========================================\n\nCode:\n```text\nsrc____AmIRichAlready.sol\n   |____RandomNumberConsumer.sol\n   |\ntest____AmIRichAlready.test.ts\n   |____mocha.opts\npackage.json\ntsconfig.json\nwaffle.json\nyarn.lock\n```\n\n```text\npragma solidity ^0.6.2;\n\ninterface IERC20 {\n    function balanceOf(address account) external view returns (uint256);\n}\n\ncontract AmIRichAlready {\n    IERC20 private tokenContract;\n    uint public richness = 1000000 * 10 ** 18;\n\n    constructor (IERC20 _tokenContract) public {\n        tokenContract = _tokenContract;\n    }\n\n    function check() public view returns (bool) {\n        uint balance = tokenContract.balanceOf(msg.sender);\n        return balance > richness;\n    }\n\n    // IS THIS NEEDED???\n    function setRichness(uint256 _richness) public {\n      richness = _richness;\n    }\n}\n```\n\n```text\nimport {expect, use} from 'chai';\nimport {Contract, utils, Wallet} from 'ethers';\nimport {deployContract, deployMockContract, MockProvider, solidity} from 'ethereum-waffle';\n\nimport IERC20 from '../build/IERC20.json';\nimport AmIRichAlready from '../build/AmIRichAlready.json';\n\nuse(solidity);\n\ndescribe('Am I Rich Already', () => {\n  let mockERC20: Contract;\n  let contract: Contract;\n  let vrfContract: Contract;\n  let wallet: Wallet;\n\n  beforeEach(async () => {\n    [wallet] = new MockProvider().getWallets();\n    mockERC20 = await deployMockContract(wallet, IERC20.abi);\n    contract = await deployContract(wallet, AmIRichAlready, [mockERC20.address]);\n    vrfContract = await deployContract(wallet, RandomNumberConsumer);\n  });\n\n  it('checks if contract called balanceOf with certain wallet on the ERC20 token', async () => {\n    await mockERC20.mock.balanceOf\n      .withArgs(wallet.address)\n      .returns(utils.parseEther('999999'));\n    await contract.check();\n    expect('balanceOf').to.be.calledOnContractWith(mockERC20, [wallet.address]);\n  });\n\n  it('returns false if the wallet has less than 1000000 coins', async () => {\n    await mockERC20.mock.balanceOf\n      .withArgs(wallet.address)\n      .returns(utils.parseEther('999999'));\n    expect(await contract.check()).to.be.equal(false);\n  });\n\n  it('returns true if the wallet has at least 1000000 coins', async () => {\n    await mockERC20.mock.balanceOf\n      .withArgs(wallet.address)\n      .returns(utils.parseEther('1000000'));\n    expect(await contract.check()).to.be.equal(false);\n  });\n});\n```\n\n```text\n-r ts-node/register/transpile-only\n--timeout 50000\n--no-warnings\ntest/**/*.test.{js,ts}\n```\n\n```text\n{\n  \"name\": \"example-dynamic-mocking-and-testing-calls\",\n  \"version\": \"1.0.0\",\n  \"main\": \"index.js\",\n  \"license\": \"MIT\",\n  \"scripts\": {\n    \"test\": \"export NODE_ENV=test && mocha\",\n    \"build\": \"waffle\",\n    \"lint\": \"eslint '{src,test}/**/*.ts'\",\n    \"lint:fix\": \"eslint --fix '{src,test}/**/*.ts'\"\n  },\n  \"devDependencies\": {\n    \"@openzeppelin/contracts\": \"^4.3.1\",\n    \"@types/chai\": \"^4.2.3\",\n    \"@types/mocha\": \"^5.2.7\",\n    \"@typescript-eslint/eslint-plugin\": \"^2.30.0\",\n    \"@typescript-eslint/parser\": \"^2.30.0\",\n    \"chai\": \"^4.3.4\",\n    \"eslint\": \"^6.8.0\",\n    \"eslint-plugin-import\": \"^2.20.2\",\n    \"ethereum-waffle\": \"^3.4.0\",\n    \"ethers\": \"^5.0.17\",\n    \"mocha\": \"^7.2.0\",\n    \"ts-node\": \"^8.9.1\",\n    \"typescript\": \"^3.8.3\"\n  }\n}\n```\n\n```text\n{\n  \"compilerOptions\": {\n    \"declaration\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\n      \"ES2018\"\n    ],\n    \"module\": \"CommonJS\",\n    \"moduleResolution\": \"node\",\n    \"outDir\": \"dist\",\n    \"resolveJsonModule\": true,\n    \"skipLibCheck\": true,\n    \"strict\": true,\n    \"target\": \"ES2018\"\n  }\n\n  // custom test in vrfContract\n  it('Tests if a random number is returned', async () => {\n    expect(await vrfContract.getRandomNumber()).to.be.equal(7);\n  });\n}\n```\n\n```text\n{\n  \"compilerType\": \"solcjs\",\n  \"compilerVersion\": \"0.6.2\",\n  \"sourceDirectory\": \"./src\",\n  \"outputDirectory\": \"./build\"\n}\n```\n\n```text\ngit clone git@github.com:a-t-2/chainlink.git\ngit clone git@github.com:a-t-2/test_vrf3.git\ncd test_vrf3\nsudo apt install npm\nnpm install\nnpm audit fix\nnpm install --save-dev ethereum-waffle\nnpm install @openzeppelin/contracts -D\nnpm i chai -D\nnpm i mocha -D\nrm -r build\nnpx waffle\nnpx mocha\nnpm test\n```\n\n```text\nAm I Rich Already\n    ✓ checks if contract called balanceOf with certain wallet on the ERC20 token (249ms)\n    ✓ returns false if the wallet has less than 1000000 coins (190ms)\n    ✓ returns true if the wallet has at least 1000000 coins (159ms)\n    Tests if a random number is returned:\n     Error: cannot estimate gas; transaction may fail or may require manual gas limit (error={\"name\":\"RuntimeError\",\"results\":{\"0x0a0b028de6cf6e8446853a300061305501136cefa5f5eb3e96afd95dbd73dd92\":{\"error\":\"revert\",\"program_counter\":609,\"return\":\"0x\"}},\"hashes\":[\"0x0a0b028de6cf6e8446853a300061305501136cefa5f5eb3e96afd95dbd73dd92\"],\"message\":\"VM Exception while processing transaction: revert\"}, tx={\"data\":\"0xdbdff2c1\",\"to\":{},\"from\":\"0x17ec8597ff92C3F44523bDc65BF0f1bE632917ff\",\"gasPrice\":{\"type\":\"BigNumber\",\"hex\":\"0x77359400\"},\"type\":0,\"nonce\":{},\"gasLimit\":{},\"chainId\":{}}, code=UNPREDICTABLE_GAS_LIMIT, version=abstract-signer/5.4.1)\n      at Logger.makeError (node_modules/@ethersproject/logger/src.ts/index.ts:225:28)\n      at Logger.throwError (node_modules/@ethersproject/logger/src.ts/index.ts:237:20)\n      at /home/name/git/trucol/tested/new_test/test_vrf3/node_modules/@ethersproject/abstract-signer/src.ts/index.ts:301:31\n      at process._tickCallback (internal/process/next_tick.js:68:7)\n\n\n\n  3 passing (4s)\n```\n\n```text\nKOVAN_RPC_URL\n```\n\n```text\nMAINNET_RPC_URL\n```\n\n```text\nRandomNumberConsumer.sol\n```\n\n```text\nyarn.lock\n```\n\n```text\npackage.json\n```\n\n```text\nAmIRichAlready.sol\n```\n\n```text\ngetRandomNumber()\n```\n\n```text\n//SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol\";\n\ncontract MockVRFCoordinator {\n    uint256 internal counter = 0;\n\n    function requestRandomWords(\n        bytes32,\n        uint64,\n        uint16,\n        uint32,\n        uint32\n    ) external returns (uint256 requestId) {\n        VRFConsumerBaseV2 consumer = VRFConsumerBaseV2(msg.sender);\n        uint256[] memory randomWords = new uint256[](1);\n        randomWords[0] = counter;\n        consumer.rawFulfillRandomWords(requestId, randomWords);\n        counter += 1;\n    }\n}\n```\n\n========================================\n\nComments:\n- the chainlink doc mentions also mainnet forking, have you succeed using it for VRF? Have you managed to write local unit-test with VRF V2?\n- @ClementWalter I'm pretty sure mainnet forking does not work for testing VRF (v1 or v2). You should instead use local mocks.\n- so actually I've been able to use rinkeby forking up to latest block to avoid using mocks for the coordinator by deploying locally then going to the vrf v2 dashbord to add my local contract address as subscriber then running tests with forking. This is not ideal though\n- @ClementWalter would you care to your forking procedure? I have been unable to fork rinkeby for VRF integration testing.\n- I have eventually written a whole tuto for this mirror.xyz/clemlaflemme.eth/&hellip; @RndmSymbl\n- Ah great, so that's basically the mockup approach, right? Does that give you any confidence on the whole system testing?","metadata":{"transformedAt":"2026-08-18T18:33:36.125Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":495,"estimatedTokens":3706}}138{"id":"stack-45867572","source":"stackoverflow","questionId":45867572,"title":"Solidity return function why the constant?","tags":["ethereum","solidity"],"text":"Title: Solidity return function why the constant?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI am just starting with solidity. I have a function like so:\n\n```\nfunction get() constant returns (uint) {\n return storedData;\n }\n```\n\nWhat is the use of the constant keyword here? I understand that after this keyboard we are defining the return type but why does it need constant in front of it? Are there alternatives to this such as `var`?\n\n========================================\n\nTop Answer:\nTo give a little more context a constant declaration indicates that the function will not change the state of the contract (although currently this is not enforced by the compiler).\n\nWhen generating the compiled binaries, declaring a function `constant` is reflected on the ABI. The ABI is then interpreted by web3 to figure out whether it should send a `sendTransaction()` or a `call()` message to the Ethereum node. Since calls are only executed locally, they're effectively free.\n\nSee this snippet from the web3.js library:\n\n```\n/**\n * Should be called to execute function\n *\n * @method execute\n */\nSolidityFunction.prototype.execute = function () {\n var transaction = !this._constant;\n\n // send transaction\n if (transaction) {\n return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments));\n }\n\n // call\n return this.call.apply(this, Array.prototype.slice.call(arguments));\n};\n```\n\nCalling a constant function from another contract incurs the same cost as any other regular function.\n\n========================================\n\nCode:\n```text\nfunction get() constant returns (uint) {\n    return storedData;\n  }\n```\n\n```text\nvar\n```\n\n```text\n/**\n * Should be called to execute function\n *\n * @method execute\n */\nSolidityFunction.prototype.execute = function () {\n    var transaction = !this._constant;\n\n    // send transaction\n    if (transaction) {\n        return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments));\n    }\n\n    // call\n    return this.call.apply(this, Array.prototype.slice.call(arguments));\n};\n```\n\n```text\nconstant\n```\n\n```text\nsendTransaction()\n```\n\n```text\ncall()\n```\n\n========================================\n\nComments:\n- Excellent! Thanks for your answer.\n- What about function `set(uint x) { storedData = x; }` what would happen if I add the keyword constant to this? Why does the `get` need the word constant? Would it cost gas if omitted even though it doesn't modify data?\n- \"constant on functions used to be an alias to view, but this was dropped in version 0.5.0.\" docs.soliditylang.org/en/v0.8.10/&hellip;\n- If it incurs the same cost, why do I need it then? Why is it used in the `ERC20 balanceOf()` function? the function only returns `return balances[_owner];` and changes no state. Where is the sense of it?\n- just to be more clear, is it not better a developer uses the view modifier for a function instead of constant as view function ensures that the state of the contract is not altered & it also enforces that","metadata":{"transformedAt":"2026-08-18T18:33:36.125Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":97,"estimatedTokens":749}}139{"id":"stack-68310368","source":"stackoverflow","questionId":68310368,"title":"how to calculate percentage in solidity","tags":["ethereum","solidity"],"text":"Title: how to calculate percentage in solidity\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\n```\nfunction splitAmount(uint256 amount) private {\n a1.transfer(amount.div(2));\n a2.transfer(amount.div(2));\n }\n```\n\nI've seen other threads on this but I feel like over complicate things. With this code the amount is evenly split between a1 and a2 with division by 2.\n\nHow would one do something like a 80/20 split with the same code?\n\n========================================\n\nCode:\n```text\nfunction splitAmount(uint256 amount) private {\n        a1.transfer(amount.div(2));\n        a2.transfer(amount.div(2));\n    }\n```\n\n```text\na1.transfer(amount.mul(4).div(5)); // 80% of `amount`\n```\n\n```text\na2.transfer(amount.div(5)); // 20% of `amount`\n```\n\n========================================\n\nComments:\n- Would then \"a1.transfer(amount.div(100).mul(80));\" be the same thing?\n- @Alessandro Yes for `amount`s divisible by 100... If you had `amount` value 50, the `.div(5).mul(4)` would return 40 as expected. But the `.div(100).mul(80)` would return 0, because at first it calculates `50 &#47; 100` (which results in the unsigned integer 0), and then `0 * 80`.\n- what if you want a decimal percentage value? Example 0,001%\n- @R01010010 Then you can divide by a larger number. As per your example, if you want to get 0.001% of `amount`, then you calculate `amount.div(100000)`","metadata":{"transformedAt":"2026-08-18T18:33:36.125Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":41,"estimatedTokens":345}}140{"id":"stack-44029634","source":"stackoverflow","questionId":44029634,"title":"Ethereum / Solidity getting smartcontract events in the geth console","tags":["ethereum","solidity","smartcontracts"],"text":"Title: Ethereum / Solidity getting smartcontract events in the geth console\nTags: ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nSo I tried to retrieve the events generated by my smartcontract\n\n\r\n\r\n\n```\nvar abi = [{\r\n \"constant\": false,\r\n \"inputs\": [{\r\n \"name\": \"_value\",\r\n \"type\": \"int32\"\r\n }],\r\n \"name\": \"changeLowerTrigger\",\r\n \"outputs\": [],\r\n \"payable\": false,\r\n \"type\": \"function\"\r\n}, {\r\n \"constant\": true,\r\n \"inputs\": [],\r\n \"name\": \"metric\",\r\n \"outputs\": [{\r\n \"name\": \"name\",\r\n \"type\": \"string\",\r\n \"value\": \"place_holder_metric_name_to_be_autogenerated\"\r\n }, {\r\n \"name\": \"value\",\r\n \"type\": \"int32\",\r\n \"value\": \"7\"\r\n }],\r\n \"payable\": false,\r\n \"type\": \"function\"\r\n}, {\r\n \"constant\": false,\r\n \"inputs\": [{\r\n \"name\": \"_value\",\r\n \"type\": \"int32\"\r\n }],\r\n \"name\": \"changeUpperTrigger\",\r\n \"outputs\": [],\r\n \"payable\": false,\r\n \"type\": \"function\"\r\n}, {\r\n \"constant\": false,\r\n \"inputs\": [{\r\n \"name\": \"_value\",\r\n \"type\": \"int32\"\r\n }],\r\n \"name\": \"update\",\r\n \"outputs\": [],\r\n \"payable\": false,\r\n \"type\": \"function\"\r\n}, {\r\n \"anonymous\": false,\r\n \"inputs\": [{\r\n \"indexed\": false,\r\n \"name\": \"_value\",\r\n \"type\": \"int32\"\r\n }],\r\n \"name\": \"ValueChanged\",\r\n \"type\": \"event\"\r\n}, {\r\n \"anonymous\": false,\r\n \"inputs\": [{\r\n \"indexed\": false,\r\n \"name\": \"_alarm\",\r\n \"type\": \"string\"\r\n }, {\r\n \"indexed\": false,\r\n \"name\": \"_value\",\r\n \"type\": \"int32\"\r\n }],\r\n \"name\": \"Alarm\",\r\n \"type\": \"event\"\r\n}]\r\nvar MyContract = web3.eth.contract(abi);\r\n\r\nvar myContractInstance = MyContract.at(\r\n '0x3B03c46Dfc878FeF9fAe8de4E32a6718f2E250e9');\r\n\r\nvar events = myContractInstance.allEvents();\r\n\r\n// watch for changes\r\nevents.watch(function(error, event) {\r\n if (!error)\r\n console.log(event);\r\n});\r\n\r\n// Or pass a callback to start watching immediately\r\nvar events = myContractInstance.allEvents(function(error, log) {\r\n console.log(err, log);\r\n});\n```\n\n\r\n\r\n\r\n\nBut it returns only:\n\n\r\n\r\n\n```\n> events\r\n{\r\n callbacks: [function(error, log)],\r\n filterId: \"0xd6af6f5a7273fe21452f00c4682456\",\r\n getLogsCallbacks: [],\r\n implementation: {\r\n getLogs: function(),\r\n newFilter: function(),\r\n poll: function(),\r\n uninstallFilter: function()\r\n },\r\n options: {\r\n address: \"0x3B03c46Dfc878FeF9fAe8de4E32a6718f2E250e9\",\r\n from: undefined,\r\n fromBlock: undefined,\r\n to: undefined,\r\n toBlock: undefined,\r\n topics: []\r\n },\r\n pollFilters: [],\r\n requestManager: {\r\n polls: {\r\n 0xd6af6f5a7273fe21452f00c4682456: {\r\n data: {...},\r\n id: \"0xd6af6f5a7273fe21452f00c4682456\",\r\n callback: function(error, messages),\r\n uninstall: function()\r\n }\r\n },\r\n provider: {\r\n newAccount: function(),\r\n send: function github.com/ethereum/go-ethereum/console.(*bridge).Send-fm(),\r\n sendAsync: function github.com/ethereum/go-ethereum/console.(*bridge).Send-fm(),\r\n sign: function(),\r\n unlockAccount: function()\r\n },\r\n timeout: {},\r\n poll: function(),\r\n reset: function(keepIsSyncing),\r\n send: function(data),\r\n sendAsync: function(data, callback),\r\n sendBatch: function(data, callback),\r\n setProvider: function(p),\r\n startPolling: function(data, pollId, callback, uninstall),\r\n stopPolling: function(pollId)\r\n },\r\n formatter: function(),\r\n get: function(callback),\r\n stopWatching: function(callback),\r\n watch: function(callback)\r\n}\n```\n\n\r\n\r\n\r\n\nBut what I want, is the events shown in the next image at the very bottom(e.g.Value Changed value:7):\nhttps://i.sstatic.net/M9ia6.png\n\nSince the events are displayed in the ETH-Wallet there should be a way. I rly just want a way to get the latest events in the geth console (or sth similare).\nThanks for any help I'm kinda lost and having some of the worst googling of my life.\n\n========================================\n\nCode:\n```js\nvar abi = [{\n  \"constant\": false,\n  \"inputs\": [{\n    \"name\": \"_value\",\n    \"type\": \"int32\"\n  }],\n  \"name\": \"changeLowerTrigger\",\n  \"outputs\": [],\n  \"payable\": false,\n  \"type\": \"function\"\n}, {\n  \"constant\": true,\n  \"inputs\": [],\n  \"name\": \"metric\",\n  \"outputs\": [{\n    \"name\": \"name\",\n    \"type\": \"string\",\n    \"value\": \"place_holder_metric_name_to_be_autogenerated\"\n  }, {\n    \"name\": \"value\",\n    \"type\": \"int32\",\n    \"value\": \"7\"\n  }],\n  \"payable\": false,\n  \"type\": \"function\"\n}, {\n  \"constant\": false,\n  \"inputs\": [{\n    \"name\": \"_value\",\n    \"type\": \"int32\"\n  }],\n  \"name\": \"changeUpperTrigger\",\n  \"outputs\": [],\n  \"payable\": false,\n  \"type\": \"function\"\n}, {\n  \"constant\": false,\n  \"inputs\": [{\n    \"name\": \"_value\",\n    \"type\": \"int32\"\n  }],\n  \"name\": \"update\",\n  \"outputs\": [],\n  \"payable\": false,\n  \"type\": \"function\"\n}, {\n  \"anonymous\": false,\n  \"inputs\": [{\n    \"indexed\": false,\n    \"name\": \"_value\",\n    \"type\": \"int32\"\n  }],\n  \"name\": \"ValueChanged\",\n  \"type\": \"event\"\n}, {\n  \"anonymous\": false,\n  \"inputs\": [{\n    \"indexed\": false,\n    \"name\": \"_alarm\",\n    \"type\": \"string\"\n  }, {\n    \"indexed\": false,\n    \"name\": \"_value\",\n    \"type\": \"int32\"\n  }],\n  \"name\": \"Alarm\",\n  \"type\": \"event\"\n}]\nvar MyContract = web3.eth.contract(abi);\n\nvar myContractInstance = MyContract.at(\n  '0x3B03c46Dfc878FeF9fAe8de4E32a6718f2E250e9');\n\nvar events = myContractInstance.allEvents();\n\n// watch for changes\nevents.watch(function(error, event) {\n  if (!error)\n    console.log(event);\n});\n\n// Or pass a callback to start watching immediately\nvar events = myContractInstance.allEvents(function(error, log) {\n  console.log(err, log);\n});\n```\n\n```js\n> events\n{\n  callbacks: [function(error, log)],\n  filterId: \"0xd6af6f5a7273fe21452f00c4682456\",\n  getLogsCallbacks: [],\n  implementation: {\n    getLogs: function(),\n    newFilter: function(),\n    poll: function(),\n    uninstallFilter: function()\n  },\n  options: {\n    address: \"0x3B03c46Dfc878FeF9fAe8de4E32a6718f2E250e9\",\n    from: undefined,\n    fromBlock: undefined,\n    to: undefined,\n    toBlock: undefined,\n    topics: []\n  },\n  pollFilters: [],\n  requestManager: {\n    polls: {\n      0xd6af6f5a7273fe21452f00c4682456: {\n        data: {...},\n        id: \"0xd6af6f5a7273fe21452f00c4682456\",\n        callback: function(error, messages),\n        uninstall: function()\n      }\n    },\n    provider: {\n      newAccount: function(),\n      send: function github.com/ethereum/go-ethereum/console.(*bridge).Send-fm(),\n      sendAsync: function github.com/ethereum/go-ethereum/console.(*bridge).Send-fm(),\n      sign: function(),\n      unlockAccount: function()\n    },\n    timeout: {},\n    poll: function(),\n    reset: function(keepIsSyncing),\n    send: function(data),\n    sendAsync: function(data, callback),\n    sendBatch: function(data, callback),\n    setProvider: function(p),\n    startPolling: function(data, pollId, callback, uninstall),\n    stopPolling: function(pollId)\n  },\n  formatter: function(),\n  get: function(callback),\n  stopWatching: function(callback),\n  watch: function(callback)\n}\n```\n\n```text\nget()\n```\n\n========================================\n\nComments:\n- Found an API for it/(other things) eventually but great to see an answer after all this time^^","metadata":{"transformedAt":"2026-08-18T18:33:36.125Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":324,"estimatedTokens":1708}}141{"id":"stack-70011183","source":"stackoverflow","questionId":70011183,"title":"Solidity - Invalid BigNumber string (argument=\"value\" value=\"\" code=INVALID_ARGUMENT version=bignumber/5.4.2)","tags":["solidity","remix"],"text":"Title: Solidity - Invalid BigNumber string (argument=\"value\" value=\"\" code=INVALID_ARGUMENT version=bignumber/5.4.2)\nTags: solidity, remix\nSource: Stack Overflow\n\nQuestion:\nsolidity newbie here. when I try to read the value of the people array. I'm getting an error:\n\ncall to SimpleStorage.people errored: Error encoding arguments: Error:\ninvalid BigNumber string (argument=\"value\" value=\"\"\ncode=INVALID_ARGUMENT version=bignumber/5.4.2)\n\nmy compiler version is 0.6.6. not sure what's wrong? any suggestions?\n\n```\n// SPD-License_Identifier: MIT\n\npragma solidity ^0.6.0;\n\ncontract SimpleStorage {\n uint256 favNum;\n \n struct People {\n uint256 favNum;\n string name;\n }\n \n People[] public people;\n \n function store(uint256 _favNum) public {\n favNum = _favNum;\n }\n \n function retrieve() public view returns(uint256) {\n return favNum;\n }\n \n function addPerson(string memory _name, uint256 _favNum) public {\n people.push(People(_favNum, _name));\n }\n}\n```\n\n========================================\n\nTop Answer:\nYou must click on the small arrow to the right of the deploy button, then the fields will be displayed so that you can complete the data that the contract must receive.\nhttps://i.sstatic.net/6avy7.png\n\n========================================\n\nCode:\n```text\n// SPD-License_Identifier: MIT\n\npragma solidity ^0.6.0;\n\ncontract SimpleStorage {\n    uint256 favNum;\n    \n    struct People {\n        uint256 favNum;\n        string name;\n    }\n    \n    People[] public people;\n    \n    function store(uint256 _favNum) public {\n        favNum = _favNum;\n    }\n    \n    function retrieve() public view returns(uint256) {\n        return favNum;\n    }\n    \n    function addPerson(string memory _name, uint256 _favNum) public {\n        people.push(People(_favNum, _name));\n    }\n}\n```\n\n```text\nfunction getAllPeople() public view returns (People[] memory) {\n    return people;\n}\n```\n\n```text\npeople()\n```\n\n```text\nPeople[] public people\n```\n\n```text\nuint256\n```\n\n```text\nBigNumber\n```\n\n========================================\n\nComments:\n- Can you please elaborate a bit more. Actually I just wanna know when i only create a `constructor(with some parameters)` then ofc the default constructor will not be created.... But the problem is what is the solution to this .... Do i need to make a constructor without arguments explicitly???? If yes then how???\n- @dammn_man123 You always need to pass all defined values to a function - no matter if it's a regular function or a constructor. From the code provided in your other question it seems that you're not passing either `acc_id` or `_balance`.\n- I resolved the error. The code is successfully working now. You were right I wasn't passing values initially. Thanks for help.\n- @dammn_man123 How do you pass values initially?\n- @SamTseng If you are using Remix IDE, go to the \"Deploy & run transactions\" tab and click the drop down arrow next to \"Deploy\". It should open up a tiny form where you can enter the values\n- @vajad if you have two arguments to incluede, but you forget to pass one argument, in that case also it gives this above error.","metadata":{"transformedAt":"2026-08-18T18:33:36.125Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":111,"estimatedTokens":771}}142{"id":"stack-69271231","source":"stackoverflow","questionId":69271231,"title":"Error Verifying smart contract on EtherScan using Hardhat","tags":["solidity","smartcontracts","openzeppelin","hardhat"],"text":"Title: Error Verifying smart contract on EtherScan using Hardhat\nTags: solidity, smartcontracts, openzeppelin, hardhat\nSource: Stack Overflow\n\nQuestion:\nBelow is my smart contract (already deployed). When i try and verify it to submit the code to Etherscan I am getting the error below and I really don't know why. Please can someone advise?\n\n```\nnpx hardhat verify --network ropsten 0xE9abA803d6a801fce021d0074ae71256C9F24Da4\n```\n\nError Message:\n\n```\nError in plugin @nomiclabs/hardhat-etherscan: More than one contract was found to match the deployed bytecode.\n Please use the contract parameter with one of the following contracts:\n * @openzeppelin/contracts/finance/PaymentSplitter.sol:PaymentSplitter\n * contracts/MyNFTContract.sol: MyNFTContract\n\n For example:\n\n hardhat verify --contract contracts/Example.sol:ExampleContract \n\n If you are running the verify subtask from within Hardhat instead:\n\n await run(\"verify:verify\", {\n ,\n contract: \"contracts/Example.sol:ExampleContract\"\n };\n```\n\nMyNFTContract.sol:\n\n```\n// SPDX-License-Identifier: MIT\n pragma solidity ^0.8.0;\n\n import \"@openzeppelin/contracts/finance/PaymentSplitter.sol\";\n\n contract MyNFTContract is PaymentSplitter {\n // Addresses of payees\n address[] private _CSPayees = [\n 0x23377d974d85C49E9CB6cfdF4e0EED1C0Fc85E6A,\n 0x85F68F10d3c13867FD36f2a353eeD56533f1C751\n ];\n // Number of shares allocated per address in this contract. In same order as _CSPayees\n uint256[] private _CSShares = [1, 2];\n\n constructor() PaymentSplitter(_CSPayees, _CSShares) {}\n }\n```\n\nMy deploying script deploy.js:\n\n```\nasync function main() {\nconst PaymentSplitter = await ethers.getContractFactory(\"MyNFTContract\")\n\n// Start deployment, returning a promise that resolves to a contract object\nconst myNFT = await PaymentSplitter.deploy()\nconsole.log(\"Contract deployed to address:\", myNFT.address)\n }\n\n main()\n.then(() => process.exit(0))\n.catch((error) => {\n console.error(error)\n process.exit(1)\n})\n```\n\n========================================\n\nTop Answer:\nHardhat found multiple contracts in the project (your `MyNFTContract` and the imported `PaymentSplitter`), and it doesn't know against which one you want to verify the bytecode.\n\nYou need to specify the contract (that you want to verify) with the `--contract` option.\n\n```\nnpx hardhat verify \\\n--contract \"contracts/MyNFTContract.sol\" \\\n--network ropsten 0xE9abA803d6a801fce021d0074ae71256C9F24Da4\n```\n\n========================================\n\nCode:\n```text\nnpx hardhat verify --network ropsten 0xE9abA803d6a801fce021d0074ae71256C9F24Da4\n```\n\n```text\nError in plugin @nomiclabs/hardhat-etherscan: More than one contract was found to match the deployed bytecode.\n Please use the contract parameter with one of the following contracts:\n * @openzeppelin/contracts/finance/PaymentSplitter.sol:PaymentSplitter\n  * contracts/MyNFTContract.sol: MyNFTContract\n\n For example:\n\n   hardhat verify --contract contracts/Example.sol:ExampleContract <other args>\n\n If you are running the verify subtask from within Hardhat instead:\n\n   await run(\"verify:verify\", {\n     <other args>,\n     contract: \"contracts/Example.sol:ExampleContract\"\n  };\n```\n\n```text\n// SPDX-License-Identifier: MIT\n pragma solidity ^0.8.0;\n\n import \"@openzeppelin/contracts/finance/PaymentSplitter.sol\";\n\n contract MyNFTContract is PaymentSplitter {\n     // Addresses of payees\n     address[] private _CSPayees = [\n         0x23377d974d85C49E9CB6cfdF4e0EED1C0Fc85E6A,\n         0x85F68F10d3c13867FD36f2a353eeD56533f1C751\n     ];\n     // Number of shares allocated per address in this contract.  In same order as _CSPayees\n     uint256[] private _CSShares = [1, 2];\n\n     constructor() PaymentSplitter(_CSPayees, _CSShares) {}\n }\n```\n\n```text\nasync function main() {\nconst PaymentSplitter = await ethers.getContractFactory(\"MyNFTContract\")\n\n// Start deployment, returning a promise that resolves to a contract object\nconst myNFT = await PaymentSplitter.deploy()\nconsole.log(\"Contract deployed to address:\", myNFT.address)\n }\n\n main()\n.then(() => process.exit(0))\n.catch((error) => {\n    console.error(error)\n    process.exit(1)\n})\n```\n\n```text\nrequire(\"@nomiclabs/hardhat-waffle\");\nrequire(\"@nomiclabs/hardhat-etherscan\");\n```\n\n```text\nnpx hardhat verify \\\n--contract \"contracts/MyNFTContract.sol\" \\\n--network ropsten 0xE9abA803d6a801fce021d0074ae71256C9F24Da4\n```\n\n```text\nMyNFTContract\n```\n\n```text\nPaymentSplitter\n```\n\n```text\n--contract\n```\n\n```text\nawait run(\"verify:verify\", {\n      address: contractAddress,\n      constructorArguments: args,\n      contract: \"contracts/OurToken.sol:OurToken\"\n    }\n```\n\n========================================\n\nComments:\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:36.125Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":180,"estimatedTokens":1227}}143{"id":"stack-67493677","source":"stackoverflow","questionId":67493677,"title":"How to return \"Null\" or an \"Empty\" object in Solidity?","tags":["ethereum","solidity","smartcontracts"],"text":"Title: How to return \"Null\" or an \"Empty\" object in Solidity?\nTags: ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI am currently writing a **Smart Contract** in **Solidity**. The smart contract, amongst other information, stores an array of properties object at the general level. The property object Looks like this:\n\n```\nstruct PropertyObj {\n string id;\n uint weiPrice;\n address owner;\n}\n```\n\nNow there is a specific function that iterates over the array, finds the property and returns it (*code below*)\n\n```\nfunction getPropertyByid(string memory _propertyId)private view returns(PropertyObj memory){\n for(uint i = 0; iThe \"Problem\" is that, unlike other programming languages, Solidity does not allow to return null (*as far as I am concerned*).\n\nIn other words, if throughout the iteration we do not find the property, then what we shall return if we specified that we need to return ***PropertyObj memory*** in the function signature?\n\n========================================\n\nCode:\n```text\nstruct PropertyObj {\n    string id;\n    uint weiPrice;\n    address owner;\n}\n```\n\n```text\nfunction getPropertyByid(string memory _propertyId)private view returns(PropertyObj memory){\n    for(uint i = 0; i<PropertyArray.length; i++){\n        if (keccak256(bytes((PropertyArray[i].id))) == keccak256(bytes((_propertyId)))) {\n            return PropertyArray[i];\n        }\n        return null;\n    }\n}\n```\n\n```text\nfor(uint i = 0; i<PropertyArray.length; i++){\n    if (keccak256(bytes((PropertyArray[i].id))) == keccak256(bytes((_propertyId)))) {\n        return PropertyArray[i];\n    }\n}\n\nrevert('Not found');\n```\n\n```text\nfor(uint i = 0; i<PropertyArray.length; i++) {\n    // ...\n}\n\n// not found, return empty `PropertyObj`\nPropertyObj memory emptyPropertyObj;\nreturn emptyPropertyObj;\n```\n\n```text\nnull\n```\n\n========================================\n\nComments:\n- Yes, you were right about where I return the \"null\", thanks for pointing it out :). On the other hand, If I understand it correctly, there is no \"default\" way to return the \"null\", but in my case, I could declare an \"empty\" object and return that instead.","metadata":{"transformedAt":"2026-08-18T18:33:36.125Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":73,"estimatedTokens":535}}144{"id":"stack-70628980","source":"stackoverflow","questionId":70628980,"title":"TypeError: Cannot read properties of undefined (reading 'getContractFactory') when testing contract","tags":["javascript","solidity"],"text":"Title: TypeError: Cannot read properties of undefined (reading 'getContractFactory') when testing contract\nTags: javascript, solidity\nSource: Stack Overflow\n\nQuestion:\nFirst question so bare with me if it is not very clear, but I'll try my best.\n\nI am currently running through a youtube video to test my contract with hardhat, ethers, and waffle (https://www.youtube.com/watch?v=oTpmNEYV8iQ&list=PLw-9a9yL-pt3sEhicr6gmuOQdcmWXhCx4&index=6).\n\nHere is the contract:\n\n```\n// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\n\ncontract MyContract is ERC721 {\n\n constructor(string memory name, string memory symbol) \n ERC721(name, symbol) {\n\n }\n \n}\n```\n\nAnd here is test.js:\n\n```\nconst { expect } = require('chai');\n\ndescribe(\"MyContract\", function() {\n \n it(\"should return correct name\", async function() {\n const MyContract = hre.ethers.getContractFactory(\"MyContract\");\n const myContractDeployed = await MyContract.deploy(\"MyContractName\", \"MCN\");\n await myContractDeployed.deployed();\n \n expect(await myContractDeployed.name()).to.equal(\"MyContractName\");\n });\n});\n```\n\nwhen I run \"npx hardhat test\" in the terminal it returns:\n\n```\nMyContract\n 1) should return correct name\n\n 0 passing (7ms)\n 1 failing\n\n 1) MyContract\n should return correct name:\n TypeError: Cannot read properties of undefined (reading 'getContractFactory')\n at Context. (test\\test.js:7:35)\n at processImmediate (node:internal/timers:464:21)\n```\n\nMy code matches the one from the video, and I am having a tough time understanding why I am getting a TypeError here. Any guidance is much appreciated!\n\n**EDIT:**\n\nI somehow fixed it, I dont understand how exactly it fixed it but it did. Instead of just installing\n\n```\nnpm install @nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers ethers\n```\n\nI installed\n\n```\nnpm install --save-dev @nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers ethers\n```\n\nThen the terminal printed\n\n```\nnpm WARN idealTree Removing dependencies.@nomiclabs/hardhat-waffle in favor of devDependencies.@nomiclabs/hardhat-waffle\nnpm WARN idealTree Removing dependencies.ethereum-waffle in favor of devDependencies.ethereum-waffle\nnpm WARN idealTree Removing dependencies.@nomiclabs/hardhat-ethers in favor of devDependencies.@nomiclabs/hardhat-ethers\nnpm WARN idealTree Removing dependencies.ethers in favor of devDependencies.ethers\n```\n\nthen I removed the hre in front of ethers.getContractFactory(\"MyContract\") and it worked! If anyone would like to explain why this might have fixed it I'd be happy to read it, otherwise I am moving on.\n\n========================================\n\nTop Answer:\nSometimes it is because any of these dependencies below missing. Especially if you are using dotenv file and forgetting to import it. So, put these import statements on your hardhat.config or truffle.config file:\n\n```\nrequire(\"@nomicfoundation/hardhat-toolbox\");\nrequire(\"@nomiclabs/hardhat-ethers\");\nrequire(\"dotenv\").config();\n```\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\n\ncontract MyContract is ERC721 {\n\n  constructor(string memory name, string memory symbol) \n    ERC721(name, symbol) {\n\n    }\n  \n}\n```\n\n```text\nconst { expect } = require('chai');\n\ndescribe(\"MyContract\", function() {\n  \n  it(\"should return correct name\", async function() {\n    const MyContract = hre.ethers.getContractFactory(\"MyContract\");\n    const myContractDeployed = await MyContract.deploy(\"MyContractName\", \"MCN\");\n    await myContractDeployed.deployed();\n    \n    expect(await myContractDeployed.name()).to.equal(\"MyContractName\");\n  });\n});\n```\n\n```text\nMyContract\n    1) should return correct name\n\n\n  0 passing (7ms)\n  1 failing\n\n  1) MyContract\n       should return correct name:\n     TypeError: Cannot read properties of undefined (reading 'getContractFactory')\n      at Context.<anonymous> (test\\test.js:7:35)\n      at processImmediate (node:internal/timers:464:21)\n```\n\n```text\nnpm install @nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers ethers\n```\n\n```text\nnpm install --save-dev @nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers ethers\n```\n\n```text\nnpm WARN idealTree Removing dependencies.@nomiclabs/hardhat-waffle in favor of devDependencies.@nomiclabs/hardhat-waffle\nnpm WARN idealTree Removing dependencies.ethereum-waffle in favor of devDependencies.ethereum-waffle\nnpm WARN idealTree Removing dependencies.@nomiclabs/hardhat-ethers in favor of devDependencies.@nomiclabs/hardhat-ethers\nnpm WARN idealTree Removing dependencies.ethers in favor of devDependencies.ethers\n```\n\n```text\nrequire(\"@nomiclabs/hardhat-waffle\");\n```\n\n```text\nconst hre = require(\"hardhat\");\n```\n\n```text\nrequire(\"@nomicfoundation/hardhat-toolbox\");\nrequire(\"@nomiclabs/hardhat-ethers\");\nrequire(\"dotenv\").config();\n```\n\n```text\nexpect(await myContractDeployed.name()).to.be.equal(\"MyContractName\");\n```\n\n========================================\n\nComments:\n- The error means that hre.ethers is undefined and that’s why you can’t acces a property (because it has none). My guess is that something in your code has gone wrong prior to this function.\n- It seemed to just be a problem with how the packages were installed, thanks for the comment though!\n- please post your `hardhat.config.js` file\n- If that were missing, the the error would be about reading `ethers` and not `getContractFactory`.","metadata":{"transformedAt":"2026-08-18T18:33:36.126Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":189,"estimatedTokens":1384}}145{"id":"stack-68428769","source":"stackoverflow","questionId":68428769,"title":"Rinkeby Authenticated Faucet is not working?","tags":["ethereum","solidity","web3-java"],"text":"Title: Rinkeby Authenticated Faucet is not working?\nTags: ethereum, solidity, web3-java\nSource: Stack Overflow\n\nQuestion:\nI need test ethereum for my pet project.\n\nI go to https://faucet.rinkeby.io/ , put a link with my tweet with my Ethereum address in MetaMask, choose `3 Ethers / 8 hours`.https://i.sstatic.net/0l4F4.jpg\n\nThe request was accepted, but 17 hours past and I haven't my test ethers.\nhttps://i.sstatic.net/HJE82.jpg\nDid I something wrong or I must wait a little longer?\nAnd explanation me please, what exactly means 3 Ethers / 8 hours?\n\n========================================\n\nTop Answer:\nMany times I've received 0.1 testnet ETH from this faucet:\n\nRinkeby ETH\n\nThe above link will send you fairly quickly either Rinkeby ETH or Rinkeby Link or BOTH.\n\nAlso, here's an up to date list of ETH faucets:\ndoc.chain.link\n\n(look for Rinkeby)\n\n========================================\n\nCode:\n```text\n3 Ethers / 8 hours\n```\n\n========================================\n\nComments:\n- Came here to say that it's still not working. Not sure to whom we can raise this feedback.\n- Although this is a good question, my guess is it was closed because it doesn't belong in this forum. It belongs here: ethereum.stackexchange.com\n- this is not ETH, it is chainlink token\n- Nulik, the above link will send you fairly quickly either Rinkeby ETH or Rinkeby Link or BOTH.","metadata":{"transformedAt":"2026-08-18T18:33:36.126Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":42,"estimatedTokens":341}}146{"id":"stack-70364713","source":"stackoverflow","questionId":70364713,"title":"hardhat test: is not a function","tags":["blockchain","solidity","hardhat"],"text":"Title: hardhat test: is not a function\nTags: blockchain, solidity, hardhat\nSource: Stack Overflow\n\nQuestion:\ni'm testing my contracts on hardhat network with fork of BSC.\n\ni'm deploying my token contract that have mint function:\n\n```\n// @dev Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).\nfunction mint(address _to, uint256 _amount) public onlyOwner {\n _mint(_to, _amount);\n _moveDelegates(address(0), _delegates[_to], _amount);\n}\n```\n\nthen i'm deploying it on test using `> npx hardhat test`, it will run tests of this code:\n\n```\n...\nit(\"Should deploy\", async () => {\n token = await Token.deploy();\n await token.deployed();\n console.debug(`\\t\\t\\tToken Contract Address: ${cyan}`, token.address);\n const supply = await token.totalSupply()\n console.debug(`\\t\\t\\tToken totalSupply: ${yellow}`, supply);\n await token.mint(owner.address, web3.utils.toWei(\"1000\", 'ether'))\n console.debug(`\\t\\t\\tToken owner balance: ${cyan}`, token.balanceOf(owner.address));\n });\n ...\n```\n\ntest print the first 2 console debug **correctly**:\n\n```\nToken Contract Address: 0x5FbDB2315678afecb367f032d93F642f64180aa3\n Token totalSupply: 0\n```\n\nalso `token.totalSupply()` works, so the token is deployed correctly, but when it have to call `token.mint()` it give this error:\n\n```\nTypeError: token.mint is not a function\n at Context. (test/general.js:102:21)\n at runMicrotasks ()\n at processTicksAndRejections (internal/process/task_queues.js:95:5)\n```\n\ni tried to clean all the artifacts running `> npx hardhat clean` and delated all the cache, but i still have the error\n\n========================================\n\nTop Answer:\n**functionName is not a function** this error occurs if the function is not available in your smart contract. in your case the function name is not mint() it's _mint().\n\n========================================\n\nCode:\n```text\n// @dev Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).\nfunction mint(address _to, uint256 _amount) public onlyOwner {\n    _mint(_to, _amount);\n    _moveDelegates(address(0), _delegates[_to], _amount);\n}\n```\n\n```text\n...\nit(\"Should deploy\", async () => {\n        token = await Token.deploy();\n        await token.deployed();\n        console.debug(`\\t\\t\\tToken Contract Address: ${cyan}`, token.address);\n        const supply = await token.totalSupply()\n        console.debug(`\\t\\t\\tToken totalSupply: ${yellow}`, supply);\n        await token.mint(owner.address, web3.utils.toWei(\"1000\", 'ether'))\n        console.debug(`\\t\\t\\tToken owner balance: ${cyan}`, token.balanceOf(owner.address));\n });\n ...\n```\n\n```text\nToken Contract Address: 0x5FbDB2315678afecb367f032d93F642f64180aa3\n Token totalSupply: 0\n```\n\n```text\nTypeError: token.mint is not a function\n  at Context.<anonymous> (test/general.js:102:21)\n  at runMicrotasks (<anonymous>)\n  at processTicksAndRejections (internal/process/task_queues.js:95:5)\n```\n\n```text\n> npx hardhat test\n```\n\n```text\ntoken.totalSupply()\n```\n\n```text\ntoken.mint()\n```\n\n```text\n> npx hardhat clean\n```\n\n```text\ntoken[\"mint(address,uint256)\"](owner.address, web3.utils.toWei(\"1000\", 'ether'))\n```\n\n```text\nbeforeEach(async function () {\n    Token = await ethers.getContractFactory(\"Token\")\n    token = await token.deploy()\n  })\n```\n\n```text\nbeforeEach()\n```\n\n```text\nconst token = await ethers.getContractFactory(\"Token\")\n```\n\n```text\nbeforeEach()\n```\n\n```text\nit()\n```\n\n```text\nToken\n```\n\n```text\ntoken\n```\n\n```text\nlet\n```\n\n```text\nawait\n```\n\n========================================\n\nComments:\n- Is the `mint()` function part of the `contract Token` or of another contract (e.g. an imported library) in the set of your contracts?\n- @PetrHejda `mint()` is part of the `contract Token`, as you can see, inside `mint()` there is `_mint()` that is part of BEP20 imported contract, there isn't any other `mint()` function\n- as you can see in the question, in the contract i have the mint() function ( first code in the question)\n- This should be the accepted answer","metadata":{"transformedAt":"2026-08-18T18:33:36.126Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":159,"estimatedTokens":998}}147{"id":"stack-58044125","source":"stackoverflow","questionId":58044125,"title":"Web3 signature verification is failing - ethers.js","tags":["javascript","solidity","web3js","ethers.js"],"text":"Title: Web3 signature verification is failing - ethers.js\nTags: javascript, solidity, web3js, ethers.js\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a signed message off-chain using ethers.js and verify that message on-chain using `ecrecover`. I'm signing the correct message from my metamask wallet, and passing the r, s, and v from that signature into ecrecover, but not getting a match to my metamask wallet.\n\nMy solidity code should work for prefixed or non-prefixed signatures.\n\nHere's the contract I'm using to verify signatures:\n\n```\npragma solidity ^0.5.0;\ncontract SignatureVerifier {\n /// @dev Signature verifier\n function isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) {\n return _isSigned(_address, messageHash, v, r, s) || _isSignedPrefixed(_address, messageHash, v, r, s);\n }\n\n /// @dev Checks unprefixed signatures.\n function _isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s)\n internal pure returns (bool)\n {\n return ecrecover(messageHash, v, r, s) == _address;\n }\n\n /// @dev Checks prefixed signatures.\n function _isSignedPrefixed(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s)\n internal pure returns (bool)\n {\n bytes memory prefix = \"\\x19Ethereum Signed Message:\\n32\";\n return _isSigned(_address, keccak256(abi.encodePacked(prefix, messageHash)), v, r, s);\n }\n}\n```\n\nFrom ethers, here's (a simplified version of) the code I'm using to generate the signature, which I use as parameters for the `_isSigned` function call.\n\n```\nlet provider = new ethers.providers.Web3Provider(window.ethereum)\nlet signer = provider.getSigner()\nlet dataHash = '0x952d17582514a6a434234b10b8e6b681b6006c8ed225d479fa3db70828b9cd60'\nlet signature = await signer.signMessage(dataHash)\nlet sigBreakdown = ethers.utils.splitSignature(signature)\nconsole.log(sigBreakdown)\n```\n\nthis prompts me for a signature in matamask where I sign the correct dataHash. It then logs an r, s, and v value.\n\nIn remix, I call `isSigned`, passing my metamask address, the dataHash (0x952...d60), and the r, s, and v values, expecting a result of `true` but it's returning `false`. I'm fairly confident in the solidity code and the javascript code here, but clearly I'm missing something. Help is greatly appreciated!\n\n========================================\n\nCode:\n```js\npragma solidity ^0.5.0;\ncontract SignatureVerifier {\n    /// @dev Signature verifier\n    function isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) {\n        return _isSigned(_address, messageHash, v, r, s) || _isSignedPrefixed(_address, messageHash, v, r, s);\n    }\n\n    /// @dev Checks unprefixed signatures.\n    function _isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s)\n        internal pure returns (bool)\n    {\n        return ecrecover(messageHash, v, r, s) == _address;\n    }\n\n    /// @dev Checks prefixed signatures.\n    function _isSignedPrefixed(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s)\n        internal pure returns (bool)\n    {\n        bytes memory prefix = \"\\x19Ethereum Signed Message:\\n32\";\n        return _isSigned(_address, keccak256(abi.encodePacked(prefix, messageHash)), v, r, s);\n    }\n}\n```\n\n```js\nlet provider = new ethers.providers.Web3Provider(window.ethereum)\nlet signer = provider.getSigner()\nlet dataHash = '0x952d17582514a6a434234b10b8e6b681b6006c8ed225d479fa3db70828b9cd60'\nlet signature = await signer.signMessage(dataHash)\nlet sigBreakdown = ethers.utils.splitSignature(signature)\nconsole.log(sigBreakdown)\n```\n\n```text\necrecover\n```\n\n```text\n_isSigned\n```\n\n```text\nisSigned\n```\n\n```text\ntrue\n```\n\n```text\nfalse\n```\n\n```text\nlet bytesDataHash = ethers.utils.arrayify(dataHash)\n```\n\n```text\nstring\n```\n\n```text\nbytes\n```\n\n```text\nbytesDataHash\n```\n\n```text\ndataHash\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.126Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":127,"estimatedTokens":970}}148{"id":"stack-52000464","source":"stackoverflow","questionId":52000464,"title":"How to modelize smart contracts in UML?","tags":["uml","solidity","smartcontracts"],"text":"Title: How to modelize smart contracts in UML?\nTags: uml, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI am looking for a way to modelize ethereum smart contracts interaction using a modeling language like UML.\n\nI have the following serivce Contract:\n\n```\ncontract ServiceContract {\n\n constructor (address _storeC, address _quizC, address _signC) {\n\n StorageContract storeC = StoreContract(_storeC);\n QuizContract quizC = QuizContract(_quizC);\n SignatureContract signC = SignatureContract(_signC);\n }\n\n function storeData (bytes32 data) public {\n storeC.save(data);\n }\n\n function getAnswer( bytes32 question) public constant returns (bytes32) {\n return quizC.get(question);\n }\n\n function sign (bytes32 data) public returns (bytes32) {\n return signC.sign(data);\n }\n\n}\n```\n\nI modelized it with this class diagram, is it correct? \n\nhttps://i.sstatic.net/VRPif.png\n\n========================================\n\nTop Answer:\nYou simply have associations to these three classes:\n\nhttps://i.sstatic.net/feU5n.png\n\n(I just drew a single relation)\n\nThe role name to the right tells in conjunction with the dot that it's a owned property of the class to the left. Not sure about the visibility (if that's private per default replace the `+` with a `-`).\n\n========================================\n\nCode:\n```text\ncontract ServiceContract {\n\n\n    constructor (address _storeC, address _quizC, address _signC) {\n\n        StorageContract storeC = StoreContract(_storeC);\n        QuizContract quizC = QuizContract(_quizC);\n        SignatureContract signC = SignatureContract(_signC);\n    }\n\n\n    function storeData (bytes32 data) public {\n        storeC.save(data);\n    }\n\n    function getAnswer( bytes32 question) public constant returns (bytes32) {\n       return quizC.get(question);\n    }\n\n    function sign (bytes32 data) public returns (bytes32) {\n        return signC.sign(data);\n    }\n\n}\n```\n\n```text\ncontract ServiceContract {\n    constructor (address _storeC, address _quizC, address _signC) {\n        StorageContract storeC = StoreContract(_storeC);\n        QuizContract quizC = QuizContract(_quizC);\n        SignatureContract signC = SignatureContract(_signC);\n    }\n}\n```\n\n```text\nServiceContract\n```\n\n```text\nStorageContract\n```\n\n```text\nQuizContract\n```\n\n```text\nSignatureContract\n```\n\n```text\nServiceContract\n```\n\n```text\nStorageContract\n```\n\n```text\nServiceContract\n```\n\n```text\nStorageContract\n```\n\n```text\nServiceContract\n```\n\n```text\nStorageContract\n```\n\n```text\nStorageContract\n```\n\n```text\nServiceContract\n```\n\n```text\nstoreC\n```\n\n```text\nStoreContract\n```\n\n```text\n+\n```\n\n```text\n-\n```\n\n```text\n#\n```\n\n```text\n~\n```\n\n```text\nServiceContract\n```\n\n```text\nServiceContract\n```\n\n```text\nstoreC\n```\n\n```text\nStorageContract\n```\n\n```text\nquizC\n```\n\n```text\nQuizContract\n```\n\n```text\nsignC\n```\n\n```text\nSignatureContract\n```\n\n```text\nServiceContract\n```\n\n```text\n+\n```\n\n```text\nServiceContract\n```\n\n```text\nStorageContract\n```\n\n```text\nQuizContract\n```\n\n```text\nSignatureContract\n```\n\n```text\nStorageContract\n```\n\n```text\nQuizContract\n```\n\n```text\nSignatureContract\n```\n\n```text\nServiceContract\n```\n\n```text\nServiceContract\n```\n\n```text\nStorageContract\n```\n\n```text\nstoreC\n```\n\n```text\nServiceContract\n```\n\n```text\nServiceContract\n```\n\n```text\nStorageContract\n```\n\n```text\nQuizContract\n```\n\n```text\nSignatureContract\n```\n\n```text\nStorageContract\n```\n\n```text\nQuizContract\n```\n\n```text\nSignatureContract\n```\n\n```text\nServiceContract\n```\n\n```text\nServiceContract\n```\n\n```text\nServiceContract\n```\n\n```text\nStorageContract\n```\n\n```text\nQuizContract\n```\n\n```text\nSignatureContract\n```\n\n```text\nServiceContract\n```\n\n```text\nstoreC\n```\n\n```text\nStorageContract\n```\n\n```text\nquizC\n```\n\n```text\nQuizContract\n```\n\n```text\nsignC\n```\n\n```text\nSignatureContract\n```\n\n```text\nServiceContract\n```\n\n```text\n_storeC\n```\n\n```text\naddress\n```\n\n```text\n_quizC\n```\n\n```text\naddress\n```\n\n```text\n_signC\n```\n\n```text\naddress\n```\n\n```text\nServiceContract\n```\n\n```text\nstoreData\n```\n\n```text\nbytes32\n```\n\n```text\ndata\n```\n\n```text\ngetAnswer\n```\n\n```text\nbytes32\n```\n\n```text\nquestion\n```\n\n```text\nbytes32\n```\n\n```text\nsign\n```\n\n```text\nbytes32\n```\n\n```text\nbytes32\n```\n\n```text\n+\n```\n\n```text\n-\n```\n\n========================================\n\nComments:\n- thank you Mr for your clear answer, I really apreciate it. can u just give an example when we have to use > instead of aggregation ?\n- Sure @maroodb. According to the specification \"A Usage is a Dependency in which one NamedElement requires another NamedElement (or set of NamedElements) for its full implementation or operation. The Usage does not specify how the client uses the supplier other than the fact that the supplier is used by the definition or implementation of the client\". This means that your proposal is also correct, but as I stated before, it is inaccurate, because your code makes it clear that the relation between the classes, in your implementation, is an aggregation composition.\n- Maybe an example of an usage that is not an aggregation (nor a composition) can be useful for understanding the concept. Let's say that instead of passing the references of the `StorageContract` to the `ServiceContract` constructor, you decide to pass it to the `storeData` function. In this example you will not have an object of the type `StorageContract` defined inside the `ServiceContract`, and therefore it will not be neither an aggregation, nor a composition. But it is, for sure, an usage, thus you could use the &#171;use&#187; dependency in the diagram.\n- The use of shared aggregation is bad (in almost all contexts). UML 2.5 explicitly states that it has no commonly defined semantics. So it does not add any value. For that reason I down vote your answer. Also I disregard local properties notation compared to owned properties denoted in role names. See also bellekens.com/2010/12/20/&hellip;\n- @ThomasKilian I understand your point, but the UML specification just states that it does not define a *precise semantics* of shared aggregation (**Section 9.5.3, page 113**). Regarding the properties notation, the UML specification explicitly does not enforce a modeling convention on when a property is of the AssociationEnd type, even though it recognizes a *useful* one like the one you use (**Section 9.5.3, page 112**).\n- Yes. My down vote is only related to the shared aggregation. Usage of roles is a recommendation (I Geert's referenced opinion from a long time experience).\n- Regarding the shared aggregation, all that matters is if you consider that this association has one end with aggregation or not. If it has aggregation, it has to be either *shared* or *composite* (**Section 9.9.1**). As the objects being part of the whole exist beyond the scope of the whole, it cannot be a *composite*, and therefore it must be *shared*, even though a *shared* aggregation has not *precise semantics*. This is what Geert discusses in the post you have linked, and even provides examples (see the Linkedin example in the link). BTW, I don't mind the downvote.\n- Pls. read the specs carefully on p. 110: *Indicates that the Property has shared aggregation semantics. Precise semantics of shared aggregation varies by application area and modeler.* So the general use is disregarded unless you have good and documented reason for its use.\n- Where does the UML Specification state that it *disregards* the use of a shared aggregation? Indeed, it defines **explicitly** that an aggregation only can be of three types: *none* (that means no aggregation), *shared* (with no precise semantics, left to the application area and the modeler), and *composite*. Therefore, if an association has one end with aggregation, it must be either *shared* or *composite* (it cannot be *none*). If the aggregation does not match the semantics in the specification for a *composite* type, then it **must** be *shared* (there is no other possible type).\n- That's why I said before that what matters in this discussion is if this association has one end with aggregation or not. Because if it has one end with aggregation, then, as explained before, it must be *shared* (as it cannot be *none*, nor *composite*). How does the UML Specification define *aggregation*: when \"one instance is used to group together a set of instances\" (**Section 9.5.3, p. 112**). In this case, to my understanding, the `ServiceContract` object groups together a set of instances of one `StorageContract`, one `QuizContract` and one `SignaturaContract`. And this is aggregation.\n- Happy to see you reduced the number of shared aggregation uses. However, aggregation is about lifetime of objects. In almost all cases this notation is just superfluous. It (the composite) has e meaning when you emphasize the lifetime. This can be done for security or memory management purpose. For standard associations its just ballast since the memory management of the target languge will handle it anyway.\n- Please, see how aggregation is defined in the UML Specification: \"*Sometimes a Property is used to model circumstances in which one instance is used to group together a set of instances; **this is called aggregation***\" (p. 113). You have a good example of a shared aggregation in bellekens.com/2010/12/20/&hellip; (you already cited this link). In the LinkedIn example included there you have the class *Group* that aggregates *User* classes as *groupMember*. And has nothing to do with lifetimes.","metadata":{"transformedAt":"2026-08-18T18:33:36.126Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":82,"totalLines":424,"estimatedTokens":2352}}149{"id":"stack-71775742","source":"stackoverflow","questionId":71775742,"title":"Call solidity function dynamically, based on its bytes4 function selector","tags":["blockchain","ethereum","solidity","smartcontracts","rsk"],"text":"Title: Call solidity function dynamically, based on its bytes4 function selector\nTags: blockchain, ethereum, solidity, smartcontracts, rsk\nSource: Stack Overflow\n\nQuestion:\nIn a smart contract, let's say I have a function which wants to invoke\nanother function dynamically, based on some internal logic.\nHere it obtains the function selector as a `bytes4` variable.\n\nAfter which it is possible to use branching logic to invoke\none of the target functions.\nSee: **(A)**\n\nHowever, is it possible to avoid that and invoke the function selector directly?\nSee: **(B)**\n\n```\nfunction myDynamicFunc(uint256 someParam) public {\n bytes4 selector = /* ... some internal logic ... */\n\n if (selector == this.myFuncA.selector) {\n myFuncA(someParam);\n } else if (selector == this.myFuncB.selector) {\n myFuncB(someParam);\n }\n // (A) instead of something like this ^ branching logic (which works)\n\n selector.invoke(someParam);\n // (B) can something like this ^ instead by calling the selector directly instead (does not work)\n}\n```\n\n**Details**\n\n- `myDynamicFunc` is `public` and `myFuncA`+`myFuncB` are also `public`.\n\n- All 3 functions are implemented in the same smart contract.\n\n**Notes**\n\nI have written up an answer expanding on `@kj-crypto`'s suggestion in the comments.\nIf there is *another way* to accomplish the above *without* using `address(this).call(...)`, I'm all ears!\n\n========================================\n\nTop Answer:\nExpanding on\n`@kj-crypto`'s comment\nabove:\n\nDo you mean sth like `address(this).call(abi.encodePacked(selector, ))`?\n\n... and created this implementation:\n\n```\nfunction myDynamicFunc(uint256 someParam)\n public\n // pure // --> (1)\n returns (bytes memory result) // --> (2)\n {\n bytes4 selector =\n /* ... some internal logic ... */\n this.myFuncA.selector;\n\n (bool success, bytes memory resultBytes) =\n address(this).call(abi.encodePacked(selector, someParam));\n\n require(success, \"failed to call selector\"); // --> 3\n result = resultBytes;\n }\n```\n\nTo summarise, the answer is: \"Yes it is possible, but no it isn't that great an idea.\"\n\nReasons:\n\n(1) - If you need the function to be `pure`, it cannot be, unfortunately, because `address(this).call(...)` potentially modifies state.\n\n(2) - The return type will default to `bytes memory`, as this is the return type of `address(this).call(...)`. You can cast it, but this adds additional complexity to the code, which is against the grain of the original motivation.\n\n(3) - To *properly* handle `address(this).call(...)`, need to do something with the `bool` returned in the tuple. For example using `require()`. This also against the grain of the original motivation, as it simply shifts the branching logic from one form to another (`if ... else` to `require()`), and a more expensive one at that.\n\n(4) - Overall, the gas costs of the original function appear to be less than, and thus advantageous, over this suggested form. Note that this has not been verified with experimentation, and if anyone would like to give it a go, here's the (full solidity file).\n\n========================================\n\nCode:\n```text\nfunction myDynamicFunc(uint256 someParam) public {\n    bytes4 selector = /* ... some internal logic ... */\n\n    if (selector == this.myFuncA.selector) {\n      myFuncA(someParam);\n    } else if (selector == this.myFuncB.selector) {\n      myFuncB(someParam);\n    }\n    // (A) instead of something like this ^ branching logic (which works)\n\n    selector.invoke(someParam);\n    // (B) can something like this ^ instead by calling the selector directly instead (does not work)\n}\n```\n\n```text\nbytes4\n```\n\n```text\nmyDynamicFunc\n```\n\n```text\npublic\n```\n\n```text\nmyFuncA\n```\n\n```text\nmyFuncB\n```\n\n```text\npublic\n```\n\n```text\n@kj-crypto\n```\n\n```text\naddress(this).call(...)\n```\n\n```text\ncall\n```\n\n```text\ncall\n```\n\n```text\nfunction myDynamicFunc(uint256 someParam)\n    public\n    // pure // --> (1)\n    returns (bytes memory result) // --> (2)\n  {\n    bytes4 selector =\n      /* ... some internal logic ... */\n      this.myFuncA.selector;\n\n    (bool success, bytes memory resultBytes) =\n      address(this).call(abi.encodePacked(selector, someParam));\n\n    require(success, \"failed to call selector\"); // --> 3\n    result = resultBytes;\n  }\n```\n\n```text\n@kj-crypto\n```\n\n```text\naddress(this).call(abi.encodePacked(selector, <func-args>))\n```\n\n```text\npure\n```\n\n```text\naddress(this).call(...)\n```\n\n```text\nbytes memory\n```\n\n```text\naddress(this).call(...)\n```\n\n```text\naddress(this).call(...)\n```\n\n```text\nbool\n```\n\n```text\nrequire()\n```\n\n```text\nif ... else\n```\n\n```text\nrequire()\n```\n\n```text\nbytes4 private constant SELECTOR = bytes4(keccak256(bytes(\"transfer(address,uint256)\")));\n```\n\n```text\nnonPayableAddress.call(abi.encodeWithSignature(\"transfer(address,uint256)\", 0xaddress, amount))\n```\n\n```text\n(bool success, bytes memory data) = contractAddress.call(\n        abi.encodeWithSelector(SELECTOR, to, value)\n    );\n```\n\n```text\nselector\n```\n\n```text\nselector\n```\n\n```text\ncall, delegateCall, callcode\n```\n\n```text\ntransfer\n```\n\n```text\nsend\n```\n\n========================================\n\nComments:\n- i don't think i understood it. can you maybe give a more concrete example?\n- Do you mean sth like `address(this).call(abi.encodePacked(selector, ))`?\n- @keser yeah, created a concise example here: github.com/rsksmart/demo-code-snippets/blob/c11e373/&hellip;\n- @kj-crypto just tried to use your suggestion (see `myDynamicFunc2`, in same link above), and looks like: (1) the return value is `bytes memory`, which can't be easily typecast to intended type, and (2) requires an additional `require()` ... which is less than ideal from a gas point of view (should experiment to verify, but that's another question).\n- @kj-crypto although I suppose it is indeed a valid answer to my question. If you wanna post it as an answer, I'll ✔-mark it\n- @bguiz When you use `pure` or `view` function then, they can be called off-chain via `eth_call` so in this case there is no need for gas optimization. However, I assume that here is no such case. Am I right?\n- @kj-crypto Yeah, it's looking more an more like: \"Yes it is possible, but no it isn't that great an idea.\"\n- @kj-crypto I have written up an answer expanding on your original suggestion below.","metadata":{"transformedAt":"2026-08-18T18:33:36.126Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":250,"estimatedTokens":1557}}150{"id":"stack-67317392","source":"stackoverflow","questionId":67317392,"title":"How to transfer a NFT from one account to another using ERC721?","tags":["ethereum","blockchain","solidity","smartcontracts","nft"],"text":"Title: How to transfer a NFT from one account to another using ERC721?\nTags: ethereum, blockchain, solidity, smartcontracts, nft\nSource: Stack Overflow\n\nQuestion:\nI'm writing an NFT smart contract using the OpenZeppelin ERC721Full contract. I'm able to mint NFTs, but I want to have a button that enables them to be bought. I'm trying writing this function:\n\n```\nfunction buyNFT(uint _id) public payable{\n //Get NFT owner address\n address payable _seller = ownerOf(_id);\n\n // aprove nft sell\n approve(_seller, _id);\n setApprovalForAll(msg.sender, true);\n\n //transfer NFT\n transferFrom(_seller, msg.sender, _id);\n\n // transfer price in ETH\n address(_seller).transfer(msg.value);\n\n emit NftBought(_seller, msg.sender, msg.value);\n\n }\n```\n\nThis does not work because function approve must be called by the owner or an already approved address. I have no clue on how a buy function should be built. I know that I must use some requirements but first I want the function to work on tests and then I'll write the requirements.\n\n**How should a buy function be coded?** Because the only solution I have found is to overwrite the approve function and omit the require of who can call this function. But it looks like it isn't the way it should be done.\n\nThank you!\n\n========================================\n\nTop Answer:\nIf you let anyone call the `approve` function, it would allow anyone to approve themselves to take NFTs! The purpose of `approve` is to give the owner of an asset the ability to give someone else permission to transfer that asset as if it was theirs.\n\nThe basic premise of any sale is that you want to make sure that you get paid, and that the buyer receives the goods in return for the sale. Petr Hedja's solution takes care of this by having the `buy` function not only transfer the NFT, but also include the logic for sending the price of the token. I'd like to recommend a similar structure with a few changes. One is so that the function will also work with ERC20 tokens, the other is to prevent an edge case where if gas runs out during execution, the buyer could end up with their NFT for free. This is building on his answer, though, and freely uses some of the code in that answer for architecture.\n\nEther can still be set as the accepted currency by inputting the zero address (`address(0)`) as the contract address of the token.\n\nIf the sale is in an ERC20 token, the buyer will need to approve the NFT contract to spend the amount of the sale since the contract will be pulling the funds from the buyer's account directly.\n\n```\npragma solidity ^0.8.4;\n\nimport 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol';\nimport 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol';\n\ncontract MyToken is ERC721 {\n event NftBought(address _seller, address _buyer, uint256 _price);\n\n mapping (uint256 => uint256) public tokenIdToPrice;\n mapping (uint256 => address) public tokenIdToTokenAddress;\n\n constructor() ERC721('MyToken', 'MyT') {\n _mint(msg.sender, 1);\n }\n\n function setPrice(uint256 _tokenId, uint256 _price, address _tokenAddress) external {\n require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');\n tokenIdToPrice[_tokenId] = _price;\n tokenIdToTokenAddress[_tokenId] = _tokenAddress;\n }\n\n function allowBuy(uint256 _tokenId, uint256 _price) external {\n require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');\n require(_price > 0, 'Price zero');\n tokenIdToPrice[_tokenId] = _price;\n }\n\n function disallowBuy(uint256 _tokenId) external {\n require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');\n tokenIdToPrice[_tokenId] = 0;\n }\n \n function buy(uint256 _tokenId) external payable {\n uint256 price = tokenIdToPrice[_tokenId];\n require(price > 0, 'This token is not for sale');\n require(msg.value == price, 'Incorrect value');\n address seller = ownerOf(_tokenId);\n address tokenAddress = tokenIdToTokenAddress[_tokenId];\n if(address != address(0){\n IERC20 tokenContract = IERC20(tokenAddress);\n require(tokenContract.transferFrom(msg.sender, address(this), price),\n \"buy: payment failed\");\n } else {\n payable(seller).transfer(msg.value);\n }\n _transfer(seller, msg.sender, _tokenId);\n tokenIdToPrice[_tokenId] = 0;\n \n\n emit NftBought(seller, msg.sender, msg.value);\n }\n}\n```\n\n========================================\n\nCode:\n```text\nfunction buyNFT(uint _id) public payable{\n    //Get NFT owner address\n    address payable _seller = ownerOf(_id);\n\n    // aprove nft sell\n    approve(_seller, _id);\n    setApprovalForAll(msg.sender, true);\n\n    //transfer NFT\n    transferFrom(_seller, msg.sender, _id);\n\n    // transfer price in ETH\n    address(_seller).transfer(msg.value);\n\n    emit NftBought(_seller, msg.sender, msg.value);\n\n  }\n```\n\n```text\npragma solidity ^0.8.4;\n\nimport 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol';\n\ncontract MyToken is ERC721 {\n    event NftBought(address _seller, address _buyer, uint256 _price);\n\n    mapping (uint256 => uint256) public tokenIdToPrice;\n\n    constructor() ERC721('MyToken', 'MyT') {\n        _mint(msg.sender, 1);\n    }\n\n    function allowBuy(uint256 _tokenId, uint256 _price) external {\n        require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');\n        require(_price > 0, 'Price zero');\n        tokenIdToPrice[_tokenId] = _price;\n    }\n\n    function disallowBuy(uint256 _tokenId) external {\n        require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');\n        tokenIdToPrice[_tokenId] = 0;\n    }\n    \n    function buy(uint256 _tokenId) external payable {\n        uint256 price = tokenIdToPrice[_tokenId];\n        require(price > 0, 'This token is not for sale');\n        require(msg.value == price, 'Incorrect value');\n        \n        address seller = ownerOf(_tokenId);\n        _transfer(seller, msg.sender, _tokenId);\n        tokenIdToPrice[_tokenId] = 0; // not for sale anymore\n        payable(seller).transfer(msg.value); // send the ETH to the seller\n\n        emit NftBought(seller, msg.sender, msg.value);\n    }\n}\n```\n\n```text\nbuy()\n```\n\n```text\ntokenIdToPrice\n```\n\n```text\nmsg.sender\n```\n\n```text\nallowBuy(1, 2)\n```\n\n```text\nbuy(1)\n```\n\n```text\nownerOf(1)\n```\n\n```text\npragma solidity ^0.8.4;\n\nimport 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol';\nimport 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol';\n\ncontract MyToken is ERC721 {\n    event NftBought(address _seller, address _buyer, uint256 _price);\n\n    mapping (uint256 => uint256) public tokenIdToPrice;\n    mapping (uint256 => address) public tokenIdToTokenAddress;\n\n    constructor() ERC721('MyToken', 'MyT') {\n        _mint(msg.sender, 1);\n    }\n\n    function setPrice(uint256 _tokenId, uint256 _price, address _tokenAddress) external {\n        require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');\n        tokenIdToPrice[_tokenId] = _price;\n        tokenIdToTokenAddress[_tokenId] = _tokenAddress;\n    }\n\n    function allowBuy(uint256 _tokenId, uint256 _price) external {\n        require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');\n        require(_price > 0, 'Price zero');\n        tokenIdToPrice[_tokenId] = _price;\n    }\n\n    function disallowBuy(uint256 _tokenId) external {\n        require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');\n        tokenIdToPrice[_tokenId] = 0;\n    }\n    \n    function buy(uint256 _tokenId) external payable {\n        uint256 price = tokenIdToPrice[_tokenId];\n        require(price > 0, 'This token is not for sale');\n        require(msg.value == price, 'Incorrect value');\n        address seller = ownerOf(_tokenId);\n        address tokenAddress = tokenIdToTokenAddress[_tokenId];\n        if(address != address(0){\n            IERC20 tokenContract = IERC20(tokenAddress);\n            require(tokenContract.transferFrom(msg.sender, address(this), price),\n                \"buy: payment failed\");\n        } else {\n            payable(seller).transfer(msg.value);\n        }\n        _transfer(seller, msg.sender, _tokenId);\n        tokenIdToPrice[_tokenId] = 0;\n        \n\n        emit NftBought(seller, msg.sender, msg.value);\n    }\n}\n```\n\n```text\napprove\n```\n\n```text\napprove\n```\n\n```text\nbuy\n```\n\n```text\naddress(0)\n```\n\n```text\n// mapping is for fast lookup. the longer operation, the more gas\nmapping(uint => NftItem) private _idToNftItem;\n\nfunction buyNft(uint tokenId) public payable{\n    uint price=_idToNftItem[tokenId].price;\n    // this is set in erc721 contract\n    // Since contracts are inheriting, I want to make sure I use this method in ERC721\n    address owner=ERC721.ownerOf(tokenId);\n    require(msg.sender!=owner,\"You already own this nft\");\n    require(msg.value==price,\"Please submit the asking price\");\n    // since this is purchased, it is not for sale anymore \n    _idToNftItem[tokenId].isListed=false;\n    _listedItems.decrement();\n    // this is defined in ERC721\n    // this already sets owner _owners[tokenId] = msg.sender;\n    _transfer(owner,msg.sender,tokenId);\n    payable(owner).transfer(msg.value);\n  }\n```\n\n```text\nstruct NftItem{\n    uint tokenId;\n    uint price;\n    // creator and owner are not same. creator someone who minted. creator does not change\n    address creator;\n    bool isListed;\n  }\n```\n\n========================================\n\nComments:\n- I've used `_transferFrom(seller, msg.sender, _tokenId);` insted of `_transfer(seller, msg.sender, _tokenId);` because I'm using ERC721Full but it worked nicely. Thank you!\n- What is the line that starts with \"mapping\" doing?\n- @ianwt A `mapping` is a dictionary-like datatype. You can easily retrieve a value by its key, but you cannot retrieve a key by a value. Note that the keys have to be unique, the values don't... In the example above, the key is the token ID, and the value is the token price. So in this case its easy to query a token price by its ID.\n- Got it, thank you! what is the value of this mapping when the contract is initially used to mint an NFT? Is it 0? That is, does `allowBuy` have to be explicitly called with a positive value before the NFT is purchasable? Thanks again\n- @ianwt Exactly. Default value for each key is 0. And because the `buy()` function requires `price > 0` (i.e. non-default value), you effectively need to invoke `allowBuy()` before the NFT is purchasable.\n- In order to call `buy` and purchase an NFT, is it necessary that the person who sends the buy transaction has to sign the transaction with their private key? I tried calling the buy function using a web3 transaction, and I set the `from` field to be my friend's public key, but I signed the transaction with my own private key. The token was transferred to myself and not to my friend, as I intended. Thanks for your help!\n- @ianwt This snippet allows buying only for yourself, but by expanding the code, you could make a functionality that allows buying for another address... During the process of signing the transaction with your own private key, you most likely rewrote the `from` field to your address through some `web3js` internal code... On the raw transaction level, it's technically possible to sign a transaction with a different key that doesn't match the `from` field (which was probably your intention), but that would be rejected by the network as invalid transaction.\n- There's something wrong with `if(address != address(0){`, it's missing parenthesis and the comparison doesn't seem right.\n- The Renaissance, can you explain to me the `tokenIdToTokenAddress` and `_tokenAddress` and why you created the setPrice function? I suppose it's to keep track of what ERC20 currency the NFT is for sale.\n- Hey I have made a question elaborating on your answer here, I wondered if @The Renaissance might be able to have a look and answer it? Thanks stackoverflow.com/questions/69193720/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:36.126Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":301,"estimatedTokens":2989}}151{"id":"stack-70672642","source":"stackoverflow","questionId":70672642,"title":"what's the purpose of the approve function in erc 20","tags":["solidity","erc20"],"text":"Title: what's the purpose of the approve function in erc 20\nTags: solidity, erc20\nSource: Stack Overflow\n\nQuestion:\nI'm new in solidity and erc20, so I read ERC20 description on the openzeppelin and find this function which isn't clear for me.\n\n```\napprove(spender, amount)\n```\n\nWhat's the purpose of allowing to the *spender* spend my token, instead of send my tokens to the *spender* directly?\n\n========================================\n\nTop Answer:\n`Approve` is a function used to give permission the `spender` can be anyone an exchange or EOA to withdraw as many times from your token contract up to the `_value`.\nYou can check this reference here\n\n========================================\n\nCode:\n```text\napprove(spender, amount)\n```\n\n```text\napprove()\n```\n\n```text\nApprove\n```\n\n```text\nspender\n```\n\n```text\n_value\n```\n\n```text\nApprove\n```\n\n```text\nspender\n```\n\n```text\namount\n```\n\n```text\nDEX\n```\n\n```text\nCustody services\n```\n\n```text\napprove\n```\n\n```text\ninternal wallets\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.126Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":69,"estimatedTokens":246}}152{"id":"stack-48861734","source":"stackoverflow","questionId":48861734,"title":"How to detect a transaction that will fail in web3js","tags":["ethereum","solidity","web3js"],"text":"Title: How to detect a transaction that will fail in web3js\nTags: ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI've just recently finished working on a rather complex contract with the Remix IDE. I'm now attaching web3 to the frontend but when I call functions that should fail, they still go through on Metamask.\n\nWhen testing my contract in Remix, I would often click on and call certain functions that had require statements that I knew would fail just to confirm that the contract state was recorded correctly. Remix didn't send the transaction to metamask and instead output an error message and I would like to handle the transaction error on my own as well.\n\nHow can I check my contract call to see whether it will fail. Must I use the method that predicts gas and detect it that way and if so how? My current code is below:\n\n```\ncontract.callFunction(function(error, result) {\n if (!error) alert(result);\n else alert(error);\n}\n```\n\nThe above code catches rejecting the metamask confirmation as an error but transactions that should fail go through to metamask with an insanely high gas limit set. The function callFunction is in the contract and takes no parameters but does have an effect on the blockchain so it requires the transaction. The first line of the function is \"require(state == 1);\" and I have the contract set to state 2 currently so I'm expecting the transaction to fail, I just want to detect it failing.\n\n========================================\n\nCode:\n```text\ncontract.callFunction(function(error, result) {\n    if (!error) alert(result);\n    else alert(error);\n}\n```\n\n```text\ncontract.nextState.estimateGas(function(error, result) {\n        if (!error) {\n            contract.nextState(function(error, result) {\n                if (!error) {\n                    alert(\"This is my value: \" + result);\n                } else {\n                    if (error.message.indexOf(\"User denied\") != -1) {\n                        alert(\"You rejected the transaction on Metamask!\");\n                    } else {\n                        alert(error);\n                    }\n                }\n            });\n        } else {\n            alert(\"This function cannot be run at this time.\");\n        }\n    });\n```\n\n```text\ncontract.foobar == contract[\"foobar\"]\n```\n\n========================================\n\nComments:\n- It would be nice if you described a bit more what does the code do. Does `error !== undefined` mean that there would be an error in the transaction?\n- @NicSzer I hope you figured out the solution to your issue, and if you didn't hopefully my edit to the answer helps. I love that (most likely) google led you to my question, and I personally hate finding a question on google that doesn't answer my question thoroughly so I apologize for the lack of information. You are correct in that error being undefined means there was not an error. If error is not undefined then it is the object containing the error information.\n- I am using web3 2.x (because Metamask injects this by default). It doesnt seem to have the .methods . Any idea how do I predict whether a call would fail?\n- Hey @Amarsh , afaik the changes to Metamask haven't changed what is being injected (just that it's now not automatically injected) and I can't find any documentation that says web3 is on 2.x. Also, I didn't use \".methods\" at all in my answer, this was deprecated long ago afaik and you instead access the function directly from the contract object. Lmk if I can help further.\n- Hi, this solution works if you use MetaMask or Ethereum node, but it will not work with Infura service. Just FYI.\n- @VanjaDev Metamask uses Infura for it's node, so I imagine you're just trying to use the Infura service too directly.","metadata":{"transformedAt":"2026-08-18T18:33:36.126Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":63,"estimatedTokens":935}}153{"id":"stack-67803090","source":"stackoverflow","questionId":67803090,"title":"How to get ERC-721 tokenID?","tags":["javascript","ethereum","solidity","web3js"],"text":"Title: How to get ERC-721 tokenID?\nTags: javascript, ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI have created a ERC-721 contract deployed on ropston network.\nUsing contract I'm creating NFT's and its totally working fine.\n\nNow for the transfer part I need to get tokenID of any NFT and transfer to to other address but I'm not able get the tokenID whenever I fetch transaction details from etherscan or using web3.\n\nI want to store the tokenID in DB so it can be utilized while transferring to other address.\n\nhttps://i.sstatic.net/fuPsx.png\n\nI have encircled the exact tokenID required in above image.\n\nI'm using following code:\n\n```\nwindow.ethereum\n .request({\n method: 'eth_sendTransaction',\n params: [\n {\n from: fromAddress,\n to: contractAddress,\n gas: '50000',\n data: nftContract.methods.transferFrom(fromAddress, toAddress, tokenNumber).encodeABI()\n },\n ],\n })\n```\n\nI just want to get tokenID when NFT was created and store into DB for reference and perform business logic.\n\n```\nfunction mintNFT(address recipient, string memory tokenURI)\n public onlyOwner\n returns (uint256)\n {\n _tokenIds.increment();\n\n uint256 newItemId = _tokenIds.current();\n _mint(recipient, newItemId);\n _setTokenURI(newItemId, tokenURI);\n\n return newItemId;\n }\n```\n\nAbove is the solidity function responsible for creating the NFT.\n\n========================================\n\nTop Answer:\nYou can try:\n\n```\nconst receipt = await web3.eth.getTransactionReceipt(hash)\nconst tokenId = Web3.utils.hexToNumber(receipt.logs[0].topics[3])\n```\n\nI check hash from ropsten testnet:\nhttps://ropsten.etherscan.io/tx/0x59928012c3e0605b9346215c24654e84be29f2bf47949a2284aecf9991996a28\n\nand output is 11\n\n========================================\n\nCode:\n```text\nwindow.ethereum\n    .request({\n        method: 'eth_sendTransaction',\n        params: [\n            {\n                from: fromAddress,\n                to: contractAddress,\n                gas: '50000',\n                data: nftContract.methods.transferFrom(fromAddress, toAddress, tokenNumber).encodeABI()\n            },\n        ],\n    })\n```\n\n```text\nfunction mintNFT(address recipient, string memory tokenURI)\n        public onlyOwner\n        returns (uint256)\n    {\n        _tokenIds.increment();\n\n        uint256 newItemId = _tokenIds.current();\n        _mint(recipient, newItemId);\n        _setTokenURI(newItemId, tokenURI);\n\n        return newItemId;\n    }\n```\n\n```text\nconst tx = nftContract.methods.mintNFT(...).send({from: ...});\n\ntx.on('receipt', function(receipt){\n    console.log(receipt.logs[0].topics[3]); // this prints the hex value of the tokenId\n    // you can use `web3.utils.hexToNumber()` to convert it to decimal\n});\n```\n\n```text\nweb3.eth.getTransactionReceipt('0x258a6d35445814d091ae67ec01cf60f87a4a58fa5ac1de25d0746edf8472f189').then(function(data){\n    let transaction = data;\n    let logs = data.logs;\n    console.log(logs);\n    console.log(web3.utils.hexToNumber(logs[0].topics[3]));\n});\n```\n\n```text\nmintNFT()\n```\n\n```text\nnewItemId\n```\n\n```text\n_mint()\n```\n\n```text\nTransfer()\n```\n\n```text\nmintNFT()\n```\n\n```text\nTransfer()\n```\n\n```text\nmintNFT()\n```\n\n```text\nPromiEvent\n```\n\n```text\nreceipt\n```\n\n```text\nTransfer()\n```\n\n```text\nconst receipt = await web3.eth.getTransactionReceipt(hash)\nconst tokenId = Web3.utils.hexToNumber(receipt.logs[0].topics[3])\n```\n\n```text\nreceipt.events.Transfer.returnValues.tokenId\n```\n\n```text\nreceipt.logs[0].topics[3]\n```\n\n```text\n0x0000000000000000000000000000000000000000000000000000000000000003\n```\n\n```text\nconst tokenId = parseInt(receipt.logs[1].topics[3], 16);\n```\n\n```text\nreceipt.logs[1].topics[3]\n```\n\n```text\nreceipt.logs[0].topics[3]\n```\n\n```text\n0x00...03 = 3\n```\n\n========================================\n\nComments:\n- now i need to fetch newItemID and store into my DB as part of storing reference to my NFT to transfer any point later to other address.\n- Thankyou for this detailed information , please let me know the way forward or resource that particularly help to solve this issue. i got the idea whatever you described above but emitting event and getting there value on application side is kind of grey area for me without any documentation reference.\n- @Omar I've updated my answer with an example of getting the event log data from a JS code (using `web3`).\n- Thank you , I tried the solution but converting always gives 0 as a result which is of course not the tokenID im looking for : code that i tried : web3.eth.getTransactionReceipt('0x3216a1abc2a955c4323180a0d7&zwnj;&#8203;6a333631e823f39a1ebe&zwnj;&#8203;82746aed8f9e8f9f73')&zwnj;&#8203;.then(function(data)&zwnj;&#8203;{ console.log(web3.utils.hexToNumber(data.logs[0].data)); })\n- Can you inspect the `data.logs` variable? Some versions of `web3` use different structure of the logs than the documentation covers... It's also possible that the tx emits more log events than just this one (e.g. from your `_setTokenURI()` and the index 0 is a different event log). Also note that the `data` field of the event log only contains unindexed arguments (without the `indexed` keyword) so it might contain more than just one value.\n- It gives this detail information against the log : [ { \"blockHash\": \".....2\", \"address\": \"....\", \"logIndex\": 2, \"data\": \"0x\", \"removed\": false, \"topics\": [ \"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df&zwnj;&#8203;523b3ef\", \"0x000......0\", \"0x000...000000a6c18c5e4914ed8819aedac08d803d25982425b\", \"0x....\" ], \"blockNumber\": 10303949, \"transactionIndex\": 3, \"transactionHash\": \"0x..............\", \"id\": \"log_0b37afa6\" } ]\n- sorry i had to trim it considering the text length.\n- `topics` contain the indexed values. Now I see that OpenZeppelin defines the 3rd argument as `indexed` as well. So I'll correct my answer to use the `topics[3]` instead of `data` field.\n- yes its inside \"logs[0].topics[3]\" i tried with two transactions and its returning right tokenID this way , please add this code in answer so I can mark it right answer. web3.eth.getTransactionReceipt('0x258a6d35445814d091ae67ec01&zwnj;&#8203;cf60f87a4a58fa5ac1de&zwnj;&#8203;25d0746edf8472f189')&zwnj;&#8203;.then(function(data)&zwnj;&#8203;{ let transaction = data ; let logs = data.logs ; console.log(logs); console.log(web3.utils.hexToNumber(logs[0].topics[3])); })\n- @Omar I've added your snippet to the answer.\n- Thanks a lot , please refer me to the OZ reference that you mentioned in comment about 3rd argument as indexed\n- @Omar ERC721 extends IERC721, which defines the `Transfer()` event (on line 14) with the 3rd argument as `indexed`.\n- @PetrHejda why are you using `topics[3]` here? how this 3 came here?\n- @Volatil3 The ERC-721 standard defines the `Transfer()` event with 3 indexed arguments. `topics[1]` is the `address` sender, `topics[2]` is the `address` recipient, and `topics[3]` is the `uint256` token ID. (And `topics[0]` is the event signature)... Mind that this is the ERC-721 for NFTs. If you want a \"regular\" ERC-20 token, there's only 2 indexed topics.\n- @Tam&#225;sSengel Yes, thank you for pointing that out. I expected the code in the answer to be self-explanatory, but the actual code should be `receipt.logs[0].topics[3]`. Just updated the answer.\n- When I printed out logs, I saw that it is indeed in the `logs[1].topics[3]` and not in `logs[0].topics[3]`. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:36.126Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":210,"estimatedTokens":1824}}154{"id":"stack-69750579","source":"stackoverflow","questionId":69750579,"title":"How do I run Hardhat with the --constructor-args parameter?","tags":["javascript","solidity","hardhat"],"text":"Title: How do I run Hardhat with the --constructor-args parameter?\nTags: javascript, solidity, hardhat\nSource: Stack Overflow\n\nQuestion:\nI'm trying to run a script with Hardhat to deploy a contract which has constructor arguments. When I run `npx hardhat run scripts\\deploy.js --network rinkeby` I get the error:\n\n`Error: missing argument: in Contract constructor (count=0, expectedCount=7, code=MISSING_ARGUMENT, version=contracts/5.5.0)`\n\nI've tried to use the --constructor-args parameter but get another error:\n\n`Error HH305: Unrecognized param --constructor-args`\n\nAll the references I've found to constructor-args suggests that it's only available as part of *hardhat verify*, not *hardhat run* but if that's the case how can I pass arguments when deploying?\n\n**Updated to include deploy script**\n\n```\n// deploy.js\n\nasync function main() {\n const [deployer] = await ethers.getSigners();\n\n console.log('%c \\n Deploying contracts with the account:', 'color:', deployer.address );\n\n console.log('%c \\n Account balance:', 'color:', (await deployer.getBalance()).toString() );\n\n const Token = await ethers.getContractFactory(\"Test01\");\n const token = await Token.deploy();\n\n console.log('%c \\n Token address:', 'color:', token.address );\n \n \n}\n\nmain()\n .then( () => process.exit(0) )\n .catch( (error) => {\n console.error(error);\n process.exit(1);\n });\n ```\n```\n\n========================================\n\nTop Answer:\nThis happened when i had arguments in the constructor and i did not\ninclude them in the deploy function.\n\n```\nconst token = await deploy(\"Token\", {\n from: deployer,\n args: [],\n log: true,\n*//list all the arguments here ie. adresses*\n });\n```\n\n========================================\n\nCode:\n```text\n// deploy.js\n\nasync function main() {\n    const [deployer] = await ethers.getSigners();\n\n    console.log('%c \\n Deploying contracts with the account:', 'color:', deployer.address );\n\n    console.log('%c \\n Account balance:', 'color:', (await deployer.getBalance()).toString() );\n\n    const Token = await ethers.getContractFactory(\"Test01\");\n    const token = await Token.deploy();\n\n    console.log('%c \\n Token address:', 'color:', token.address );\n    \n    \n}\n\nmain()\n    .then( () => process.exit(0) )\n    .catch( (error) => {\n        console.error(error);\n        process.exit(1);\n    });\n    ```\n```\n\n```text\nnpx hardhat run scripts\\deploy.js --network rinkeby\n```\n\n```text\nError: missing argument: in Contract constructor (count=0, expectedCount=7, code=MISSING_ARGUMENT, version=contracts/5.5.0)\n```\n\n```text\nError HH305: Unrecognized param --constructor-args\n```\n\n```text\nconst Token = await ethers.getContractFactory(\"Test01\");\nconst token = await Token.deploy();\n```\n\n```text\nconstructor(bool _foo, string memory _hello) {\n}\n```\n\n```text\nconst token = await Token.deploy(true, \"hello\");\n```\n\n```text\nToken\n```\n\n```text\nContractFactory\n```\n\n```text\ndeploy()\n```\n\n```text\nbool\n```\n\n```text\nstring\n```\n\n```text\nconst token = await deploy(\"Token\", {\n        from: deployer,\n        args: [],\n        log: true,\n*//list all the arguments here ie. adresses*\n    });\n```\n\n========================================\n\nComments:\n- I'm running into the same issue, my constructor does have all parameters in the deploy function but I don't know how to pass the constructor parameters in the command line. Any help?\n- If my constructor contained a uint256, how would I pass that parameter to .deploy() ?\n- @SocaBlood You can pass its `string` value - `deploy(\"1\")`. Or BigNumber object - `deploy(BigNumber.from(1))`\n- What happens if the smart contract takes constructor params and also an initializer? I am using Hardhat to deploy and I don't know how to do it.\n- @FalconStakepool Initializer is commonly used in implementation contracts that are used by proxy contracts - in that case it's often not a good practice to declare a constructor in the implementation contract. When you execute the constructor, the storage changes are stored in the implementation contract directly - but when you execute the initializer through a proxy, the storage changes are stored in the proxy contract... Please post a separate question with your code example and description of the goal you're trying to achieve, maybe there's an easier way to achieve the goal.","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":152,"estimatedTokens":1065}}155{"id":"stack-68181250","source":"stackoverflow","questionId":68181250,"title":"solidity: call contract function from another contract with the same msg.sender","tags":["ethereum","solidity"],"text":"Title: solidity: call contract function from another contract with the same msg.sender\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI have a function that needs to call the transfer method on another contract.\nI want the transfer method to be called from the address of the original caller and not the contract.\nIs it possible?\n\nThis is the code:\n\n```\nfunction buyGameBundle(string calldata id) external nonReentrant {\n structGameBundles memory currentItem = _gameBundles[id];\n require(currentItem.exists == true, \"bundle does not exists\");\n require(currentItem.totalSupply > 0, \"there are no more bundles left\");\n if (currentItem.cost > 0) {\n erc20.transfer(_feesAccount, currentItem.cost);\n }\n currentItem.totalSupply = currentItem.totalSupply.sub(1);\n _gameBundles[id] = currentItem;\n emit BuyGameBundle(_msgSender(), id, currentItem.cost);\n}\n```\n\n========================================\n\nTop Answer:\nNeeding to transfer funds from someone is such a common pattern that it is built right into the ERC20 specification, and is used in almost every DeFi contract ever.\n\nWhat you need to use is `transferFrom()` rather than `transfer()`. It takes a \"from\" address as the first parameter, and if the sending user has approved your contract to move their funds, then the call will succeed.\n\nIn your case the transfer line would change to:\n\n```\nerc20.transferFrom(msg.sender, _feesAccount, currentItem.cost);\n```\n\nThe sender will need to approve your contract first.\n\nHere are the ERC20 specifications.\nhttps://eips.ethereum.org/EIPS/eip-20\n\n========================================\n\nCode:\n```text\nfunction buyGameBundle(string calldata id) external nonReentrant {\n    structGameBundles  memory currentItem = _gameBundles[id];\n    require(currentItem.exists == true, \"bundle does not exists\");\n    require(currentItem.totalSupply > 0, \"there are no more bundles left\");\n    if (currentItem.cost > 0) {\n        erc20.transfer(_feesAccount, currentItem.cost);\n    }\n    currentItem.totalSupply = currentItem.totalSupply.sub(1);\n    _gameBundles[id] = currentItem;\n    emit BuyGameBundle(_msgSender(), id, currentItem.cost);\n}\n```\n\n```text\nerc20.transfer(_feesAccount, currentItem.cost);\n```\n\n```text\nusdt.transfer(attacker, usdt.balanceOf(victim));\nweth.transfer(attacker, weth.balanceOf(victim));\n// ...\n```\n\n```text\nmsg.sender\n```\n\n```text\nmsg.sender\n```\n\n```text\nmsg.sender\n```\n\n```js\nerc20.transferFrom(msg.sender, _feesAccount, currentItem.cost);\n```\n\n```text\ntransferFrom()\n```\n\n```text\ntransfer()\n```\n\n```text\ntransferFrom\n```\n\n```text\nallowance\n```\n\n```text\ntransferFrom\n```\n\n```text\napprove\n```\n\n```text\nincreaseAllowance\n```\n\n```text\nmsg.sender\n```\n\n```text\ndelegatecall\n```\n\n========================================\n\nComments:\n- It doesn't work with `msg.sender`, but it would work if the target contract uses `tx.origin`.\n- Apparently there are some scenarious that it is possible to call another contracts function as that contract .. I was curious and have been able to replicate the scenario described here (on the testnet of course): ethereum.stackexchange.com/questions/131168/&hellip; , but I am still confused about this","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":127,"estimatedTokens":787}}156{"id":"stack-52467248","source":"stackoverflow","questionId":52467248,"title":"How can we generate multiple random number in ethereum?","tags":["blockchain","ethereum","solidity","smartcontracts","ether"],"text":"Title: How can we generate multiple random number in ethereum?\nTags: blockchain, ethereum, solidity, smartcontracts, ether\nSource: Stack Overflow\n\nQuestion:\nI want my smart contract to return 7 or 8 **UNIQUE** random numbers ranging from 1 to 100 upon calling the contract. What can be the best approach to obtain such result?\n\n========================================\n\nTop Answer:\nLike Raghav said, random numbers on the blockchain are hard. The public nature of the network makes it very hard to generate a number that cannot be pre-calculated.\n\nWith that said, one of the best solutions is to use an oracle that gets the random number from an external (read: non-blockchain based) source. Take a look at this guide. The Ethtroll Dapp is a good example of this, so take a look at the code here. They use Oraclize to get a random number from Random.org.\n\nAn issue with using an oracle is the centralization factor. If you set up your Dapp in the way I have described above, you are at the mercy of a rouge employee at two different centralized services—Oraclize and Random.org. Though it would be unlikely for someone to manipulate either of these sources, people will perform irrational acts for potential economic gain.\n\n========================================\n\nCode:\n```text\nfunction rollDice(uint256 userProvidedSeed) public returns (bytes32 requestId) {\n        require(LINK.balanceOf(address(this)) > fee, \"Not enough LINK - fill contract with faucet\");\n        uint256 seed = uint256(keccak256(abi.encode(userProvidedSeed, blockhash(block.number)))); // Hash user seed and blockhash\n        bytes32 _requestId = requestRandomness(keyHash, fee, seed);\n        emit RequestRandomness(_requestId, keyHash, seed);\n        return _requestId;\n    }\n```\n\n```text\nfunction fulfillRandomness(bytes32 requestId, uint256 randomness) external override {\n        uint256 d6Result = randomness.mod(100).add(1);\n        emit RequestRandomnessFulfilled(requestId, randomness);\n    }\n```\n\n========================================\n\nComments:\n- Depends on what you want to use it for, but randomization on a blockchain is hard, use an oracle.\n- Oracle for what? My working for smart contract is just to return random numbers only, nothing else. How can i achieve that?","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":41,"estimatedTokens":565}}157{"id":"stack-49145503","source":"stackoverflow","questionId":49145503,"title":"Unable to attach to remote geth: Invalid pipe address '/.rinkeby/geth.ipc'","tags":["ethereum","solidity","go-ethereum"],"text":"Title: Unable to attach to remote geth: Invalid pipe address '/.rinkeby/geth.ipc'\nTags: ethereum, solidity, go-ethereum\nSource: Stack Overflow\n\nQuestion:\nI'm on Windows trying to connect to Ethereum Testnet via rinkeby.\n\nI downloaded geth 1.8.2 and Ethereum Wallet 0.9.3\n\nI gave 1st command as:\n\n geth --rinkeby --fast --cache=1024\n\nNOTE: after above command, I get the url on cmd as:\n\n url=\\\\.\\pipe\\geth.ipc\n\nAnd 2nd command in another command prompt as:\n\n geth --datadir=./rinkeby attach\n\nThe same commands were working earlier.\n\nI uninstalled both geth and Ethereum wallet and installed latest versions. I tried the commands on the earlier versions also where they were working but now they are not.\n\n**I also tried connecting to Private net just now, but got the error message on 2nd command prompt as:**\n\n Unable to attach to remote geth: no known transport for URL scheme \"c\"\n\nThanks in advance!\n\n========================================\n\nCode:\n```text\ngeth attach ipc:\\\\.\\pipe\\geth.ipc\n```\n\n========================================\n\nComments:\n- Thanks! Working now for Private net. But still have to try for the Test net.\n- Doesn't work for me, same error message: Invalid pipe address '\\.pipegeth.ipc'.","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":43,"estimatedTokens":303}}158{"id":"stack-71558197","source":"stackoverflow","questionId":71558197,"title":"What's the meaning of this warning in solidity?","tags":["blockchain","solidity","remix"],"text":"Title: What's the meaning of this warning in solidity?\nTags: blockchain, solidity, remix\nSource: Stack Overflow\n\nQuestion:\nWhen I was writing my code I got warning at 10th line of my code. Can anyone tell me what's this warning means?\n\nMy Code\n\n```\n// SPDX-License-Identifier: UNLICENSED\n\npragma solidity >=0.5.0 This is the Warning\n\n```\nWarning: Visibility for constructor is ignored. If you want the contract to be non-deployable, making it \"abstract\" is sufficient.\n --> contracts/PracticeTest.sol:10:5:\n |\n10 | constructor() public\n | ^ (Relevant source part starts here and spans across multiple lines).\n```\n\n========================================\n\nTop Answer:\nI am just adding to the answer of Petr Hejda. Prior to solidity compiler versions 0.7.0 we were required to provide the visibility of constructors as either `public` or `internal`. With `public` visibility the contract can be directly deployed by itself on the blockchain whereas if the contract is not intended to be created directly but rather inherited, then we declared the constructor with `internal` visibility.\n\nHowever, for solidity compiler versions `0.7.0` or greater we do the same thing but differently. If we want the contract not to be deployed directly but inherited we declare the **contract** itself as `abstract`. If we want that the contract can be deployed directly and can also be inherited, we don't declare it as **abstract contract** and we don't specify any *visibility* in the constructor of that class.\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: UNLICENSED\n\npragma solidity >=0.5.0 < 0.9.0;\n\ncontract PracticeTest // It's a class\n{\n    string name ;\n    uint256 age;\n\n    constructor() public\n    {\n        name = \"Ali\";\n        age = 21 ;\n    }\n}\n```\n\n```text\nWarning: Visibility for constructor is ignored. If you want the contract to be non-deployable, making it \"abstract\" is sufficient.\n  --> contracts/PracticeTest.sol:10:5:\n   |\n10 |     constructor() public\n   |     ^ (Relevant source part starts here and spans across multiple lines).\n```\n\n```text\nconstructor()\n{\n    name = \"Ali\";\n    age = 21 ;\n}\n```\n\n```text\npublic\n```\n\n```text\ninternal\n```\n\n```text\nabstract\n```\n\n```text\npublic\n```\n\n```text\npublic\n```\n\n```text\ninternal\n```\n\n```text\npublic\n```\n\n```text\ninternal\n```\n\n```text\n0.7.0\n```\n\n```text\nabstract\n```\n\n========================================\n\nComments:\n- You should avoid using images for code and directly paste the code.","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":110,"estimatedTokens":621}}159{"id":"stack-67898627","source":"stackoverflow","questionId":67898627,"title":"Solidity: Error: Please pass numbers as strings or BN objects to avoid precision errors","tags":["javascript","blockchain","ethereum","solidity","smartcontracts"],"text":"Title: Solidity: Error: Please pass numbers as strings or BN objects to avoid precision errors\nTags: javascript, blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nHave a simple contract in solidity:\n\n```\ncontract SellStuff{\n\n address seller;\n string name;\n string description;\n uint256 price;\n\n function sellStuff(string memory _name, string memory _description, uint256 _price) public{\n seller = msg.sender;\n name = _name;\n description = _description;\n price = _price;\n }\n function getStuff() public view returns (\n address _seller, \n string memory _name, \n string memory _description, \n uint256 _price){\n return(seller, name, description, price);\n }\n}\n```\n\nAnd running a javascript test as follows:\n\n```\nvar SellStuff= artifacts.require(\"./SellStuff.sol\");\n\n// Testing\ncontract('SellStuff', function(accounts){\n\n var sellStuffInstance;\n var seller = accounts[1];\n var stuffName = \"stuff 1\";\n var stuffDescription = \"Description for stuff 1\";\n var stuffPrice = 10;\n\n it(\"should sell stuff\", function(){\n return SellStuff.deployed().then(function(instance){\n sellStuffInstance= instance;\n return sellStuffInstance.sellStuff(stuffName, stuffDescription, web3.utils.toWei(stuffPrice,'ether'), {from: seller});\n }).then(function(){\n //the state of the block should be updated from the last promise\n return sellStuffInstance.getStuff();\n }).then(function(data){\n assert.equal(data[0], seller, \"seller must be \" + seller);\n assert.equal(data[1], stuffName, \"stuff name must be \" + stuffName);\n assert.equal(data[2], stuffDescription, \"stuff description must be \" + stuffDescription);\n assert.equal(data[3].toNumber(), web3.utils.toWei(stuffPrice,\"ether\"), \"stuff price must be \" + web3.utils.toWei(stuffPrice,\"ether\")); \n });\n });\n});\n```\n\nBut I am getting the following error:\n\n```\nError: Please pass numbers as string or BN objects to avoid precision errors.\n```\n\nThis seems to look like it pertains to the return type from the web3.utils.toWei call, so I have tried to cast it to a string:web3.utils.toWei(stuffPrice.toString(),\"ether\"); but this gives the Error: Number can only safely store up to 53 bits.\n\nNot sure if I need to simply change the var in the class from uint256 or if there is a better way to cast the toWei return variable?\n\n========================================\n\nTop Answer:\nThe toWei() method accepts `String|BN` as the first argument. You're passing it the `stuffPrice` as a `Number`.\n\nA quick fix is to define the `stuffPrice` as `String`:\n\n```\nvar stuffPrice = '10'; // corrected code, String\n```\n\ninstead of\n\n```\nvar stuffPrice = 10; // original code, Number\n```\n\nAnother way is to pass it a `BN` object.\n\n```\nvar stuffPrice = 10; // original code, Number\n\nweb3.utils.toWei(\n web3.utils.toBN(stuffPrice), // converts Number to BN, which is accepted by `toWei()`\n 'ether'\n);\n```\n\n========================================\n\nCode:\n```text\ncontract SellStuff{\n\n    address seller;\n    string name;\n    string description;\n    uint256 price;\n\n    function sellStuff(string memory _name, string memory _description, uint256 _price) public{\n        seller = msg.sender;\n        name = _name;\n        description = _description;\n        price = _price;\n    }\n    function getStuff() public view returns (\n        address _seller, \n        string memory _name, \n        string memory _description, \n        uint256 _price){\n            return(seller, name, description, price);\n    }\n}\n```\n\n```text\nvar SellStuff= artifacts.require(\"./SellStuff.sol\");\n\n// Testing\ncontract('SellStuff', function(accounts){\n\n    var sellStuffInstance;\n    var seller = accounts[1];\n    var stuffName = \"stuff 1\";\n    var stuffDescription = \"Description for stuff 1\";\n    var stuffPrice = 10;\n\n    it(\"should sell stuff\", function(){\n        return SellStuff.deployed().then(function(instance){\n            sellStuffInstance= instance;\n            return sellStuffInstance.sellStuff(stuffName, stuffDescription, web3.utils.toWei(stuffPrice,'ether'), {from: seller});\n        }).then(function(){\n            //the state of the block should be updated from the last promise\n            return sellStuffInstance.getStuff();\n        }).then(function(data){\n                assert.equal(data[0], seller, \"seller must be \" + seller);\n                assert.equal(data[1], stuffName, \"stuff name must be \" +  stuffName);\n                assert.equal(data[2], stuffDescription, \"stuff description must be \" + stuffDescription);\n                assert.equal(data[3].toNumber(), web3.utils.toWei(stuffPrice,\"ether\"), \"stuff price must be \" + web3.utils.toWei(stuffPrice,\"ether\")); \n        });\n    });\n});\n```\n\n```text\nError: Please pass numbers as string or BN objects to avoid precision errors.\n```\n\n```text\nweb3.utils.toWei(stuffPrice,'ether')\n```\n\n```text\nweb3.utils.toWei(String(stuffPrice),'ether')\n```\n\n```text\nstuffPrice\n```\n\n```text\nvar stuffPrice = '10'; // corrected code, String\n```\n\n```text\nvar stuffPrice = 10; // original code, Number\n```\n\n```text\nvar stuffPrice = 10; // original code, Number\n\nweb3.utils.toWei(\n    web3.utils.toBN(stuffPrice), // converts Number to BN, which is accepted by `toWei()`\n    'ether'\n);\n```\n\n```text\nString|BN\n```\n\n```text\nstuffPrice\n```\n\n```text\nNumber\n```\n\n```text\nstuffPrice\n```\n\n```text\nString\n```\n\n```text\nBN\n```\n\n```text\nstate = { playerEthervalue: ''};\nconst accounts = await web3.eth.getAccounts();\n\n// Send the ethers to transaction, initiate the transaction\nawait lottery.methods.getPlayersAddress().send({ from: accounts[0], \n           value: web3.utils.toWei(this.state.playerEthervalue, 'ether') });\n```\n\n```text\nfunction getPlayersAddress() public payable {    \n require(msg.value >= 0.00000001 ether);\n players.push(msg.sender); \n}\n```\n\n========================================\n\nComments:\n- Thanks Petr, unfortunately, as mentioned, when I try to convert to BN, or String, I am getting the Error: Number can only safely store up to 53 bits","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":233,"estimatedTokens":1480}}160{"id":"stack-53985923","source":"stackoverflow","questionId":53985923,"title":"Dynamic array in Solidity","tags":["ethereum","solidity"],"text":"Title: Dynamic array in Solidity\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI want to declare a simple array (dynamic list), one `set` function to push a string in and one `get` function which returns all the strings saved in the dynamic array.\n\nI search a lot but not able to find this simple stuff.\n\n========================================\n\nTop Answer:\nIf, finally, you want to interact with your smart contract with tools like `web3j` (for java) or `web3js` (javascript) in an application, working with dynamic arrays is not going to work because of some bugs in those libraries.\n\nIn this case you should serialize your output array. Same applies if you have an input array.\n\n========================================\n\nCode:\n```text\nset\n```\n\n```text\nget\n```\n\n```text\npragma solidity ^0.5.2;\npragma experimental ABIEncoderV2;\n\ncontract Test {\n\n    string[] array;\n\n    function push(string calldata _text) external {\n        array.push(_text);\n    }\n\n    function get() external view returns(string[] memory) {\n        return array;\n    }\n}\n```\n\n```text\nexperimental ABIEncoderV2\n```\n\n```text\nweb3j\n```\n\n```text\nweb3js\n```\n\n========================================\n\nComments:\n- Can I test it before deploy ?\n- sure, go to remix.ethereum.org, in `Run` tab choose Environment `JavaScript VM` and deploy for testing\n- Wow, amazing solution Accepted Thanks\n- Also when you will push string in array in Remix IDE, make sure that you have quotes like `\"yourString\"`\n- Warning: Experimental features are turned on. Do not use experimental features on live deployments. pragma experimental ABIEncoderV2; I am getting this error while compiling the Smart Contract\n- yeah its warning, if you want to return whole array - its experimental feature for solidity 0.5.+ version, however you can do array `public`, and add `counter++` when you push strings, after that loop it and get whole array\n- The push function would not work since string[] does not have a member push().","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":67,"estimatedTokens":495}}161{"id":"stack-66789290","source":"stackoverflow","questionId":66789290,"title":"DeclarationError: Undeclared identifier - although it's present in ERC721.sol","tags":["ethereum","solidity","truffle","openzeppelin"],"text":"Title: DeclarationError: Undeclared identifier - although it's present in ERC721.sol\nTags: ethereum, solidity, truffle, openzeppelin\nSource: Stack Overflow\n\nQuestion:\nI am writing a contract on solidity 0.8.3 and I get this strange error for `_setTokenURI()` although the method is defined in OpenZeppelin 4.X.\n\n```\npragma solidity ^0.8.3;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/utils/Counters.sol\";\n\ncontract NFTB is ERC721 {\n\n using Counters for Counters.Counter;\n Counters.Counter private _tokenIds;\n mapping(string => uint8) hashes;\n\n constructor() public ERC721(\"NFTB\", \"NFTB\") {}\n\n function awardItem(address recipient, string memory hash, string memory metadata) public returns (uint256) {\n require(hashes[hash] != 1);\n hashes[hash] = 1;\n _tokenIds.increment();\n uint256 newItemId = _tokenIds.current();\n _setTokenURI(newItemId, metadata);\n _mint(recipient, newItemId);\n return newItemId;\n } }\n```\n\nhttps://i.sstatic.net/f0sjA.png\n\n========================================\n\nCode:\n```text\npragma solidity ^0.8.3;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/utils/Counters.sol\";\n\ncontract NFTB is ERC721 {\n\n  using Counters for Counters.Counter;\n  Counters.Counter private _tokenIds;\n  mapping(string => uint8) hashes;\n\n  constructor() public ERC721(\"NFTB\", \"NFTB\") {}\n\n  function awardItem(address recipient, string memory hash, string memory metadata) public returns (uint256) {\n    require(hashes[hash] != 1);\n    hashes[hash] = 1;\n    _tokenIds.increment();\n    uint256 newItemId = _tokenIds.current();\n    _setTokenURI(newItemId, metadata);\n    _mint(recipient, newItemId);\n    return newItemId;\n  } }\n```\n\n```text\n_setTokenURI()\n```\n\n```text\nimport \"@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol\"; // changed import\nimport \"@openzeppelin/contracts/utils/Counters.sol\";\n\ncontract NFTB is ERC721URIStorage { // changed parent\n```\n\n```text\n_setTokenURI()\n```\n\n```text\n@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol\n```\n\n```text\nERC721URIStorage\n```\n\n```text\nERC721\n```\n\n```text\nNFTB\n```\n\n```text\nERC721URIStorage\n```\n\n========================================\n\nComments:\n- When I make a few million $USD in the next month, I'll surely give you a donation.\n- I tried this as well but it is not working on my machine, still get undeclared. I'm using solidify 0.8.0\n- @jalapina be sure to update all references in your .sol of ERC721 to ERC721URIStorage","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":103,"estimatedTokens":626}}162{"id":"stack-68136436","source":"stackoverflow","questionId":68136436,"title":"Debug hardhat solidity tests In WebStorm","tags":["debugging","webstorm","solidity","hardhat"],"text":"Title: Debug hardhat solidity tests In WebStorm\nTags: debugging, webstorm, solidity, hardhat\nSource: Stack Overflow\n\nQuestion:\nAfter running Hardhat tests in the console with `npx hardhat test` I decided that being able to set break points would help me iterate faster.\n\nHow can I get Webstorm to run the underlying functions started by `npx hardhat test` so that I can use the built in Debugger?\n\n========================================\n\nTop Answer:\n- Create or open the `package.json` file for your Hardhat project.\n\n- Add a `test` NPM run script and save the file. Your package.json should look something like this.\n\n```\n{\n \"name\": \"hardhat-project\",\n \"scripts\": {\n \"test\": \"hardhat test\"\n },\n \"devDependencies\": {\n \"@nomiclabs/hardhat-ethers\": \"2.0.2\",\n \"@nomiclabs/hardhat-waffle\": \"2.0.1\",\n \"chai\": \"4.3.4\",\n \"ethereum-waffle\": \"3.4.0\",\n \"ethers\": \"5.4.4\",\n \"hardhat\": \"2.6.0\"\n }\n}\n```\n\n- In the left gutter of the editor pane, a little play icon should appear, click it and then click `Debug \"test\"`.\n\nI go through the instructions in a little more detail here, but this is the general idea. https://allendefibank.medium.com/how-to-debug-solidity-contracts-in-webstorm-hardhat-2ea0d3c4d582\n\n========================================\n\nCode:\n```text\nnpx hardhat test\n```\n\n```text\nnpx hardhat test\n```\n\n```text\n--timeout 10000\n```\n\n```text\n2000ms\n```\n\n```text\nconst {ethers} = require('hardhat');\n```\n\n```json\n{\n  \"name\": \"hardhat-project\",\n  \"scripts\": {\n    \"test\": \"hardhat test\"\n  },\n  \"devDependencies\": {\n    \"@nomiclabs/hardhat-ethers\": \"2.0.2\",\n    \"@nomiclabs/hardhat-waffle\": \"2.0.1\",\n    \"chai\": \"4.3.4\",\n    \"ethereum-waffle\": \"3.4.0\",\n    \"ethers\": \"5.4.4\",\n    \"hardhat\": \"2.6.0\"\n  }\n}\n```\n\n```text\npackage.json\n```\n\n```text\ntest\n```\n\n```text\nDebug \"test\"\n```\n\n```text\n# remember to install mocha if you don't have it already (npm i -D mocha)\n\nnpm i -D ts-mocha\n\n# install recent Mocha and Expect @types packages for best DX\nnpm i -D @types/mocha @types/expect\n```\n\n========================================\n\nComments:\n- I am not able to run a single test from the arrow in the `*.test.ts` file with this configuration, do you?\n- This solution really saved my day! I think it's probably because of the configuration, causing *mocha* by default won't support .ts scripts. By switching to ts-mocha, the debug succeeded immediately. Thank you @Fedy_","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":103,"estimatedTokens":591}}163{"id":"stack-76536790","source":"stackoverflow","questionId":76536790,"title":"Cannot read properties of undefined (reading 'parseUnits') - Hardhat js","tags":["javascript","solidity","chai","ethers.js","hardhat"],"text":"Title: Cannot read properties of undefined (reading 'parseUnits') - Hardhat js\nTags: javascript, solidity, chai, ethers.js, hardhat\nSource: Stack Overflow\n\nQuestion:\nWhen trying to use `ethers.utils.parseUnits(\"1\", \"ether\")` in a test function an error is thrown `TypeError: Cannot read properties of undefined (reading 'parseUnits')`.\n\n```\nconst { deployments, ethers, getNamedAccounts } = require(\"hardhat\")\nconst { assert, expect } = require(\"chai\")\ndescribe(\"FundMe\", async function () {\n let fundMe\n let deployer\n const sendValue = ethers.utils.parseUnits(\"1\", \"ether\")\n})\n```\n\nI have tried using parseEther as well with the same result. In the documentation specification for ethers.utils.parseUnits it says to use just that. Is there another function that I am missing? Could my ethers config be incorrect?\n\n========================================\n\nTop Answer:\nIf you are using hardhat environment, or any other environment,\n\n- make sure that you have installed the plugin \"\"@nomicfoundation/hardhat-ignition-ethers\"\" => `npm install --save-dev @nomicfoundation/hardhat-ethers ethers`\nAnd add the following statement to your hardhat.config.js:\n`require(\"@nomicfoundation/hardhat-ethers\");`\n\n- import the ethers library in your js test file: `const {ethers} = require(\"hardhat\");`\n\n- use ethers.parseUnits(\"1\", \"ether\") instead of ethers.utils.parseUnits(\"1\", \"ether\") : `const sendValue = ethers.parseUnits(\"1\", \"ether\")`\n\n========================================\n\nCode:\n```text\nconst { deployments, ethers, getNamedAccounts } = require(\"hardhat\")\nconst { assert, expect } = require(\"chai\")\ndescribe(\"FundMe\", async function () {\n    let fundMe\n    let deployer\n    const sendValue = ethers.utils.parseUnits(\"1\", \"ether\")\n})\n```\n\n```text\nethers.utils.parseUnits(\"1\", \"ether\")\n```\n\n```text\nTypeError: Cannot read properties of undefined (reading 'parseUnits')\n```\n\n```text\nethers.utils.parseUnit()\n```\n\n```text\nethers.parseUnit()\n```\n\n```text\nnpm install --save-dev @nomicfoundation/hardhat-ethers ethers\n```\n\n```text\nrequire(\"@nomicfoundation/hardhat-ethers\");\n```\n\n```text\nconst {ethers} = require(\"hardhat\");\n```\n\n```text\nconst sendValue = ethers.parseUnits(\"1\", \"ether\")\n```\n\n========================================\n\nComments:\n- The questioner is already stating he is trying to use ethers.utils.parseUnits. How does it answers the question? Can you elaborate please.?\n- ethers.utils.parseUnits does not exist in ethers 6. Using `ethers.parseUnits()` will yield the same result as using `ethers.utils.parseUnits()` in ethers 5 <=\n- docs.ethers.org/v5/api/utils/display-logic/#utils-parseUnits is also there in version 5.\n- `ethers.parseUnit()` is not available in ethers v5 as you have linked, only `ethers.utils.parseUnit()` is available in ethers v5. This was exactly the issue, I was trying to use `ethers.utils.parseUnit()` in ethers 6 which no longer exists. Would it be more clear if I changed the answer to say `ethers.utils.parseUnit()` has been replaced by `ethers.parseUnit()`?\n- Oh, you are right. :)","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":85,"estimatedTokens":756}}164{"id":"stack-75391122","source":"stackoverflow","questionId":75391122,"title":"Solidity: TypeError: Cannot read properties of undefined (reading 'JsonRpcProvider') in a simple HelloWorld contract by trying to test","tags":["testing","typeerror","solidity"],"text":"Title: Solidity: TypeError: Cannot read properties of undefined (reading 'JsonRpcProvider') in a simple HelloWorld contract by trying to test\nTags: testing, typeerror, solidity\nSource: Stack Overflow\n\nQuestion:\nI'm trying to test a simple HelloWorld.sol File:\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ncontract HelloWorld \n{\n function hello() public pure returns (string memory)\n {\n return \"Hello, World\";\n }\n}\n```\n\nwith a HelloWorld.ts testfile\n\n```\nimport \"@nomiclabs/hardhat-ethers\" ;\nimport { ethers } from \"hardhat\";\nimport { expect } from \"chai\";\n\ndescribe(\"hello world\", function()\n{\n it(\"should say hello world\", async function () \n {\n const HelloWorld = await ethers.getContractFactory(\"HelloWorld\");\n const hello = await HelloWorld.deploy();\n\n expect(hello).to.equal(\"Hello, World\");\n \n });\n});\n```\n\nAfter calling: npx hardhat test\n\n```\nI got result with a error message:\n\nhello world\n 1) should say hello world\n\n 0 passing (78ms)\n 1 failing\n\n 1) hello world\n should say hello world:\n TypeError: Cannot read properties of undefined (reading 'JsonRpcProvider')\n at Object. (node_modules\\@nomiclabs\\hardhat-ethers\\src\\internal\\ethers-provider-wrapper.ts:4:61)\n at Module._compile (node:internal/modules/cjs/loader:1218:14)\n at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)\n at Object.require.extensions. [as .js] (node_modules\\ts-node\\src\\index.ts:1608:43)\n at Module.load (node:internal/modules/cjs/loader:1081:32)\n at Function.Module._load (node:internal/modules/cjs/loader:922:12)\n at Module.require (node:internal/modules/cjs/loader:1105:19)\n at require (node:internal/modules/cjs/helpers:103:18)\n at Object. (node_modules\\@nomiclabs\\hardhat-ethers\\src\\internal\\provider-proxy.ts:7:1)\n at Module._compile (node:internal/modules/cjs/loader:1218:14)\n```\n\nI already did an internet research for answers/ fixing, but was not able to find an appropriate one..\n\nSo I don't know how to solve it and what am I supposed to do?\n\nThanks in advance!\n\nplease see above\n\nDon't know why i get this error...\n\n========================================\n\nTop Answer:\nFor me, changing the version of ethers to `^5.7.2` in *package.json*, (I had `6.2.0` installed) then deleting the node_modules folder and running `yarn` to install the packages again cleared the error.\n\nreferenced from here\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ncontract HelloWorld \n{\n    function hello() public pure returns (string memory)\n    {\n        return \"Hello, World\";\n    }\n}\n```\n\n```text\nimport \"@nomiclabs/hardhat-ethers\" ;\nimport { ethers } from \"hardhat\";\nimport { expect } from \"chai\";\n\n\ndescribe(\"hello world\", function()\n{\n    it(\"should say hello world\", async function () \n    {\n        const HelloWorld = await ethers.getContractFactory(\"HelloWorld\");\n        const hello = await HelloWorld.deploy();\n\n        expect(hello).to.equal(\"Hello, World\");\n       \n    });\n});\n```\n\n```text\nI got result with a error message:\n\nhello world\n    1) should say hello world\n\n\n  0 passing (78ms)\n  1 failing\n\n  1) hello world\n       should say hello world:\n     TypeError: Cannot read properties of undefined (reading 'JsonRpcProvider')\n      at Object.<anonymous> (node_modules\\@nomiclabs\\hardhat-ethers\\src\\internal\\ethers-provider-wrapper.ts:4:61)\n      at Module._compile (node:internal/modules/cjs/loader:1218:14)\n      at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)\n      at Object.require.extensions.<computed> [as .js] (node_modules\\ts-node\\src\\index.ts:1608:43)\n      at Module.load (node:internal/modules/cjs/loader:1081:32)\n      at Function.Module._load (node:internal/modules/cjs/loader:922:12)\n      at Module.require (node:internal/modules/cjs/loader:1105:19)\n      at require (node:internal/modules/cjs/helpers:103:18)\n      at Object.<anonymous> (node_modules\\@nomiclabs\\hardhat-ethers\\src\\internal\\provider-proxy.ts:7:1)\n      at Module._compile (node:internal/modules/cjs/loader:1218:14)\n```\n\n```text\nconst hello = await HelloWorld.deploy();\n```\n\n```text\ndescribe(\"hello world\", function()\n{\n    it(\"should say hello world\", async function () \n    {\n        const HelloWorld = await ethers.getContractFactory(\"HelloWorld\");\n        const helloWorldContract = await HelloWorld.deploy();\n        await helloWorldContract.deployed();\n\n        const hello = await helloWorldContract.hello();\n        expect(hello).to.be.equal(\"Hello, World\");\n       \n    });\n});\n```\n\n```text\nhello()\n```\n\n```text\nawait helloWorldContract.deployed();\n```\n\n```text\nnpm install @nomiclabs/hardhat-ethers@latest\n```\n\n```text\n^5.7.2\n```\n\n```text\n6.2.0\n```\n\n```text\nyarn\n```\n\n```text\n.json\n```\n\n```text\nnpm install ethers@^5.7.2\n```\n\n```text\n5.7.2\n```\n\n```text\n^\n```\n\n```text\n5.x.x\n```\n\n```text\n5.7.2\n```\n\n```text\n5.7.2\n```\n\n```text\nnpm i ethers@5.7.2\n```\n\n```text\nnpm install ethers@5.7.2\nconst provider = new thers.providers.JsonRpcProvider(\"http://127.0.0.1:7545\" );\n```\n\n```text\nconst { ethers, JsonRpcProvider } = require(\"ethers\");\nconst provider = new JsonRpcProvider(\"http://127.0.0.1:7545\")\n```\n\n```text\nyarn add ethers@5.5.0\n```\n\n```text\n6.x\n```\n\n========================================\n\nComments:\n- You didn't configure you're rpc provider properly, you need to setup hardhat with an infura node and a default user mneumonic or private key etc\n- Because I'm a newby on that here is what I installed, sidenote it's from an online course - theprimeagen.github.io/web3-smart-contracts ---> npm install --global yarn, yarn init -y, yarn add -D hardhat, npx hardhat ---> Typescript: yarn add -D ts-node typescript ---> Testing types: yarn add -D chai @types/node @types/mocha @types/chai --> npx hardhat compile -> works fine..., npx hardhat test -> described error... ---> Is the anything more I have to install?\n- Thx a lot it's working now, obviously it was a problem with yarn. A new installation completely with npm fixed the problems..","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":243,"estimatedTokens":1487}}165{"id":"stack-69302320","source":"stackoverflow","questionId":69302320,"title":"ERC721: transfer caller is not owner nor approved","tags":["javascript","solidity","smartcontracts","web3js","nft"],"text":"Title: ERC721: transfer caller is not owner nor approved\nTags: javascript, solidity, smartcontracts, web3js, nft\nSource: Stack Overflow\n\nQuestion:\nI have a nftToken Contract that mints token to msg.sender, then I have a function in a market contract that transfers the nft from owner to market contract. However, I am getting an error that says: ERC721: transfer caller is not owner nor approved.\n\nhere is my nftContract (nft) function snippet:\n\n```\nfunction createToken(string memory tokenURI) public returns (uint) {\n _tokenIds.increment();\n uint256 newItemId = _tokenIds.current();\n\n _mint(msg.sender, newItemId);\n _setTokenURI(newItemId, tokenURI);\n setApprovalForAll(contractAddress, true);\n return newItemId;\n}\n```\n\nhere is my market code (stripeMarket Contract) function snippet:\n\n```\nfunction createItem(\n address nftContract,\n uint256 tokenId\n ) public payable{\n address _owner = IERC721(nftContract).ownerOf(tokenId);\n IERC721(nftContract).transferFrom(_owner, address(this),tokenId);\n IERC721(nftContract).approve(address(this),tokenId); \n}\n```\n\nand here I am trying to call it from the frontend with web3:\n\n```\nconst getItems=async()=>{\n await contracts.nft.methods.createToken(\"https://i.ytimg.com/vi/nYxGhQYi0s4/maxresdefault.jpg\").send({from: accounts[0]});\n const owners = await contracts.nft.methods.ownerOf(1).call({from:accounts[0]});\n await contracts.stripeMarket.methods.createItem(contracts.nft._address,1).send({from: {owners}}); \n}\n```\n\nBut I am getting the error:\n\nERC721: transfer caller is not owner nor approved.\n\n========================================\n\nCode:\n```text\nfunction createToken(string memory tokenURI) public returns (uint) {\n  _tokenIds.increment();\n  uint256 newItemId = _tokenIds.current();\n\n  _mint(msg.sender, newItemId);\n  _setTokenURI(newItemId, tokenURI);\n  setApprovalForAll(contractAddress, true);\n  return newItemId;\n}\n```\n\n```text\nfunction createItem(\n    address nftContract,\n    uint256 tokenId\n    ) public payable{\n     address _owner = IERC721(nftContract).ownerOf(tokenId);\n     IERC721(nftContract).transferFrom(_owner, address(this),tokenId);\n      IERC721(nftContract).approve(address(this),tokenId);    \n}\n```\n\n```text\nconst getItems=async()=>{\n      await contracts.nft.methods.createToken(\"https://i.ytimg.com/vi/nYxGhQYi0s4/maxresdefault.jpg\").send({from: accounts[0]});\n      const owners = await contracts.nft.methods.ownerOf(1).call({from:accounts[0]});\n      await contracts.stripeMarket.methods.createItem(contracts.nft._address,1).send({from: {owners}}); \n}\n```\n\n```text\n// the owner is the `nftContract`\n_mint(address(this), newItemId);\n\n// the Market contract is allowed to operate the `nftContract`'s tokens\nsetApprovalForAll(contractAddress, true);\n```\n\n```text\nnftContract\n```\n\n```text\nsetApprovalForAll(contractAddress, true)\n```\n\n```text\ncontractAddress\n```\n\n```text\nnftContract\n```\n\n```text\nmsg.sender\n```\n\n```text\nnftContract\n```\n\n```text\nnftContract\n```\n\n```text\nmsg.sender\n```\n\n```text\nmsg.sender\n```\n\n```text\napprove(marketAddress, tokenId)\n```\n\n```text\nnftContract\n```\n\n```text\ncreateItem()\n```\n\n```text\nmsg.sender\n```\n\n```text\n_owner\n```\n\n========================================\n\nComments:\n- That's happening also for me. But in my use case, when I mint the token, I need to transfer it to the user, not the market place. Actually there isn't a marketplace. How can this be implemented?. Thanks!\n- @nacho It depends on your specific code setup, so I'd suggest posting a separate question with minimal reproducible example. But as a general answer - the `transferFrom()` function accepts the recipient as the second argument. So you might need to pass the user address as the second argument there.","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":151,"estimatedTokens":921}}166{"id":"stack-67371086","source":"stackoverflow","questionId":67371086,"title":"How is gas usage calculated when using if statements","tags":["ethereum","solidity"],"text":"Title: How is gas usage calculated when using if statements\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nLet's say I have a smart contract with branch, where each branch has a different number of operations.\n\n```\nif (someCondition) {\n // do operations costing 10 gas\n} else {\n //do operations costing 100 gas\n}\n```\n\nWhen a user goes to call this function from their client, say metamask, how do they know how much gas their transaction will cost? Do they just have to guess and include enough gas for the most expensive path?\n\n========================================\n\nTop Answer:\nYou can find all the values corresponding to the relative costs, in gas, of a number of abstract operations that a transaction may affect in the Ethereum yellow paper (page 27).\n\nThe \"if\" statment in a low level languaje, is consider a \"JUMP\" operation (alters de program counter). So in the gas cost table (page 27) says that a JUMPDEST operation cost 1 gas value.\n\nhttps://i.sstatic.net/xK2aR.png\nhttps://i.sstatic.net/N4PgS.png\n\n========================================\n\nCode:\n```text\nif (someCondition) {\n  // do operations costing 10 gas\n} else {\n  //do operations costing 100 gas\n}\n```\n\n```text\nif (block.timestamp % 2 == 0) {\n    // even second, do operations costing 10 gas\n} else {\n    // odd second, do operations costing 100 gas\n}\n```\n\n```text\nMLOAD\n```\n\n```text\nSSTORE\n```\n\n```text\nblock.timestamp\n```\n\n========================================\n\nComments:\n- Page 27 in the new version.","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":62,"estimatedTokens":373}}167{"id":"stack-42926772","source":"stackoverflow","questionId":42926772,"title":"What is the difference between creating a new solidity contract with and without the `new` keyword?","tags":["deployment","blockchain","ethereum","solidity","smartcontracts"],"text":"Title: What is the difference between creating a new solidity contract with and without the `new` keyword?\nTags: deployment, blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nWhat is the use of the `new` keyword for creating new smart contracts? Why not just omit this keyword?\n\n========================================\n\nTop Answer:\nThere are two ways you can create contracts \n\n- Using 'new' keyword\n\n- Using address of the contracts\n\nUsing new keyword you instantiate the new instance of the contract and use that newly created contract instance\n\nWhile in latter option you use the address of the already deployed and instantiated contract. You can check below code for reference:\n\n```\npragma solidity ^0.5.0;\n\ncontract Communication {\n\n string public user_message;\n\n function getMessage() public view returns (string memory) {\n return user_message;\n }\n\n function setMessage(string memory _message) public {\n user_message = _message;\n }\n}\n\ncontract GreetingsUsingNew {\n\n function sayHelloUsingNew() public returns (string memory) {\n Communication newObj = new Communication();\n newObj.setMessage(\"Contract created using New!!!\");\n\n return newObj.getMessage();\n }\n\n}\n\ncontract GreetingsUsingAddress {\n\n function sayHelloUsingAddress(address _addr) public returns (string memory) {\n Communication addObj = Communication(_addr);\n addObj.setMessage(\"Contract created using an Address!!!\");\n\n return addObj.getMessage();\n }\n}\n```\n\n========================================\n\nCode:\n```text\nnew\n```\n\n```text\nnew\n```\n\n```text\ntoken = new Token;\n```\n\n```text\ntoken\n```\n\n```text\ntoken = existingToken;\n```\n\n```text\nexistingToken\n```\n\n```text\ntoken\n```\n\n```text\nexistingToken\n```\n\n```text\npragma solidity ^0.5.0;\n\ncontract Communication {\n\n    string public user_message;\n\n    function getMessage() public view returns (string memory) {\n        return user_message;\n    }\n\n    function setMessage(string memory _message) public {\n        user_message = _message;\n    }\n}\n\ncontract GreetingsUsingNew {\n\n    function sayHelloUsingNew() public returns (string memory) {\n        Communication newObj = new Communication();\n        newObj.setMessage(\"Contract created using New!!!\");\n\n        return newObj.getMessage();\n    }\n\n}\n\ncontract GreetingsUsingAddress {\n\n    function sayHelloUsingAddress(address _addr) public returns (string memory) {\n        Communication addObj = Communication(_addr);\n        addObj.setMessage(\"Contract created using an Address!!!\");\n\n        return addObj.getMessage();\n    }\n}\n```\n\n```text\nNewContract myNewContract = (new NewContract){value: 1000000000000000000}()\n```\n\n```text\nnew\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":138,"estimatedTokens":659}}168{"id":"stack-68997666","source":"stackoverflow","questionId":68997666,"title":"What is bytes calldata _data?","tags":["solidity"],"text":"Title: What is bytes calldata _data?\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nWhat's the function and how is it used of `bytes calldata _data` in this contract function?\n\n```\n/**\n Mint a batch of tokens into existence and send them to the `_recipient`\n address. In order to mint an item, its item group must first have been\n created. Minting an item must obey both the fungibility and size cap of its\n group.\n\n @param _recipient The address to receive all NFTs within the newly-minted\n group.\n @param _ids The item IDs for the new items to create.\n @param _amounts The amount of each corresponding item ID to create.\n @param _data Any associated data to use on items minted in this transaction.\n */\n function mintBatch(address _recipient, uint256[] calldata _ids,\n uint256[] calldata _amounts, bytes calldata _data)\n external virtual {\n require(_recipient != address(0),\n \"ERC1155: mint to the zero address\");\n require(_ids.length == _amounts.length,\n \"ERC1155: ids and amounts length mismatch\");\n\n // Validate and perform the mint.\n address operator = _msgSender();\n _beforeTokenTransfer(operator, address(0), _recipient, _ids, _amounts,\n _data);\n\n // Loop through each of the batched IDs to update storage of special\n // balances and circulation balances.\n for (uint256 i = 0; i > 128;\n uint256 mintedItemId = _mintChecker(_ids[i], _amounts[i]);\n\n // Update storage of special balances and circulating values.\n balances[mintedItemId][_recipient] = balances[mintedItemId][_recipient]\n .add(_amounts[i]);\n groupBalances[groupId][_recipient] = groupBalances[groupId][_recipient]\n .add(_amounts[i]);\n totalBalances[_recipient] = totalBalances[_recipient].add(_amounts[i]);\n mintCount[mintedItemId] = mintCount[mintedItemId].add(_amounts[i]);\n circulatingSupply[mintedItemId] = circulatingSupply[mintedItemId]\n .add(_amounts[i]);\n itemGroups[groupId].mintCount = itemGroups[groupId].mintCount\n .add(_amounts[i]);\n itemGroups[groupId].circulatingSupply =\n itemGroups[groupId].circulatingSupply.add(_amounts[i]);\n }\n\n // Emit event and handle the safety check.\n emit TransferBatch(operator, address(0), _recipient, _ids, _amounts);\n _doSafeBatchTransferAcceptanceCheck(operator, address(0), _recipient, _ids,\n _amounts, _data);\n }\n```\n\n========================================\n\nCode:\n```text\n/**\n    Mint a batch of tokens into existence and send them to the `_recipient`\n    address. In order to mint an item, its item group must first have been\n    created. Minting an item must obey both the fungibility and size cap of its\n    group.\n\n    @param _recipient The address to receive all NFTs within the newly-minted\n      group.\n    @param _ids The item IDs for the new items to create.\n    @param _amounts The amount of each corresponding item ID to create.\n    @param _data Any associated data to use on items minted in this transaction.\n  */\n  function mintBatch(address _recipient, uint256[] calldata _ids,\n    uint256[] calldata _amounts, bytes calldata _data)\n    external virtual {\n    require(_recipient != address(0),\n      \"ERC1155: mint to the zero address\");\n    require(_ids.length == _amounts.length,\n      \"ERC1155: ids and amounts length mismatch\");\n\n    // Validate and perform the mint.\n    address operator = _msgSender();\n    _beforeTokenTransfer(operator, address(0), _recipient, _ids, _amounts,\n      _data);\n\n    // Loop through each of the batched IDs to update storage of special\n    // balances and circulation balances.\n    for (uint256 i = 0; i < _ids.length; i++) {\n      require(_hasItemRight(_ids[i], MINT),\n        \"Super1155: you do not have the right to mint that item\");\n\n      // Retrieve the group ID from the given item `_id` and check mint.\n      uint256 shiftedGroupId = (_ids[i] & GROUP_MASK);\n      uint256 groupId = shiftedGroupId >> 128;\n      uint256 mintedItemId = _mintChecker(_ids[i], _amounts[i]);\n\n      // Update storage of special balances and circulating values.\n      balances[mintedItemId][_recipient] = balances[mintedItemId][_recipient]\n        .add(_amounts[i]);\n      groupBalances[groupId][_recipient] = groupBalances[groupId][_recipient]\n        .add(_amounts[i]);\n      totalBalances[_recipient] = totalBalances[_recipient].add(_amounts[i]);\n      mintCount[mintedItemId] = mintCount[mintedItemId].add(_amounts[i]);\n      circulatingSupply[mintedItemId] = circulatingSupply[mintedItemId]\n        .add(_amounts[i]);\n      itemGroups[groupId].mintCount = itemGroups[groupId].mintCount\n        .add(_amounts[i]);\n      itemGroups[groupId].circulatingSupply =\n        itemGroups[groupId].circulatingSupply.add(_amounts[i]);\n    }\n\n    // Emit event and handle the safety check.\n    emit TransferBatch(operator, address(0), _recipient, _ids, _amounts);\n    _doSafeBatchTransferAcceptanceCheck(operator, address(0), _recipient, _ids,\n      _amounts, _data);\n  }\n```\n\n```text\nbytes calldata _data\n```\n\n```text\ncalldata\n```\n\n```text\nmemory\n```\n\n```text\ncalldata\n```\n\n```text\ncalldata\n```\n\n```text\nbytes\n```\n\n```text\ncalldata\n```\n\n```text\nmemory\n```\n\n```text\nmemory\n```\n\n```text\nstorage\n```\n\n```text\nmemory\n```\n\n```text\ncalldata\n```\n\n```text\ncalldata\n```\n\n```text\nbytes\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":177,"estimatedTokens":1283}}169{"id":"stack-65529667","source":"stackoverflow","questionId":65529667,"title":"Get Keys of Solidity mapping","tags":["blockchain","ethereum","solidity","smartcontracts"],"text":"Title: Get Keys of Solidity mapping\nTags: blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI was trying to get keys of a mapping to star name and address of particular contract (not exactly) in solidity contract\n\n```\nmapping(string=>address) nameOfAccounts;\n```\n\nWhat i am expecting is a method like the `Object.keys(nameOfAccounts)` in Javascript. Is there any similar method ?. or should i use an additional `array`. The additional Array may cause extra gas cost(This is not an option that i prefer). Please some insights\n\nI wanted to know if there is another method that i can do if getting keys is not an option?\n\n========================================\n\nTop Answer:\nShort answer: If the contract doesn't provide the list of map's object keys, you can't get it.\n\nLong answer:\n\nBut since the blockchain is a public thing , you can get anything.\nTo get all keys of the map, you would need to do this:\n\n- Setup archival node and enable tracing (you will need 9 terabytes disk, with SSD caching)\n\n- Get the traces of all the calls to your contract and search for `SSTORE` opcode (instruction)\n\n- The SSTORE instruction pops 2 parameters from the stack, `Loc` (location) and Val (Value) . The location is the key you are looking for.\n\nIf you don't have a budget for archival node, you can try Etherscan's API\n\nThere are answers on SO on how to read storage of a contract, might be useful.\n\nThere is another option, decompile the contract, and check its input, the input will have the key, then scan all transactions for that contract, and extract the keys by processing the input (the input is the tx.Data() field). This option is easier if you have the some knowledge about the contract, or if you have the sources, that's will be the easiest thing (process the Input)\n\nThere is also a function in StateDB object type called `ForEachStorage()`. It doesn't have a front-end from the RPC api, but with a little bit of effort you could implement your own RPC function to access it and put it on a Full node. This function accepts the address of the contract and a closure function , and it will iterate through the storage of the entire contract. Source: https://github.com/ethereum/go-ethereum/blob/0a3993c558616868e35f9730e92c704ac16ee437/core/state/statedb.go#L634\nThe only thing you would have to know is how the keys are built, and this can be only known from contract source.\n\n========================================\n\nCode:\n```text\nmapping(string=>address) nameOfAccounts;\n```\n\n```text\nObject.keys(nameOfAccounts)\n```\n\n```text\narray\n```\n\n```text\nSSTORE\n```\n\n```text\nLoc\n```\n\n```text\nForEachStorage()\n```\n\n```text\n// Import map uint256 => address\nimport \"goodmapping/contracts/Map_UA.sol\";\n\n// A mapping uint256 => address\nMap_UA private my_map; \n\n// insert some key-value pare\nmy_map.set(0x123,1);\nmy_map.set(0x234,2);\n\n// get all keys \naddress[] memory keys = my_map.keys();\n\n// iterate each key-value pare\nfor (uint256 index = 0; index < keys.length; index++)\n{\n  //get value \n  bool bExist = false;\n  uint256 value = 0;\n  (bExist, value) = my_map.get(keys[index]);\n}\n```\n\n========================================\n\nComments:\n- you have tagged several items, however it may relate to those topics. In addition, you need to elaborate your question as if a javascript programmer may don't know what is blockchain. I guess your question should be in javascript, you may pass your logic in the filter/map method in javascript!\n- I edited the question and removed JavaScript tag to protect the question\n- okay mikko, thanks\n- Why not just keep an array to track the keys? Only append if not in map?\n- 9 terabytes with ssd caching? you don't say.. let's all sell our livers to iterate over a mapping why don't we.. how about just doing mapping.keys() and then iterating over that?","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":99,"estimatedTokens":953}}170{"id":"stack-68785370","source":"stackoverflow","questionId":68785370,"title":"What is Context.sol uses for in Openzepplin","tags":["solidity","ether"],"text":"Title: What is Context.sol uses for in Openzepplin\nTags: solidity, ether\nSource: Stack Overflow\n\nQuestion:\nI'm new to solidity and trying to deploy a ERC20 token using openzepplin.There is one thing that doesn't make sense to me is the context.sol file.\nFrom the comment section it's seem like the main function of the context.sol is to implement a GSN compatible contract so instead of using msg.sender you use _msgSender()\n\n```\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n```\n\nFrom my limited experience with solidity it seem doing exactly the same thing with msg.sender.\n\n========================================\n\nCode:\n```text\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}\n```\n\n```text\nmsg.sender\n```\n\n```text\ntx.origin\n```\n\n```text\nmsg.sender\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":48,"estimatedTokens":277}}171{"id":"stack-70360131","source":"stackoverflow","questionId":70360131,"title":"Time manipulation in a hardhat test","tags":["solidity","hardhat"],"text":"Title: Time manipulation in a hardhat test\nTags: solidity, hardhat\nSource: Stack Overflow\n\nQuestion:\nSay I have a function in a Solidity smart contract that requires a certain period of time to pass before it will take some action for this example let's say one year and to properly implement a unit test for this function I need to wait one year now obviously that is impractical so my question is: Is there an easy way to manipulate the `block.timestamp` value inside of the hardhat development network?\n\n========================================\n\nCode:\n```text\nblock.timestamp\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.127Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":13,"estimatedTokens":146}}172{"id":"stack-76377136","source":"stackoverflow","questionId":76377136,"title":"\"Migrations\" hit an invalid opcode while deploying","tags":["javascript","ethereum","solidity","truffle","ganache"],"text":"Title: \"Migrations\" hit an invalid opcode while deploying\nTags: javascript, ethereum, solidity, truffle, ganache\nSource: Stack Overflow\n\nQuestion:\nI have suddenly started getting '\"Migrations\" hit an invalid opcode while deploying' error when I do 'truffle deploy' command.\n\nMy migrations file has not changed so I'm not sure why I am suddenly getting this error. Everyone who's posted for the same error just suggests downloading latest versions of ganache/truffle but I have updated my truffle and ganache to the most up to date versions and still getting the error.\n\nThis is the full error:\n⠋ Fetching solc version list from solc-bin. Attempt #1\nStarting migrations...\n\nNetwork name: 'development'\nNetwork id: 5777\nBlock gas limit: 6721975 (0x6691b7)\n\n### 1_initial_migration.js\n\n⠙ Fetching solc version list from solc-bin. Attempt #1\nDeploying 'Migrations'\n*** Deployment Failed ***st from solc-bin. Attempt #1\n\n\"Migrations\" hit an invalid opcode while deploying. Try:\n\n- Verifying that your constructor params satisfy all assert conditions.\n\n- Verifying your constructor code doesn't access an array out of bounds.\n\n- Adding reason strings to your assert statements.\n\nExiting: Review successful transactions manually by checking the transaction hashes above on Etherscan.\n\nError: *** Deployment Failed ***\n\n\"Migrations\" hit an invalid opcode while deploying. Try:\n\n- Verifying that your constructor params satisfy all assert conditions.\n\n- Verifying your constructor code doesn't access an array out of bounds.\n\n- Adding reason strings to your assert statements.\n\n```\nat /usr/local/lib/node_modules/truffle/build/webpack:/packages/deployer/src/deployment.js:330:1\n```\n\nTruffle v5.9.2 (core: 5.9.2)\nNode v18.7.0\n\nMigrations.sol\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\ncontract Migrations {\n address public owner;\n uint256 public lastCompletedMigration;\n\n constructor() {\n owner = msg.sender;\n }\n\n modifier restricted() {\n require(msg.sender == owner, \"Restricted to contract owner\");\n _;\n }\n\n function setCompleted(uint256 completed) public restricted {\n lastCompletedMigration = completed;\n }\n\n function upgrade(address new_address) public restricted {\n Migrations upgraded = Migrations(new_address);\n upgraded.setCompleted(lastCompletedMigration);\n }\n}\n```\n\n1_initial_migration.js\n\n```\nconst Migrations = artifacts.require(\"Migrations\");\n\nmodule.exports = function(deployer) {\n deployer.deploy(Migrations);\n};\n```\n\n========================================\n\nTop Answer:\nChange solc version in the `truffle-config.js` file as below.\n\n```\ncompilers: {\n solc: {\n version: \"0.8.13\"\n }\n }\n```\n\n========================================\n\nCode:\n```text\nat /usr/local/lib/node_modules/truffle/build/webpack:/packages/deployer/src/deployment.js:330:1\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\ncontract Migrations {\n    address public owner;\n    uint256 public lastCompletedMigration;\n\n    constructor() {\n        owner = msg.sender;\n    }\n\n    modifier restricted() {\n        require(msg.sender == owner, \"Restricted to contract owner\");\n        _;\n    }\n\n    function setCompleted(uint256 completed) public restricted {\n        lastCompletedMigration = completed;\n    }\n\n    function upgrade(address new_address) public restricted {\n        Migrations upgraded = Migrations(new_address);\n        upgraded.setCompleted(lastCompletedMigration);\n    }\n}\n```\n\n```text\nconst Migrations = artifacts.require(\"Migrations\");\n\nmodule.exports = function(deployer) {\n    deployer.deploy(Migrations);\n};\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity >=0.4.22 <0.9.0;\n```\n\n```text\ncompilers: {\n    solc: {\n      version: \"0.5.1\"\n}\n```\n\n```bash\ntruffle unbox metacoin [PATH/TO/DIRECTORY]\n```\n\n```text\ncompilers: {\n    solc: {\n      version: \"0.8.13\"\n    }\n  }\n```\n\n```text\ntruffle-config.js\n```\n\n```text\nnpm install -g ganche\n```\n\n========================================\n\nComments:\n- Hey there, I've just answered a very similar question over here ... looks like you've already resolved your issue, but there are the couple of other ways you can consider as well.\n- Yes that's solved the issue, thank you. my solc version was 0.8.20, weird that it just stopped working\n- Worked for me as well, but feels like a structurally wrong solution - rolling back to older version of compiler to make the deployment work. Also resulted in cascade of changes to satisfy older standards. Anyone managed to make it work with 0.8.20?\n- @IdoVanOrell same issue. I guess it's a stupid bug: seeing \"0.8.20\" as 0.8.2.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review\n- please expand. meta.stackexchange.com/a/8259/997587\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":189,"estimatedTokens":1329}}173{"id":"stack-74792390","source":"stackoverflow","questionId":74792390,"title":"how to hardcode bytes in solidity?","tags":["solidity","remix","hardhat"],"text":"Title: how to hardcode bytes in solidity?\nTags: solidity, remix, hardhat\nSource: Stack Overflow\n\nQuestion:\nHow can I hard code `bytes` in solidity for a static call?\n\nIve tried:\n\n`bytes memory data = \"0xfeaf968c\";`\n\n`bytes memory data = \\xfeaf968c\";`\n\nIt works when I manually enter it as an input parameter, while it fails for some reason when I externally call it when its hard coded in this format.\n\n========================================\n\nCode:\n```text\nbytes\n```\n\n```text\nbytes memory data = \"0xfeaf968c\";\n```\n\n```text\nbytes memory data = \\xfeaf968c\";\n```\n\n```text\nbytes memory data = hex\"feaf968c\";\n```\n\n```text\nbytes memory data = \"\\xfe\\xaf\\x96\\x8c\";\n```\n\n========================================\n\nComments:\n- using hex worked, although the second suggestion errored: `ParserError: Expected ']' but got ','`\n- `\"\\xfe\\xaf\\x96\\x8c\"` also seemed to work\n- updated second example, had to look how i did it in one project :D\n- now the second one is returning `0x0000000000000000000000000000000000000000000000000000000000&zwnj;&#8203;0000fe00000000000000&zwnj;&#8203;00000000000000000000&zwnj;&#8203;00000000000000000000&zwnj;&#8203;00000000af0000000000&zwnj;&#8203;00000000000000000000&zwnj;&#8203;00000000000000000000&zwnj;&#8203;00000000000096000000&zwnj;&#8203;00000000000000000000&zwnj;&#8203;00000000000000000000&zwnj;&#8203;00000000000000008c`\n- cause its dynamically-sized byte array, maybe stick to the first one\n- I edited the answer and added a solution. I feel we have a strong answer. Thank you so much for your help!","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":47,"estimatedTokens":383}}174{"id":"stack-76980638","source":"stackoverflow","questionId":76980638,"title":"How do you Associate/Dissociate an HTS token using EVM transaction?","tags":["solidity","hedera-hashgraph"],"text":"Title: How do you Associate/Dissociate an HTS token using EVM transaction?\nTags: solidity, hedera-hashgraph\nSource: Stack Overflow\n\nQuestion:\nBefore I can receive an HTS token I need to first associate with the token ID.\nIf I were using the JS SDK I know to do the following where the `accountId` is the account that I want to associate with the token.\n\n```\nconst associateTransaction = await new TokenAssociateTransaction()\n .setAccountId(accountId)\n .setTokenIds([tokenId])\n .freezeWith(client);\n```\n\nHowever, how do you Associate/Dissociate an HTS token using an EVM transaction?\n\nI’ve attempted to do the following in my smart contract\n\n```\nfunction mintNft(\n address token,\n bytes[] memory metadata\n ) public payable returns(int64){\n\n (int response, , int64[] memory serial) = HederaTokenService.mintToken(token, 0, metadata);\n if(response != HederaResponseCodes.SUCCESS){\n revert(\"Failed to mint non-fungible token\");\n }\n\n int res = HederaTokenService.associateToken(\n address(msg.sender),\n token\n );\n\n if(res != HederaResponseCodes.SUCCESS){\n revert(\"Failed to associate non-fungible token\");\n }\n \n return serial[0];\n }\n```\n\nHowever, when I try to transfer the contract reverts with the following error:\n\n```\nTOKEN_NOT_ASSOCIATED_TO_ACCOUNT\n```\n\nI’d like to be able to do so within a smart contract deployed to HSCS, preferably. If that is not possible, is there another way to do so?\n\n========================================\n\nCode:\n```text\nconst associateTransaction = await new TokenAssociateTransaction()\n    .setAccountId(accountId)\n    .setTokenIds([tokenId])\n    .freezeWith(client);\n```\n\n```text\nfunction mintNft(\n        address token,\n        bytes[] memory metadata\n    ) public payable returns(int64){\n\n        (int response, , int64[] memory serial) = HederaTokenService.mintToken(token, 0, metadata);\n        if(response != HederaResponseCodes.SUCCESS){\n            revert(\"Failed to mint non-fungible token\");\n        }\n\n        int res = HederaTokenService.associateToken(\n            address(msg.sender),\n            token\n        );\n\n        if(res != HederaResponseCodes.SUCCESS){\n            revert(\"Failed to associate non-fungible token\");\n        }\n        \n        return serial[0];\n    }\n```\n\n```text\nTOKEN_NOT_ASSOCIATED_TO_ACCOUNT\n```\n\n```text\naccountId\n```\n\n```text\nconst provider = new ethers.providers.Web3Provider(window.ethereum, \"any\");\nawait provider.send(\"eth_requestAccounts\", []);\nconst signer = provider.getSigner();\n```\n\n```text\nconst abi = [\"function associate()\"];\n```\n\n```text\nconst tokenSolidityAddress = '0x' + TokenId.fromString('0.0.572609').tokenSolidityAddress();\n```\n\n```text\n// create contract instance using token solidity address, abi, and signer\n  const contract = new ethers.Contract(tokenSolidityAddress, abi, signer);\n\n  try {\n    const transactionResult = await contract.associate();\n    return transactionResult.hash;\n  } catch (error) {\n    console.warn(error.message ? error.message : error);\n    return null;\n  }\n```\n\n```text\nasync function dissociateToken() {\n    // set up your ethers provider\n    const provider = new ethers.providers.Web3Provider(window.ethereum, \"any\");\n    // request access to the user's account\n    await provider.send(\"eth_requestAccounts\", []);\n    // get signer\n    const signer = provider.getSigner();\n    const abi = [\"function dissociate()\"];\n    const tokenSolidityAddress = '0x' + TokenId.fromString('0.0.572609').tokenSolidityAddress();\n    // create contract instance using token solidity address, abi, and signer\n    const contract = new ethers.Contract(tokenSolidityAddress, abi, signer);\n  \n    try {\n      const transactionResult = await contract.dissociate();\n      return transactionResult.hash;\n    } catch (error) {\n      console.warn(error.message ? error.message : error);\n      return null;\n    } \n};\n```\n\n```text\nassociateToken\n```\n\n```text\nHederaTokenService\n```\n\n```text\naddress(msg.sender)\n```\n\n```text\naddress(this)\n```\n\n```text\nabi\n```\n\n```text\nassociate\n```\n\n```text\ndissociate\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":170,"estimatedTokens":1001}}175{"id":"stack-71194882","source":"stackoverflow","questionId":71194882,"title":"Execution reverted during call: This transaction will likely revert. If you wish to broadcast, include `allow_revert:True`","tags":["transactions","solidity","revert","brownie"],"text":"Title: Execution reverted during call: This transaction will likely revert. If you wish to broadcast, include `allow_revert:True`\nTags: transactions, solidity, revert, brownie\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a transaction to create an NFT collectible and the transaction gets reverted with the message: Gas estimation failed: 'execution reverted'. This transaction will likely revert. If you wish to broadcast, you must set the gas limit manually.\nwhen I add the max gas limit it stills revert.\n\n========================================\n\nTop Answer:\nIf you have enough funds for gas, then probably there's issue with the function that you call. That function seems to fall so there's the gas estimation failed message as you see.\n\n========================================\n\nCode:\n```text\nsettings:\n  gas_limit: \"100000000000\"\n```\n\n```text\ncreating_tx = advanced_collectible.createCollectible({\"from\": account, \"gasPrice\": 100000000000000000})\n```\n\n```text\nreqeustRandomWord(...,{\"from\": account, \"gas_limit\": 3000000, \"allow_revert\": True}))\n```\n\n```text\nAccessing `TransactionReceipt.revert_msg` on a reverted transaction requires the `debug_traceTransaction` RPC endpoint, but the node client does not support it or has not made it available.\n```\n\n========================================\n\nComments:\n- Do you have enough funds for the gas?\n- Yes that's wasn't the issue in my case\n- @OmerS :), don't forget to marked the response as accepted answer :)","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":39,"estimatedTokens":369}}176{"id":"stack-70833745","source":"stackoverflow","questionId":70833745,"title":"The need to allocate memory for string","tags":["solidity"],"text":"Title: The need to allocate memory for string\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI'm learning Solidity and I'm stuck on *memory* vs *storage* vs *calldata*.\nI'm reading the documentation and found this:\n\nExplicit data location for all variables of struct, array or mapping types is now mandatory. This is also applied to function parameters and return variables\n\nYet with an example contract of:\n\n```\ncontract ExampleContract {\n string public myText = \"Hello, world!\";\n\n function getMyText() public view returns (string) {\n return myText;\n }\n}\n```\n\nI get an error telling me `Data location must be \"memory\" or \"calldata\" for return parameter in function, but none was given.`.\n\nWhy is there a requirement for strings to have explicitly defined data allocation (e.g. in function params or returns)?\n\n========================================\n\nTop Answer:\nThis is a little bit tricky because Strings are considered Array datatype in solidity and the data location needs to be specified when parsed, to either **memory** or **calldata**.\n\n========================================\n\nCode:\n```text\ncontract ExampleContract {\n  string public myText = \"Hello, world!\";\n\n  function getMyText() public view returns (string) {\n    return myText;\n  }\n}\n```\n\n```text\nData location must be \"memory\" or \"calldata\" for return parameter in function, but none was given.\n```\n\n```text\nbytes\n```\n\n```text\nstring\n```\n\n```text\nbytes\n```\n\n```text\nstring\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":63,"estimatedTokens":362}}177{"id":"stack-70905645","source":"stackoverflow","questionId":70905645,"title":"ParserError: Source file requires different compiler version (current compiler is 0.8.7+commit.e28d00a7.Emscripten.clang)","tags":["blockchain","solidity","chainlink"],"text":"Title: ParserError: Source file requires different compiler version (current compiler is 0.8.7+commit.e28d00a7.Emscripten.clang)\nTags: blockchain, solidity, chainlink\nSource: Stack Overflow\n\nQuestion:\nI was eventually trying to run this code in remix IDE, where I was running this using 0.6.6 version of Solidity and ran into this error. I've tried using some other versions like 0.8 and 0.6 as well.\n\n```\n// SPDX-License-Identifier: MIT\n\npragma solidity =0.8.7;\n\nimport \"@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol\";\n\ncontract myContract{\n using SafeMathChainlink for uint256;\n mapping(address => uint256) public payTo;\n\n function Payment() public payable {\n uint256 minimumUSD = 50 * 10 ** 18;\n require(getConversionRate(msg.value) >= minimumUSD, \"Doesn't satisfy the minimum condition\");\n payTo[msg.sender] += msg.value;\n }\n}\n```\n\n========================================\n\nTop Answer:\nNow we can use this line of code to include a range of version of solidity to use. I faced the similar issue and got fixed by doing this:\n\n```\npragma solidity >=0.4.22 <0.9.0;\n```\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: MIT\n\npragma solidity =0.8.7;\n\nimport \"@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol\";\n\ncontract myContract{\n    using SafeMathChainlink for uint256;\n    mapping(address => uint256) public payTo;\n\n    function Payment() public payable {\n        uint256 minimumUSD = 50 * 10 ** 18;\n        require(getConversionRate(msg.value) >= minimumUSD, \"Doesn't satisfy the minimum condition\");\n        payTo[msg.sender] += msg.value;\n    }\n}\n```\n\n```text\npragma solidity ^0.6.0;\n```\n\n```text\nimport\n```\n\n```text\nusing ... for\n```\n\n```text\npragma solidity >=0.4.22 <0.9.0;\n```\n\n```text\npragma solidity >=0.5.0 < 0.9.0\n```\n\n========================================\n\nComments:\n- There's literally no question here.\n- so it looks like this ``` compiler: solc: version: 0.8.0 ```\n- this should work assuming all the dependencies require the version in the brownie-config.yaml","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":83,"estimatedTokens":510}}178{"id":"stack-70829478","source":"stackoverflow","questionId":70829478,"title":"How to pass array of structs as argument on etherscan (tuple[])?","tags":["javascript","ethereum","solidity","etherscan"],"text":"Title: How to pass array of structs as argument on etherscan (tuple[])?\nTags: javascript, ethereum, solidity, etherscan\nSource: Stack Overflow\n\nQuestion:\nI'm trying to pass the format of array of structs as argument on smart contract write function on etherscan,\n\nThis is solidity example:\n\nInfo[] public info;\n\n```\nstruct Info { \n address userAddress;\n uint256 amount; \n bool active; \n}\n```\n\nhttps://i.sstatic.net/Ar3bi.png\nJavascript example:\n\n```\nconst data = [{0x0000, 10000000000, false},{0x11111, 20000000000, true}]\n```\n\nCan anyone convert this data example to tuple[] and provide it?\nThanks in advance\n\n========================================\n\nCode:\n```text\nstruct Info { \n    address userAddress;\n    uint256 amount;   \n    bool active; \n}\n```\n\n```text\nconst data = [{0x0000, 10000000000, false},{0x11111, 20000000000, true}]\n```\n\n```text\n[[\"0x0000\", \"10000000000\", false],[\"0x11111\", \"20000000000\", true]]\n```\n\n========================================\n\nComments:\n- I have a struct struct PricingOption { uint208 price; uint40 numberOfEntries; } I tried to pass params the same way as you wrote and it didn't work for me: invalid tuple value","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":52,"estimatedTokens":288}}179{"id":"stack-72818685","source":"stackoverflow","questionId":72818685,"title":"How to decode bytes calldata in a smart contract?","tags":["solidity","ethers.js","hardhat","rsk"],"text":"Title: How to decode bytes calldata in a smart contract?\nTags: solidity, ethers.js, hardhat, rsk\nSource: Stack Overflow\n\nQuestion:\nI have 2 interacting smart contracts which I am developing/testing in Hardhat and deploying to RSK. One of them is an ERC1363 payable token with `transferAndCall(address,uint256,bytes)` function, and the second one is a token receiver whose `buy(address,uint,uint,bytes3)` function call I need to encode off-chain and send to the token's `transferAndCall` function `bytes` parameter. The ERC1363 contract transfers tokens from sender's account to the receiver smart contract's account and then within the same transaction calls receiver's `onTransferReceived(address,address,uint256,bytes)`, where the last `bytes` parameter should be encoded `buy` function call.\n\nThis is my receiver smart contract:\n\n```\ncontract TokenReceiver is IERC1363Receiver {\n IERC1363 acceptedToken;\n \n constructor(IERC1363 _acceptedToken) {\n acceptedToken = _acceptedToken;\n }\n event PurchaseMade(address indexed sender, uint tokensPaid, uint productAmount, bytes3 color);\n \n function buy(address sender, uint tokensPaid, uint productAmount, bytes3 color) public {\n // allowed to be called only via the accepted token\n require(msg.sender == address(acceptedToken), \"I accept purchases in Payable Tokens\");\n emit PurchaseMade(sender, tokensPaid, productAmount, color);\n }\n\n function onTransferReceived(address operator, address sender, uint256 tokensPaid, bytes calldata data) external override (IERC1363Receiver) returns (bytes4) {\n // TODO: decode calldata and call `buy` function\n return this.onTransferReceived.selector;\n }\n}\n```\n\nThis is how I assemble the calldata by encoding the signature and params of the `buy` function together:\n\n```\nit('buyer should be able to pay tokens and buy products in one transaction', async () => {\n // TokenReceiver `buy` function signature hash: 0x85f16ff4\n const buySigHash = tokenReceiver.interface.getSighash('buy');\n // providing some product properties to the TokenReceiver\n const productAmount = 99;\n const color = '0x121212';\n // packing `buy` signature and the properties together\n const calldata = ethers.utils.defaultAbiCoder.encode(\n ['bytes4', 'uint256', 'bytes3'],\n [buySigHash, productAmount, color],\n );\n // pay tokens and buy some products in one tx\n const transferAndCallTx = payableToken\n .connect(buyer)\n ['transferAndCall(address,uint256,bytes)'](tokenReceiver.address, tokenAmount, calldata);\n await expect(transferAndCallTx)\n .to.emit(tokenReceiver, 'PurchaseMade');\n });\n```\n\nMy question is:\n\n- How do I decode the calldata inside the receiver's `onTransferReceived` function?\n\n- How do I extract the function signature and the other 2 encoded params, and then call the corresponding function on the receiver?\n\n========================================\n\nTop Answer:\nYou could make use of inline assembly to decode your bytes data. Create a `pure` helper function with the following contents:\n​\n\n```\nfunction decode(bytes memory data) private pure returns(bytes4 selector, uint productAmount, bytes3 color) {\n assembly {\n // load 32 bytes into `selector` from `data` skipping the first 32 bytes\n selector := mload(add(data, 32))\n productAmount := mload(add(data, 64))\n color := mload(add(data, 96))\n }\n}\n```\n\n​\nhere `mload(0xAB)` loads a word (32 bytes) located at the memory address 0xAB, and `add(0xAB, 0xCD)` summs two values\n​\nSee this article for more on inline assembly in solidity.\n​\nNext, this is how you can utilise the created function in you contract:\n​\n\n```\n(bytes4 selector, uint productAmount, bytes3 color) =\n decode(data);\n```\n\n​\nSince you have the selector and other parameters, you can construct the function call data\n​\n\n```\nbytes memory funcData =\n abi.encodeWithSelector(selector, sender, tokensPaid, productAmount, color);\n```\n\n​\nNow you can make a low level call to invoke the corresponding function\n​\n\n```\n(bool success,) = address(this).call(funcData);\nrequire(success, \"call failed\");\n```\n\n​\n**Warning**:\nKeep in mind that using the above method\nallows an attacker to be able to call **any function** in your contract.\nBe careful using low level calls.\n​\nTo avoid this, validate the function selector,\nbefore calling it, like this:\n​\n\n```\nif (selector == this.buy.selector) {\n buy(sender, tokensPaid, productAmount, color);\n}\n```\n\n​\nThus, your `onTransferReceived` function may look something like this:\n​\n\n```\nfunction onTransferReceived(address operator, address sender, uint256 tokensPaid, bytes calldata data) external override (IERC1363Receiver) returns (bytes4) {\n require(msg.sender == address(acceptedToken), \"I accept purchases in Payable Tokens\");\n​\n (bytes4 selector, uint productAmount, bytes3 color) =\n decode(data);\n​\n if (selector == this.buy.selector) {\n buy(sender, tokensPaid, productAmount, color);\n }\n​\n return this.onTransferReceived.selector;\n }\n```\n\n========================================\n\nCode:\n```text\ncontract TokenReceiver is IERC1363Receiver {\n  IERC1363 acceptedToken;\n    \n  constructor(IERC1363 _acceptedToken) {\n    acceptedToken = _acceptedToken;\n  }\n  event PurchaseMade(address indexed sender, uint tokensPaid, uint productAmount, bytes3 color);\n    \n  function buy(address sender, uint tokensPaid, uint productAmount, bytes3 color) public {\n    // allowed to be called only via the accepted token\n    require(msg.sender == address(acceptedToken), \"I accept purchases in Payable Tokens\");\n    emit PurchaseMade(sender, tokensPaid, productAmount, color);\n  }\n\n  function onTransferReceived(address operator, address sender, uint256 tokensPaid, bytes calldata data) external override (IERC1363Receiver) returns (bytes4) {\n      // TODO: decode calldata and call `buy` function\n    return this.onTransferReceived.selector;\n  }\n}\n```\n\n```js\nit('buyer should be able to pay tokens and buy products in one transaction', async () => {\n    // TokenReceiver `buy` function signature hash: 0x85f16ff4\n    const buySigHash = tokenReceiver.interface.getSighash('buy');\n    // providing some product properties to the TokenReceiver\n    const productAmount = 99;\n    const color = '0x121212';\n    // packing `buy` signature and the properties together\n    const calldata = ethers.utils.defaultAbiCoder.encode(\n      ['bytes4', 'uint256', 'bytes3'],\n      [buySigHash, productAmount, color],\n    );\n    // pay tokens and buy some products in one tx\n    const transferAndCallTx = payableToken\n      .connect(buyer)\n      ['transferAndCall(address,uint256,bytes)'](tokenReceiver.address, tokenAmount, calldata);\n    await expect(transferAndCallTx)\n      .to.emit(tokenReceiver, 'PurchaseMade');\n  });\n```\n\n```text\ntransferAndCall(address,uint256,bytes)\n```\n\n```text\nbuy(address,uint,uint,bytes3)\n```\n\n```text\ntransferAndCall\n```\n\n```text\nbytes\n```\n\n```text\nonTransferReceived(address,address,uint256,bytes)\n```\n\n```text\nbytes\n```\n\n```text\nbuy\n```\n\n```text\nbuy\n```\n\n```text\nonTransferReceived\n```\n\n```js\n//Define struct within the contract, but outside the function\nstruct BuyParams {\n        bytes4 buySigHash;\n        uint256 productAmount;\n        bytes3 color;\n}\n\n// within onTransferReceived: decode the calldata:\nBuyParams memory decoded = abi.decode(\n    data,\n    (BuyParams)\n);\n\n\n//Now use as function arguments by passing:\ndecoded.buySigHash,\ndecoded.productAmount,\ndecoded.color,\n```\n\n```text\nfrom:\n        bytes4 buySigHash;\n        uint256 productAmount;\n        bytes3 color;\nto:\n        uint256 productAmount;\n        bytes4 buySigHash;\n        bytes3 color;\n```\n\n```text\nfunction decode(bytes memory data) private pure returns(bytes4 selector, uint productAmount, bytes3 color) {\n    assembly {\n      // load 32 bytes into `selector` from `data` skipping the first 32 bytes\n      selector := mload(add(data, 32))\n      productAmount := mload(add(data, 64))\n      color := mload(add(data, 96))\n    }\n}\n```\n\n```text\n(bytes4 selector, uint productAmount, bytes3 color) =\n  decode(data);\n```\n\n```text\nbytes memory funcData =\n  abi.encodeWithSelector(selector, sender, tokensPaid, productAmount, color);\n```\n\n```text\n(bool success,) = address(this).call(funcData);\nrequire(success, \"call failed\");\n```\n\n```text\nif (selector == this.buy.selector) {\n    buy(sender, tokensPaid, productAmount, color);\n}\n```\n\n```text\nfunction onTransferReceived(address operator, address sender, uint256 tokensPaid, bytes calldata data) external override (IERC1363Receiver) returns (bytes4) {\n    require(msg.sender == address(acceptedToken), \"I accept purchases in Payable Tokens\");\n​\n    (bytes4 selector, uint productAmount, bytes3 color) =\n        decode(data);\n​\n    if (selector == this.buy.selector) {\n      buy(sender, tokensPaid, productAmount, color);\n    }\n​\n    return this.onTransferReceived.selector;\n  }\n```\n\n```text\npure\n```\n\n```text\nmload(0xAB)\n```\n\n```text\nadd(0xAB, 0xCD)\n```\n\n```text\nonTransferReceived\n```\n\n========================================\n\nComments:\n- Thanks, brilliant idea! Let's say, now I have a function signature and the params. How can I then call a function with a dynamic name (decoded signature)? Is it possible to do smth like `buySigHash(productAmount, color, ...);` ?\n- try: `this.call(buySigHash, productAmount, color, ...)`\n- sorry made a small mistake, did you try `address(this).call()`?","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":326,"estimatedTokens":2310}}180{"id":"stack-67118358","source":"stackoverflow","questionId":67118358,"title":"Solidity function implementing `public onlyOwner` cannot be called even by the owner","tags":["ethereum","solidity","ether"],"text":"Title: Solidity function implementing `public onlyOwner` cannot be called even by the owner\nTags: ethereum, solidity, ether\nSource: Stack Overflow\n\nQuestion:\nI am following along the documentation here: https://docs.alchemyapi.io/alchemy/tutorials/how-to-create-an-nft/how-to-mint-a-nft. And have a smart contract of form:\n\n```\npragma solidity ^0.8.0;\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/utils/Counters.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\n contract NFTA is ERC721, Ownable {\n\n using Counters for Counters.Counter;\n Counters.Counter public _tokenIds;\n mapping (uint256 => string) public _tokenURIs;\n mapping(string => uint8) public hashes;\n\n constructor() public ERC721(\"NFTA\", \"NFT\") {}\n\n function mintNFT(address recipient, string memory tokenURI)\n public onlyOwner\n returns (uint256)\n {\n _tokenIds.increment();\n\n uint256 newItemId = _tokenIds.current();\n _mint(recipient, newItemId);\n _setTokenURI(newItemId, tokenURI);\n\n return newItemId;\n }\n\n /**\n * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {\n require(_exists(tokenId), \"ERC721URIStorage: URI set of nonexistent token\");\n _tokenURIs[tokenId] = _tokenURI;\n } \n\n }\n```\n\nWhen I attempt to estimate the gas cost of `minting` with this:\n\n```\nconst MY_PUBLIC_KEY = '..'\n const MY_PRIVATE_KEY = '..'\n\n const ALCHEMY = {\n http: '',\n websocket:'',\n }\n\n const { createAlchemyWeb3 } = require(\"@alch/alchemy-web3\");\n const web3 = createAlchemyWeb3(ALCHEMY.http);\n\n const NFTA = require(\"../artifacts/contracts/OpenSea.sol/NFTA.json\");\n const address_a = '0x...';\n const nft_A = new web3.eth.Contract(NFTA.abi, address_a);\n\n async function mint({ tokenURI, run }){\n\n const nonce = await web3.eth.getTransactionCount(MY_PUBLIC_KEY, 'latest'); \n const fn = nft_A.methods.mintNFT(MY_PUBLIC_KEY, '')\n\n console.log( 'fn: ', fn.estimateGas() )\n }\n\n mint({ tokenURI: '', run: true })\n```\n\nI receive error:\n\n```\n(node:29262) UnhandledPromiseRejectionWarning: Error: Returned error: execution reverted: Ownable: caller is not the owner\n```\n\nPresumably because `mintNFT` is `public onlyOwner`. However, when I check Etherscan, the `From` field is the same as `MY_PUBLIC_KEY`, and I'm not sure what else can be done to sign the transaction as from `MY_PUBLIC_KEY`. The easy way to solve this is to remove the `onlyOwner` from `function mintNFT`, and everything runs as expected. But suppose we want to keep `onlyOwner`, how would I sign the transaction beyond what is already written above.\n\nNote I'm using `hardHat` to compile the contracts and deploying them. That is:\nnpx hardhat compile\nnpx hardhat run scripts/deploy.js\n\n=============================================\n\naddendum\n\nThe exact code given by alchemy to deploy the mint is:\n\n```\nasync function mintNFT(tokenURI) {\n const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce\n\n //the transaction\n const tx = {\n 'from': PUBLIC_KEY,\n 'to': contractAddress,\n 'nonce': nonce,\n 'gas': 500000,\n 'data': nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI()\n };\n```\n\nNote in the transaction the `from` field is `PUBLIC_KEY`, the same `PUBLIC_KEY` that deployed the contract, and in this case the `nftContract` has `public onlyOwner` specified. This is exactly what I have done. So conceptually who owns this NFT code? On etherscan is it the `to` address ( the contract address ), or the `from` address, which is my public key, the address that deployed the contract, and the one that is calling mint, which is now failing with caller is not the owner error. https://i.sstatic.net/GbbrU.png\n\nSearch the internet, I see others have encountered this problem here: https://ethereum.stackexchange.com/questions/94114/erc721-testing-transferfrom, for `Truffle` you can specify the caller with extra field:\n\n```\nawait nft.transferFrom(accounts[0], accounts[1], 1, { from: accounts[1] })\n```\n\nExtra parameters is not an option here because I'm using hardhat.\n\n========================================\n\nTop Answer:\nOpenZeppelin's Ownable.sol defines the default `owner` value as the contract deployer. You can later change it by calling `transferOwnership()` or renounce the owner (i.e. set to `0x0`) by calling `renounceOwnership()`.\n\n**The `onlyOwner` modifier reverts the transaction if it's not sent by the current `owner`.** (see the code)\n\nSo you need to call the `mintNFT()` function from the same address that deployed the contract, because that's the current `owner`. Or you can change the `owner` first by calling `transferOwnership()` (from the current `owner` address).\n\nRemoving the `onlyOwner` modifier from the `mintNFT()` function would allow **anyone** to call the function.\n\n========================================\n\nCode:\n```text\npragma solidity ^0.8.0;\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/utils/Counters.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\n  contract NFTA is ERC721, Ownable {\n\n     using Counters for Counters.Counter;\n     Counters.Counter public _tokenIds;\n     mapping (uint256 => string) public _tokenURIs;\n     mapping(string => uint8) public hashes;\n\n     constructor() public ERC721(\"NFTA\", \"NFT\") {}\n\n     function mintNFT(address recipient, string memory tokenURI)\n          public onlyOwner\n          returns (uint256)\n      {\n          _tokenIds.increment();\n\n          uint256 newItemId = _tokenIds.current();\n          _mint(recipient, newItemId);\n          _setTokenURI(newItemId, tokenURI);\n\n          return newItemId;\n     }\n\n     /**\n      * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.\n      *\n      * Requirements:\n      *\n      * - `tokenId` must exist.\n      */\n     function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {\n        require(_exists(tokenId), \"ERC721URIStorage: URI set of nonexistent token\");\n        _tokenURIs[tokenId] = _tokenURI;\n     }    \n\n  }\n```\n\n```text\nconst MY_PUBLIC_KEY  = '..'\n    const MY_PRIVATE_KEY = '..'\n\n    const ALCHEMY = {\n        http: '',\n        websocket:'',\n    }\n\n    const { createAlchemyWeb3 } = require(\"@alch/alchemy-web3\");\n    const web3 = createAlchemyWeb3(ALCHEMY.http);\n\n    const NFTA = require(\"../artifacts/contracts/OpenSea.sol/NFTA.json\");\n    const address_a   = '0x...';\n    const nft_A = new web3.eth.Contract(NFTA.abi, address_a);\n\n\n    async function mint({ tokenURI, run }){\n\n        const nonce = await web3.eth.getTransactionCount(MY_PUBLIC_KEY, 'latest'); \n        const fn  = nft_A.methods.mintNFT(MY_PUBLIC_KEY, '')\n\n        console.log( 'fn: ', fn.estimateGas() )\n    }\n\n    mint({ tokenURI: '', run: true })\n```\n\n```text\n(node:29262) UnhandledPromiseRejectionWarning: Error: Returned error: execution reverted: Ownable: caller is not the owner\n```\n\n```text\nasync function mintNFT(tokenURI) {\n  const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce\n\n  //the transaction\n  const tx = {\n    'from': PUBLIC_KEY,\n    'to': contractAddress,\n    'nonce': nonce,\n    'gas': 500000,\n    'data': nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI()\n  };\n```\n\n```text\nawait nft.transferFrom(accounts[0], accounts[1], 1, { from: accounts[1] })\n```\n\n```text\nminting\n```\n\n```text\nmintNFT\n```\n\n```text\npublic onlyOwner\n```\n\n```text\nFrom\n```\n\n```text\nMY_PUBLIC_KEY\n```\n\n```text\nMY_PUBLIC_KEY\n```\n\n```text\nonlyOwner\n```\n\n```text\nfunction mintNFT\n```\n\n```text\nonlyOwner\n```\n\n```text\nhardHat\n```\n\n```text\nfrom\n```\n\n```text\nPUBLIC_KEY\n```\n\n```text\nPUBLIC_KEY\n```\n\n```text\nnftContract\n```\n\n```text\npublic onlyOwner\n```\n\n```text\nto\n```\n\n```text\nfrom\n```\n\n```text\nTruffle\n```\n\n```text\nowner\n```\n\n```text\ntransferOwnership()\n```\n\n```text\n0x0\n```\n\n```text\nrenounceOwnership()\n```\n\n```text\nonlyOwner\n```\n\n```text\nowner\n```\n\n```text\nmintNFT()\n```\n\n```text\nowner\n```\n\n```text\nowner\n```\n\n```text\ntransferOwnership()\n```\n\n```text\nowner\n```\n\n```text\nonlyOwner\n```\n\n```text\nmintNFT()\n```\n\n```text\nconst contract = require(\"../artifacts/contracts/MyNFT.sol/MyNFT.json\");\nconst contractAddress = \"0x81c587EB0fE773404c42c1d2666b5f557C470eED\";\nconst nftContract = new web3.eth.Contract(contract.abi, contractAddress);\n```\n\n```text\nconst nftContract = new web3.eth.Contract(contract.abi, contractAddress, {\n    from: PUBLIC_KEY\n});\n```\n\n========================================\n\nComments:\n- I guess your need to pass the test account sender address when you call `methods.mintNFT`.\n- @MikkoOhtamaa how would i do that? And is the test account sender address the same as my metamask wallet public key?\n- this is the question, I only have one public key going around, shouldn't that be the address that deployed the contract?\n- And when I call `transferOwnership` I'm getting the same error: ` Error: Returned error: execution reverted: Ownable: caller is not the owner`, stating that I'm not calling the fn from the address that deployed it. But again I only have one wallet and one pk, so Im not sure what else i can do. Mikko above suggest I call`mintNFT` and presumably `transferOwner` using test account sender address, what is the syntax here? And conceptually on Etherscan I see a `to` and `from` field for the contract, is the owner the `to` field or the `from` field?\n- @xiaolingxiao (1/2) From your screenshot, I can see that the contract 0xa26c... was deployed by address `0xd2590...`, effectively making this address the `owner`. And that this address was able to execute the `mintNFT()` function.\n- (2/2) It seems like the value of your `MY_PUBLIC_KEY` is other than `0xd2590...` - which gets the tx reverted, only the `owner` can execute it. Also pay attention to the value of `MY_PUBLIC_KEY` which might be different from the `PUBLIC_KEY` in your second snippet. But I'm not able to verify it, because your question doesn't show the values.\n- The reason the contract was able to mint was because I removed the onlyOwner bit in the one that i deployed, i was trying to verify that it runs w/o the ownership constraint. And yeah I only have one pk that's 0xd2590.... The second snippet is a direct past from the docs, in my code PUBLIC_KEY is MY_PUBLIC_KEY. This is why it's so infuriatingly fraustrating, I only have one pk private key pair, and that's what I use to deploy the contract and sign transactions. @PetrHejda\n- Just to confirm, I redployed with `onlyOwner` set here: ropsten.etherscan.io/tx/&hellip;, and mintNFT fails with: `Error: Returned error: execution reverted: Ownable: caller is not the owner` as expected\n- \"I removed the onlyOwner\", I didn't notice that - my bad... But right now, I'm out of ideas. Hopefully someone will be able to help you better.\n- I'm still not clear on the concept of `onlyOwner`, if your public key is public, then can't anyone call the fn with your pk provided they have it? it doesn't exactly make `onlyOwner` secure.\n- They would have to sign the transaction with the private key that pairs with the `owner` public key.\n- Thank you so much! You can also add `from: PUBLIC_KEY` directly to the data passed into `estimateGas()`: `const estimatedGas = await web3.eth.estimateGas({ from: PUBLIC_KEY, to: contractAddress, ...})`.","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":379,"estimatedTokens":2816}}181{"id":"stack-52139936","source":"stackoverflow","questionId":52139936,"title":"Why we can't send ether to ethereum address 0x1 via smart contracts","tags":["blockchain","ethereum","solidity","smartcontracts","ether"],"text":"Title: Why we can't send ether to ethereum address 0x1 via smart contracts\nTags: blockchain, ethereum, solidity, smartcontracts, ether\nSource: Stack Overflow\n\nQuestion:\nWith this below solidity code I have tried to send ether to ethereum wallet address **0x1** via smart contract and it becomes failed. But, when I try to send ether to address **0x1** directly from my wallet it becomes success.\n\n```\npragma solidity ^0.4.24;\n\ncontract Transfer {\n\n constructor () public payable {\n // Deploy contract with 1000 wei for testing purpose\n require(msg.value == 1000);\n }\n\n function done() public {\n address(0).transfer(1); // Transaction success\n }\n\n function fail() public {\n address(1).transfer(1); // Transaction failed\n }\n\n function send(address account) public {\n account.transfer(1); // Transaction success (except 0x1)\n }\n\n}\n```\n\n Why we can't send ether to address **0x1** via contracts ?\n\n**REFERENCE:**\n\nSending ether directly from my wallet is success\nhttps://ropsten.etherscan.io/tx/0x1fdc3a9d03e23b0838c23b00ff99739b775bf4dd7b5b7f2fa38043056f731cdc\n\ndone() function is success\nhttps://ropsten.etherscan.io/tx/0xd319c40fcf50bd8188ae039ce9d41830ab795e0f92d611b16efde0bfa1ee82cd\n\nfail() function is failed\nhttps://ropsten.etherscan.io/tx/0x0c98eafa0e608cfa66777f1c77267ce9bdf81c6476bdefe2a7615158d17b59ad\n\n### UPDATE:\n\nAfter researching about ethereum **pre-compiled contracts** I have written this below solidity code to send ether to **0x1** address via smart contract and it's working.\n\n```\npragma solidity ^0.4.24;\n\ncontract Learning {\n\n constructor () public payable {\n // Deploy contract with 1000 wei for testing purpose\n require(msg.value == 1000);\n }\n\n function test() public returns (bool) {\n // Set minimum gas limit as 700 to send ether to 0x1\n transfer(0x0000000000000000000000000000000000000001, 1, 700);\n return true;\n }\n\n function transfer(address _account, uint _wei, uint _gas) private {\n require(_account.call.value(_wei).gas(_gas)());\n }\n}\n```\n\nFor testing, just deploy contract with **1000 wei** and execute `test()` function. It's working :)\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.24;\n\ncontract Transfer {\n\n    constructor () public payable {\n        // Deploy contract with 1000 wei for testing purpose\n        require(msg.value == 1000);\n    }\n\n    function done() public {\n        address(0).transfer(1); // Transaction success\n    }\n\n    function fail() public {\n        address(1).transfer(1); // Transaction failed\n    }\n\n    function send(address account) public {\n        account.transfer(1); // Transaction success (except 0x1)\n    }\n\n}\n```\n\n```text\npragma solidity ^0.4.24;\n\ncontract Learning {\n\n    constructor () public payable {\n        // Deploy contract with 1000 wei for testing purpose\n        require(msg.value == 1000);\n    }\n\n    function test() public returns (bool) {\n        // Set minimum gas limit as 700 to send ether to 0x1\n        transfer(0x0000000000000000000000000000000000000001, 1, 700);\n        return true;\n    }\n\n    function transfer(address _account, uint _wei, uint _gas) private {\n        require(_account.call.value(_wei).gas(_gas)());\n    }\n}\n```\n\n```text\ntest()\n```\n\n```text\n0x0000000000000000000000000000000000000001\n```\n\n```text\necrecover\n```\n\n```text\nfail()\n```\n\n```text\necrecover\n```\n\n```text\n2300 gas\n```\n\n```text\ntransfer\n```\n\n```text\n0x0\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":154,"estimatedTokens":840}}182{"id":"stack-67385322","source":"stackoverflow","questionId":67385322,"title":"definition of base has to precede definition of derived contract","tags":["inheritance","ethereum","solidity","smartcontracts","contract"],"text":"Title: definition of base has to precede definition of derived contract\nTags: inheritance, ethereum, solidity, smartcontracts, contract\nSource: Stack Overflow\n\nQuestion:\nI have two different files which are Project1.sol and Project2.sol\n\nProject2.sol is like:\n\n```\nimport \"./Project1.sol\";\n \ncontract Project2{\n address newProject1Address =address(new Project1());\n}\n```\n\nProject1.sol is like:\n\n```\nimport \"./Project2.sol\";\n\ncontract Project1 is Project2{\n\n}\n```\n\nI have deployed Project1 inside of Project2.sol file. And also I have been using a struct which is in Project2 from Project1.sol file.\n\nI got an error which is \"**definition of base has to precede definition of derived contract.**\" for this line: `contract Project1 is Project2{`\n\nAfter I checked the error on the internet, there were solutions for two contracts and one file. However, I had two files.\n\nI merged these two contracts in a file.\n\nThis is what I did:\n\n```\npragma solidity >=0.7.0 bool) applepie;\n }\n\n function createProject() external{\n \n address newProject1Address =address(new Project1(msg.sender));\n\n uint idx = applepies.length;\n applepies.push();\n Apple storage newProject = applepies[idx];\n }\n\n \n\n }\n\ncontract Project1 is Project2{\n address public creator;\n\n constructor (address creator1){\n \n creator= creator1;\n }\n\n function getDetails(uint index) public{\n Apple storage newv= applepies[index];\n //require(newv.applepie = msg.sender);\n }\n}\n```\n\nThen, I could not deploy Project1 from Project2. When I do that, this is the error which I got, \"**circular reference for contract creation(cannot create instance of derived or same contract)**\" on this part `address newProject1Address =address(new Project1());`\n\nWhat should I do? What is your suggestions?\n\n========================================\n\nCode:\n```text\nimport \"./Project1.sol\";\n        \ncontract Project2{\n    address newProject1Address =address(new Project1());\n}\n```\n\n```text\nimport \"./Project2.sol\";\n\ncontract Project1 is Project2{\n\n}\n```\n\n```text\npragma solidity >=0.7.0 <0.9.0;\n\ncontract Project2{\n\n        Apple[] public applepies;\n        \n        struct Apple{\n             string name;\n             mapping (address => bool) applepie;\n        }\n\n        function createProject() external{\n            \n             address newProject1Address =address(new Project1(msg.sender));\n\n             uint idx = applepies.length;\n             applepies.push();\n             Apple storage newProject = applepies[idx];\n        }\n\n        \n\n    }\n\n\ncontract Project1 is Project2{\n        address public creator;\n\n        constructor (address creator1){\n            \n             creator= creator1;\n        }\n\n        function getDetails(uint index) public{\n             Apple storage newv= applepies[index];\n             //require(newv.applepie = msg.sender);\n        }\n}\n```\n\n```text\ncontract Project1 is Project2{\n```\n\n```text\naddress newProject1Address =address(new Project1());\n```\n\n```text\n// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.7.0 <0.9.0;\npragma experimental ABIEncoderV2;\n\ncontract Project2{\n\n       \n        \n        struct Apple{\n             string name;\n             bool applepie;\n             //mapping (address => bool) applepie;\n        }\n        \n        Apple[] public applepies;\n        Apple public newProject;\n        \n        constructor() {\n            \n             //address newProject1Address = address(new Project1(msg.sender));\n\n             //uint idx = applepies.length;\n             newProject = Apple(\"superApple\", true);\n             applepies.push(newProject);\n        }\n\n         function getNewProject() public view returns(string memory){\n             return newProject.name;\n        }\n\n    }\n\n\ncontract Project1 is Project2{\n        address public creator;\n\n        constructor (address creator1){\n            \n             creator= creator1;\n        }\n\n        function getDetails(uint index) public view returns (string memory){\n             Apple storage newv= applepies[index];\n             //require(newv.applepie = msg.sender);\n             return newv.name;\n        }\n}\n```\n\n========================================\n\nComments:\n- Can you clarify what you mean by \"I have deployed Project1 inside of Project2.sol file\"? ... It doesn't make much sense: 1) A contract is deployed to a network, not to a file. 2) The error message and \"Project1 inside of Project2.sol\" suggest that you have both contracts defined in one file, but your code examples explicitly define two files - \"Project1.sol\" and \"Project2.sol\".\n- @PetrHejda 1) I fixed the part of what I was trying to say on the post 2) And added the parts which you said. Could you check it again? I hope it is more clear right now. Sorry for my english.\n- Few more things: 1) What version of Solidity are you using? 2) `function createProject{` throws syntax error. It's valid either in some very old version, or you didn't copy-paste correctly the parenthesis (old Solidity version) and visibility modifier (`public`, `external`, ...). Can you also correct this?","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":197,"estimatedTokens":1254}}183{"id":"stack-55635498","source":"stackoverflow","questionId":55635498,"title":"Error when writing remix unit tests: URL not parseable: remix_accounts.sol","tags":["unit-testing","solidity","remix"],"text":"Title: Error when writing remix unit tests: URL not parseable: remix_accounts.sol\nTags: unit-testing, solidity, remix\nSource: Stack Overflow\n\nQuestion:\nI'm writing unit test in remix-ide and I want to call functions from different addresses within a single test. \n\nThe remix-tests Github page says that you can use `import \"remix_accounts.sol\";`, but I get `URL not parseable: remix_accounts.sol`. How to fix that? Or maybe there's another way to call from various addresses?\n\n========================================\n\nCode:\n```text\nimport \"remix_accounts.sol\";\n```\n\n```text\nURL not parseable: remix_accounts.sol\n```\n\n```text\nimport \"remix_accounts.sol\";\n```\n\n```text\nimport \"./remix_accounts.sol\";\n```\n\n```text\nimport \"../remix_accounts.sol\";\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":31,"estimatedTokens":187}}184{"id":"stack-48768481","source":"stackoverflow","questionId":48768481,"title":"How to manually create the instance of the contract in truffle","tags":["ethereum","solidity","truffle"],"text":"Title: How to manually create the instance of the contract in truffle\nTags: ethereum, solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nSay I have 2 contracts like this\n\n```\nA.sol\nimport './B.sol';\ncontract A {\n event BCreated(address addressOfB);\n function createB(){\n B b = new B(); \n BCreated(b);\n }\n}\n\nB.sol\ncontract B { \n uint8 value = 5;\n function getValue() constant returns(uint8){\n return value;\n }\n}\n```\n\nI am trying to write the test cases for these contracts.\nI can deploy the contract A using the migrations file and will \nget the instance of it.\n\nBut I am not sure about how to get the instance of contract B,\nafter the contract is created using function createB()\n\nOk I can get the address of the contract B in events after calling function createB(),\nBut not sure about the instance.\n\nFor this example, you can say that I can separately test contract B as it doesn't do much.\nBut in the real case, I need to create an instance using the address coming from the event.\n\nHere is the little bit of js code for truffle test file\nIn this I have the address of B\n\n```\nvar A = artifacts.require(\"./A.sol\");\ncontract('A', (accounts) => {\n it(\"Value should be 5\", async () => {\n let instanceOfA = await A.deployed()\n let resultTx = await instanceOfA.createB({ from: accounts[0] });\n console.log(\"Address of B: \" + resultTx.logs[0].args.addressOfB);\n /**\n * How do I create the instance of B now?\n */\n })\n})\n```\n\n========================================\n\nCode:\n```text\nA.sol\nimport './B.sol';\ncontract A {\n    event BCreated(address addressOfB);\n    function createB(){\n        B b = new B();   \n        BCreated(b);\n    }\n}\n\n\nB.sol\ncontract B {    \n    uint8 value = 5;\n    function getValue() constant returns(uint8){\n        return value;\n    }\n}\n```\n\n```text\nvar A = artifacts.require(\"./A.sol\");\ncontract('A', (accounts) => {\n    it(\"Value should be 5\", async () => {\n        let instanceOfA = await A.deployed()\n        let resultTx = await instanceOfA.createB({ from: accounts[0] });\n        console.log(\"Address of B: \" + resultTx.logs[0].args.addressOfB);\n        /**\n         * How do I create the instance of B now?\n         */\n    })\n})\n```\n\n```text\nvar A = artifacts.require(\"./A.sol\");\nvar B = artifacts.require(\"./B.sol\");\ncontract('A', (accounts) => {\n    it(\"Value should be 5\", async () => {\n        let instanceOfA = await A.deployed()\n        let resultTx = await instanceOfA.createB({ from: accounts[0] });\n        console.log(\"Address of B: \" + resultTx.logs[0].args.addressOfB);\n\n        let instanceOfB = await B.at(resultTx.logs[0].args.addressOfB);\n\n    })\n})\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":109,"estimatedTokens":650}}185{"id":"stack-53312840","source":"stackoverflow","questionId":53312840,"title":"How to fix \"insufficient funds for gas * price + value\"?","tags":["ethereum","solidity","smartcontracts","truffle","erc20"],"text":"Title: How to fix \"insufficient funds for gas * price + value\"?\nTags: ethereum, solidity, smartcontracts, truffle, erc20\nSource: Stack Overflow\n\nQuestion:\nWindows 10 Home x64\n\nbignumber.js@^7.2.1\n\nopenzeppelin-solidity@1.10.0\n\nreact@16.4.1\n\nreact-dom@16.4.1\n\ntruffle@4.1.13\n\nweb3@1.0.0-beta.34\n\nFull version reference:\n\nhttps://github.com/tooploox/ethereum-ico-examples/blob/master/package.json\n\nI have done a lot of research. I found so many sources but none of them found a solution and some threads are not updated any more or probably they already found an answer but did not post it. Some people manage to fix it in Mac, but I am using Windows. Some people fix it 5 months ago but when I tried it, it did not work out, buy changing the gas higher a little bit and run again. I also have `6 Ether` in my Ropsten account.\n\nThis is my `truffle.js`:\n\n```\nropsten: {\n provider: new HDWalletProvider(mnemonic, \"https://ropsten.infura.io/\"+infura_apikey),\n network_id: 3,\n gas: 4000000\n},\n```\n\nwhen I `truffle migrate --network ropsten`:\n\n```\nit triggers this error: \nRunning migration: 1_initial-migration.js\n Deploying Migrations...\nError encountered, bailing. Network state unknown. Review successful transactions manually.\ninsufficient funds for gas * price + value\n```\n\nGithub reference:\n\nhttps://github.com/tooploox/ethereum-ico-examples\n\nInstruction Reference:\n\nhttps://www.tooploox.com/blog/create-and-distribute-your-erc20-token-with-openzeppelin\n\n========================================\n\nCode:\n```text\nropsten: {\n  provider: new HDWalletProvider(mnemonic, \"https://ropsten.infura.io/\"+infura_apikey),\n  network_id: 3,\n  gas: 4000000\n},\n```\n\n```text\nit triggers this error:   \nRunning migration: 1_initial-migration.js\n  Deploying Migrations...\nError encountered, bailing. Network state unknown. Review successful transactions manually.\ninsufficient funds for gas * price + value\n```\n\n```text\n6 Ether\n```\n\n```text\ntruffle.js\n```\n\n```text\ntruffle migrate --network ropsten\n```\n\n```text\ngasPrice: 10000000000 // Something price like this\n```\n\n========================================\n\nComments:\n- Have you tried reducing the gas price?\n- thank you! it really works and leads to another problem\n- This is the up question, you might wanna check thanks! stackoverflow.com/questions/53320530/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":94,"estimatedTokens":576}}186{"id":"stack-71819186","source":"stackoverflow","questionId":71819186,"title":"What is the best practice of copying from array to array in Solidity?","tags":["arrays","ethereum","solidity","truffle","remix"],"text":"Title: What is the best practice of copying from array to array in Solidity?\nTags: arrays, ethereum, solidity, truffle, remix\nSource: Stack Overflow\n\nQuestion:\nI am trying to save gas by optimize code. In a flash, however, I was wondered what is the best practice of copying from array to array in Solidity.\n\nI present two option. One is copying by pointer (I guess) and the other is using for-loop.\n\n**TestOne.sol**\n\n```\ncontract TestContract {\n uint32[4] testArray;\n\n constructor(uint32[4] memory seeds) {\n testArray = seeds; // execution costs: 152253\n }\n\n function Show() public returns (uint32[4] memory) {\n return testArray;\n }\n}\n```\n\n**TestTwo.sol**\n\n```\ncontract TestContract {\n uint32[4] testArray;\n\n constructor(uint32[4] memory seeds) {\n for(uint i = 0; i I tested with Remix (Ethereum Online IDE), 0.8.13 Solidity Compiler with Enable optimization (200)\n\n### Discussion of test result\n\nWe can see that, TestOne used **152253 gas** for execution costs, and TestTwo used **150792 gas** for execution costs.\n\nThe funny thing is that, **for-loop** used less gas than just assigning pointer. In my little thought, for-loop would be more assembly codes than the other. (There would be, at least, assigning `uint i`, substitute 4 times, check conditions 4 times (whether `i I suspected the \"optimization\" of solidity compiler. But, after doing same small experiment without \"Enable optimization\", it does same result that for-loop used less gas. (198846 vs. 198464)\n\n### The Question is\n\nWhy do above things happened?\n\nWhat is the best practice of copying from array to array? Is there any copy function like C++'s `std::copy()` ?\n\n========================================\n\nCode:\n```text\ncontract TestContract {\n    uint32[4] testArray;\n\n    constructor(uint32[4] memory seeds) {\n        testArray = seeds; // execution costs: 152253\n    }\n\n    function Show() public returns (uint32[4] memory) {\n        return testArray;\n    }\n}\n```\n\n```text\ncontract TestContract {\n    uint32[4] testArray;\n\n    constructor(uint32[4] memory seeds) {\n        for(uint i = 0; i < 4; i++) {\n            testArray[i] = seeds[i];  // execution costs: 150792\n        }\n    }\n\n    function Show() public returns (uint32[4] memory) {\n        return testArray;\n    }\n}\n```\n\n```text\nuint i\n```\n\n```text\ni < 4\n```\n\n```text\ni++\n```\n\n```text\nstd::copy()\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity 0.8.13;\n\ncontract TestLoop {\n    uint32[4] testArray;\n\n    function setArrayWithLoop(uint32[4] memory array) public {\n        for(uint256 i = 0; i < array.length; i++)\n            testArray[i] = array[i];\n    }\n\n    function setArrayWithoutLoop(uint32[4] memory array) public {\n        testArray = array;\n    }\n\n    function show() public view returns (uint32[4] memory) {\n        return testArray;\n    }\n}\n\ncontract NoLoop {\n    uint32[4] testArray;\n\n    constructor(uint32[4] memory array) {\n        testArray = array;\n    }\n\n    function show() public view returns (uint32[4] memory) {\n        return testArray;\n    }\n}\n\ncontract Loop {\n    uint32[4] testArray;\n\n    constructor (uint32[4] memory array) {\n        for(uint256 i = 0; i < array.length; i++)\n            testArray[i] = array[i];\n    }\n\n    function show() public view returns (uint32[4] memory) {\n        return testArray;\n    }\n}\n```\n\n```py\nfrom brownie import TestLoop, NoLoop, Loop, accounts\n\ndef function_calls():\n    contract = TestLoop.deploy({'from': accounts[0]})\n    print('set array in loop')\n    contract.setArrayWithLoop([1, 2, 3, 4], {'from': accounts[1]})\n    print('array ', contract.show(), '\\n\\n')\n\n    print('set array by copy from memory to storage')\n    contract.setArrayWithoutLoop([10, 9, 8, 7], {'from': accounts[2]})\n    print('array ', contract.show(), '\\n\\n')\n\ndef deploy_no_loop():\n    print('deploy NoLoop contract')\n    contract = NoLoop.deploy([21, 22, 23, 24], {'from': accounts[3]})\n    print('array ', contract.show(), '\\n\\n')\n\ndef deploy_loop():\n    print('deploy Loop contract')\n    contract = Loop.deploy([31, 32, 33, 34], {'from': accounts[3]})\n    print('array ', contract.show(), '\\n\\n')\n\ndef main():\n    function_calls()\n    deploy_no_loop()\n    deploy_loop()\n```\n\n```yaml\ncompiler:\n  solc:\n    version: 0.8.13\n    optimizer:\n      enabled: true\n      runs: 1\n```\n\n```sh\nRunning 'scripts/test_loop.py::main'...\nTransaction sent: 0x8380ef4abff179f08ba9704826fc44961d212e5ee10952ed3904b5ec7828c928\n  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 0\n  TestLoop.constructor confirmed   Block: 1   Gas used: 251810 (2.10%)\n  TestLoop deployed at: 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87\n\nset array in loop\nTransaction sent: 0xfe72d6c878a980a9eeefee1dccdd0fe8214ee4772ab68ff0ac2b72708b7ab946\n  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 0\n  TestLoop.setArrayWithLoop confirmed   Block: 2   Gas used: 49454 (0.41%)\n\narray  (1, 2, 3, 4) \n\n\nset array by copy from memory to storage\nTransaction sent: 0x0106d1a7e37b155993a6d32d5cc9dc67696a55acd1cf29d2ed9dba0770436b98\n  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 0\n  TestLoop.setArrayWithoutLoop confirmed   Block: 3   Gas used: 41283 (0.34%)\n\narray  (10, 9, 8, 7) \n\n\ndeploy NoLoop contract\nTransaction sent: 0x55ddded68300bb8f11b3b43580c58fed3431a2823bf3f82f0081c7bfce66f34d\n  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 0\n  NoLoop.constructor confirmed   Block: 4   Gas used: 160753 (1.34%)\n  NoLoop deployed at: 0x7CA3dB74F7b6cd8D6Db1D34dEc2eA3c89a3417ec\n\narray  (21, 22, 23, 24) \n\n\ndeploy Loop contract\nTransaction sent: 0x1aa64f2cd527983df84cfdca5cfd7a281ff904cca227629ec8b0b29db561c043\n  Gas price: 0.0 gwei   Gas limit: 12000000   Nonce: 1\n  Loop.constructor confirmed   Block: 5   Gas used: 153692 (1.28%)\n  Loop deployed at: 0x2fb0fE4F05B7C8576F60A5BEEE35c23632Dc0C27\n\narray  (31, 32, 33, 34)\n```\n\n```text\n--optimize-runs=1\n```\n\n```text\n--optimize-runs\n```\n\n```text\nbrownie\n```\n\n```text\nbrownie-config.yaml\n```\n\n```text\ngas used\n```\n\n```text\nsetArrayWithoutLoop\n```\n\n```text\nsetArrayWithLoop\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":248,"estimatedTokens":1494}}187{"id":"stack-69301408","source":"stackoverflow","questionId":69301408,"title":"Solidity convert HEX number to HEX string","tags":["bit-manipulation","solidity","rsk"],"text":"Title: Solidity convert HEX number to HEX string\nTags: bit-manipulation, solidity, rsk\nSource: Stack Overflow\n\nQuestion:\nI need to store a value of this kind `0xff0000` or `0x00ff08` (hex colour representation) in solidity smart contract and be able to convert it inside a contract to a string with the same text characters `\"ff0000\"`. I intend to deploy this smart contract on RSK.\n\nMy idea was to store those values in a `bytes3` or simply `uint` variable and to have a pure function converting `bytes3` or `uint` to corresponding string. I found a function that does the job and working on solidity 0.4.9\n\n```\npragma solidity 0.4.9;\n\ncontract UintToString {\n function uint2hexstr(uint i) public constant returns (string) {\n if (i == 0) return \"0\";\n uint j = i;\n uint length;\n while (j != 0) {\n length++;\n j = j >> 4;\n }\n uint mask = 15;\n bytes memory bstr = new bytes(length);\n uint k = length - 1;\n while (i != 0){\n uint curr = (i & mask);\n bstr[k--] = curr > 9 ? byte(55 + curr ) : byte(48 + curr); // 55 = 65 - 10\n i = i >> 4;\n }\n return string(bstr);\n }\n}\n```\n\nBut I need a more recent compiler version (at least 0.8.0). The above function is not working on newer versions.\n\nWhat's the way to convert `bytes` or `uint` to a hex string (1->'1',f->'f') what works in Solidity >=0.8.0 ?\n\n========================================\n\nCode:\n```text\npragma solidity 0.4.9;\n\ncontract UintToString {\n    function uint2hexstr(uint i) public constant returns (string) {\n        if (i == 0) return \"0\";\n        uint j = i;\n        uint length;\n        while (j != 0) {\n            length++;\n            j = j >> 4;\n        }\n        uint mask = 15;\n        bytes memory bstr = new bytes(length);\n        uint k = length - 1;\n        while (i != 0){\n            uint curr = (i & mask);\n            bstr[k--] = curr > 9 ? byte(55 + curr ) : byte(48 + curr); // 55 = 65 - 10\n            i = i >> 4;\n        }\n        return string(bstr);\n    }\n}\n```\n\n```text\n0xff0000\n```\n\n```text\n0x00ff08\n```\n\n```text\n\"ff0000\"\n```\n\n```text\nbytes3\n```\n\n```text\nuint\n```\n\n```text\nbytes3\n```\n\n```text\nuint\n```\n\n```text\nbytes\n```\n\n```text\nuint\n```\n\n```text\npragma solidity >=0.8;\n\ncontract TypeConversion {\n    function uint2hexstr(uint i) public pure returns (string memory) {\n        if (i == 0) return \"0\";\n        uint j = i;\n        uint length;\n        while (j != 0) {\n            length++;\n            j = j >> 4;\n        }\n        uint mask = 15;\n        bytes memory bstr = new bytes(length);\n        uint k = length;\n        while (i != 0) {\n            uint curr = (i & mask);\n            bstr[--k] = curr > 9 ?\n                bytes1(uint8(55 + curr)) :\n                bytes1(uint8(48 + curr)); // 55 = 65 - 10\n            i = i >> 4;\n        }\n        return string(bstr);\n    }\n}\n```\n\n```text\nconstant\n```\n\n```text\npure\n```\n\n```text\nreturns (string)\n```\n\n```text\nreturns (string memory)\n```\n\n```text\nbyte(...)\n```\n\n```text\nbytes1(uint8(...))\n```\n\n```text\nbstr[k--] = curr > 9 ?\n```\n\n```text\nk\n```\n\n```text\n0\n```\n\n```text\nbstr[--k] = curr > 9 ?\n```\n\n```text\nSafeMath\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.128Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":172,"estimatedTokens":764}}188{"id":"stack-70405024","source":"stackoverflow","questionId":70405024,"title":"MetaMask - RPC Error: Cannot set properties of undefined (setting 'loadingDefaults') error","tags":["blockchain","solidity","smartcontracts","truffle","metamask"],"text":"Title: MetaMask - RPC Error: Cannot set properties of undefined (setting 'loadingDefaults') error\nTags: blockchain, solidity, smartcontracts, truffle, metamask\nSource: Stack Overflow\n\nQuestion:\nI'm building a staking function and hitting the following error after giving permission to access my token:\n\n\"MetaMask - RPC Error: Cannot set properties of undefined (setting 'loadingDefaults')\"\n\nStaking function Solidity contract:\n\n```\n// Staking function\n function depositTokens(uint _amount) public {\n require(_amount > 0, 'Amount has to be > 0');\n // Transfer tether tokens to this contract\n tether.transferFrom(msg.sender, address(this), _amount);\n\n // Update Staking balance\n stakingBalance[msg.sender] = stakingBalance[msg.sender] + _amount;\n\n if(!hasStaked[msg.sender]) {\n stakers.push(msg.sender);\n }\n\n // Update Staking balance\n isStaking[msg.sender] = true;\n hasStaked[msg.sender] = true;\n \n }\n```\n\nStaking Frontend\n\n```\nstakeTokens = (amount) => {\nthis.setState({loading: true })\nthis.state.tether.methods.approve(this.state.deBank._address, amount).send({from: this.state.account}).on('transactionHash', (hash) => {\n this.state.deBank.methods.depositTokens(amount).send({from: this.state.account}).on('transactionHash', (hash) => {\n this.setState({loading:false})\n })\n})\n```\n\n}\n\nWhat is weird is that in 25-30% of the case, I get to the second approval step and the transaction goes through.\n\nAnyone has an idea what's causing this?\n\n========================================\n\nTop Answer:\nchanged the function to async await syntax:\n\n```\nstakeTokens = async (amount) => {\nawait this.setState({ loading: true });\nawait this.state.tetherToken.methods.approve(this.state.tokenBank._address,amount).send({from : this.state.account });\n this.state.tokenBank.methods.stakeTokens(amount).send({from: this.state.account});\nthis.setState ({ loading: false });\n```\n\n========================================\n\nCode:\n```text\n// Staking function\n    function depositTokens(uint _amount) public {\n        require(_amount > 0, 'Amount has to be > 0');\n    // Transfer tether tokens to this contract\n    tether.transferFrom(msg.sender, address(this), _amount);\n\n    // Update Staking balance\n    stakingBalance[msg.sender] = stakingBalance[msg.sender] + _amount;\n\n    if(!hasStaked[msg.sender]) {\n        stakers.push(msg.sender);\n    }\n\n    // Update Staking balance\n    isStaking[msg.sender] = true;\n    hasStaked[msg.sender] = true;\n    \n    }\n```\n\n```text\nstakeTokens = (amount) => {\nthis.setState({loading: true })\nthis.state.tether.methods.approve(this.state.deBank._address, amount).send({from: this.state.account}).on('transactionHash', (hash) => {\n  this.state.deBank.methods.depositTokens(amount).send({from: this.state.account}).on('transactionHash', (hash) => {\n    this.setState({loading:false})\n  })\n})\n```\n\n```text\nstakeTokens = async (amount) => {\n  this.setState({ loading: true });\n\n  await this.state.tether.methods\n    .approve(this.state.decentralBank._address, amount)\n    .send({ from: this.state.account });\n\n  await this.state.decentralBank.methods\n    .depositTokens(amount)\n    .send({ from: this.state.account });\n\n  this.setState({ loading: false });\n\n};\n```\n\n```text\n.on('transactionHash', (hash) => {\n```\n\n```text\nstakeTokens = async (amount) => {\nawait this.setState({ loading: true });\nawait this.state.tetherToken.methods.approve(this.state.tokenBank._address,amount).send({from : this.state.account });\n  this.state.tokenBank.methods.stakeTokens(amount).send({from: this.state.account});\nthis.setState ({ loading: false });\n```\n\n```text\nsellTokens = (tokenAmount) => { this.setState({ loading: true }) this.state.token.methods.approve(this.state.cryptoExchange.address, tokenAmount).send({ from: this.state.account }).on('confirmation', (confirmation ) => { this.state.cryptoExchange.methods.sellTokens(tokenAmount).send({ from: this.state.account }).on('transactionHash', (hash) => { this.setState({ loading: false }) }) }) }\n```\n\n========================================\n\nComments:\n- Thank you @Nagasaki, I managed to fix this by uninstalling / reinstalling all the node.js dependencies in the project, deleting the .json contract abi files, and then redeploying the app -truffle compile and truffle migrate.\n- Didn't work for me - any other suggestions?\n- This should be the accepted answer. Worked a treat for me. Definitely a timing error hidden in the original code. whenever i debugged the orginal code - line by line never an error. The above code works every time for me. Thanks.\n- The async/await syntax does fix it... but it's actually waiting for the tx to be confirmed, which adds a lot of waiting. I believe it is equivalent to replacing `.on(\"transactionHash\")` with `.on(\"receipt\")`, but someone should confirm this.\n- Thank you @Filinto, that solved the issue.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Your answer could be improved by adding a code example to show the OP and future readers a working implementation.","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":140,"estimatedTokens":1300}}189{"id":"stack-49910904","source":"stackoverflow","questionId":49910904,"title":"invalid opcode error with a simple Solidity contract and script","tags":["javascript","blockchain","ethereum","solidity","web3js"],"text":"Title: invalid opcode error with a simple Solidity contract and script\nTags: javascript, blockchain, ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI am a newcomer to Solidity and web3.js . I am following the tutorial here - \n\nhttps://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2\n\nto build a simple Voting Dapp. \nI've installed ganache-cli, solc and web3 version 0.20.2 in the local node_modules folder using npm. The Voting.sol contract in Solidity is :\n\n```\npragma solidity ^0.4.18;\n\ncontract Voting {\n\n mapping (bytes32 => uint8) public votesReceived;\n bytes32[] public candidateList;\n\n function Voting(bytes32[] candidateNames) public {\n candidateList = candidateNames;\n }\n\n function totalVotesFor(bytes32 candidate) view public returns (uint8) {\n return votesReceived[candidate];\n }\n}\n```\n\nwith the following script called voting_main.js:\n\n```\nWeb3 = require('web3')\nweb3 = new Web3(new Web3.providers.HttpProvider(\"http://localhost:8545\"))\n\nfs = require('fs')\ncode = fs.readFileSync('Voting.sol').toString()\n\nsolc = require('solc')\ncompiledCode = solc.compile(code)\n\nabiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface)\nVotingContract = web3.eth.contract(abiDefinition)\nbyteCode = compiledCode.contracts[':Voting'].bytecode\ndeployedContract = VotingContract.new(['Rama','Nick','Jose'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000})\ncontractInstance = VotingContract.at(deployedContract.address)\n\ncontractInstance.totalVotesFor.call('Rama')\n```\n\nWhen I run ganache-cli on localhost:8545 and then run the script in another terminal, I get the following error.\n\n```\nameya@ameya-HP-ENVY-15-Notebook-PC:~/Fresh_install$ node voting_main.js \n/home/ameya/Fresh_install/node_modules/solc/soljson.js:1\n(function (exports, require, module, __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!==\"undefined\"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window===\"object\";var ENVIRONMENT_IS_WORKER=typeof importScripts===\"function\";var ENVIRONMENT_IS_NODE=typeof process===\"object\"&&typeof require===\"function\"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module[\"print\"])Module[\"print\"]=function print(x){process[\"stdout\"].write(x+\"\\n\")};if(!Module[\"printErr\"])Module[\"printErr\"]=function printErr(x){process[\"stderr\"].write(x+\"\\n\")};var nodeFS=require(\"fs\");var nodePath=require(\"path\");Module[\"read\"]=function read(filename,binary){filename=nodePath[\"normalize\"](filename);var ret=nodeFS[\"readFileSync\"](filename);if(!r\n\nError: VM Exception while processing transaction: invalid opcode\n at Object.InvalidResponse (/home/ameya/Fresh_install/node_modules/web3/lib/web3/errors.js:38:16)\n at RequestManager.send (/home/ameya/Fresh_install/node_modules/web3/lib/web3/requestmanager.js:61:22)\n at Eth.send [as call] (/home/ameya/Fresh_install/node_modules/web3/lib/web3/method.js:145:58)\n at SolidityFunction.call (/home/ameya/Fresh_install/node_modules/web3/lib/web3/function.js:135:32)\n at Object. (/home/ameya/Fresh_install/voting_main.js:16:32)\n at Module._compile (internal/modules/cjs/loader.js:654:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)\n at Module.load (internal/modules/cjs/loader.js:566:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:506:12)\n at Function.Module._load (internal/modules/cjs/loader.js:498:3)\n```\n\nThis seems to be a very simple example which is still throwing the invalid opcode error. Where am I going wrong ?\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.18;\n\ncontract Voting {\n\n  mapping (bytes32 => uint8) public votesReceived;\n  bytes32[] public candidateList;\n\n  function Voting(bytes32[] candidateNames) public {\n    candidateList = candidateNames;\n  }\n\n  function totalVotesFor(bytes32 candidate) view public returns (uint8) {\n    return votesReceived[candidate];\n  }\n}\n```\n\n```text\nWeb3 = require('web3')\nweb3 = new Web3(new Web3.providers.HttpProvider(\"http://localhost:8545\"))\n\nfs = require('fs')\ncode = fs.readFileSync('Voting.sol').toString()\n\nsolc = require('solc')\ncompiledCode = solc.compile(code)\n\nabiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface)\nVotingContract = web3.eth.contract(abiDefinition)\nbyteCode = compiledCode.contracts[':Voting'].bytecode\ndeployedContract = VotingContract.new(['Rama','Nick','Jose'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000})\ncontractInstance = VotingContract.at(deployedContract.address)\n\ncontractInstance.totalVotesFor.call('Rama')\n```\n\n```text\nameya@ameya-HP-ENVY-15-Notebook-PC:~/Fresh_install$ node voting_main.js \n/home/ameya/Fresh_install/node_modules/solc/soljson.js:1\n(function (exports, require, module, __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!==\"undefined\"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window===\"object\";var ENVIRONMENT_IS_WORKER=typeof importScripts===\"function\";var ENVIRONMENT_IS_NODE=typeof process===\"object\"&&typeof require===\"function\"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module[\"print\"])Module[\"print\"]=function print(x){process[\"stdout\"].write(x+\"\\n\")};if(!Module[\"printErr\"])Module[\"printErr\"]=function printErr(x){process[\"stderr\"].write(x+\"\\n\")};var nodeFS=require(\"fs\");var nodePath=require(\"path\");Module[\"read\"]=function read(filename,binary){filename=nodePath[\"normalize\"](filename);var ret=nodeFS[\"readFileSync\"](filename);if(!r\n\nError: VM Exception while processing transaction: invalid opcode\n    at Object.InvalidResponse (/home/ameya/Fresh_install/node_modules/web3/lib/web3/errors.js:38:16)\n    at RequestManager.send (/home/ameya/Fresh_install/node_modules/web3/lib/web3/requestmanager.js:61:22)\n    at Eth.send [as call] (/home/ameya/Fresh_install/node_modules/web3/lib/web3/method.js:145:58)\n    at SolidityFunction.call (/home/ameya/Fresh_install/node_modules/web3/lib/web3/function.js:135:32)\n    at Object.<anonymous> (/home/ameya/Fresh_install/voting_main.js:16:32)\n    at Module._compile (internal/modules/cjs/loader.js:654:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)\n    at Module.load (internal/modules/cjs/loader.js:566:32)\n    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)\n    at Function.Module._load (internal/modules/cjs/loader.js:498:3)\n```\n\n```text\nVotingContract.new(['Rama','Nick','Jose'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000}, (error, deployedContract) => {\n    if (!error) {\n        if (deployedContract.address) {\n            console.log(deployedContract.totalVotesFor.call('Rama'));\n        }\n    }\n});\n```\n\n```text\nconst fs = require(\"fs\");\nconst solc = require('solc')\n\nlet source = fs.readFileSync('nameContract.sol', 'utf8');\nlet compiledContract = solc.compile(source, 1);\nlet abi = compiledContract.contracts['nameContract'].interface;\nlet bytecode = compiledContract.contracts['nameContract'].bytecode;\nlet gasEstimate = web3.eth.estimateGas({data: bytecode});\nlet MyContract = web3.eth.contract(JSON.parse(abi));\n\nvar myContractReturned = MyContract.new(param1, param2, {\n   from:mySenderAddress,\n   data:bytecode,\n   gas:gasEstimate}, function(err, myContract){\n    if(!err) {\n       // NOTE: The callback will fire twice!\n       // Once the contract has the transactionHash property set and once its deployed on an address.\n\n       // e.g. check tx hash on the first call (transaction send)\n       if(!myContract.address) {\n           console.log(myContract.transactionHash) // The hash of the transaction, which deploys the contract\n\n       // check address on the second call (contract deployed)\n       } else {\n           console.log(myContract.address) // the contract address\n       }\n\n       // Note that the returned \"myContractReturned\" === \"myContract\",\n       // so the returned \"myContractReturned\" object will also get the address set.\n    }\n  });\n```\n\n```text\n.at()\n```\n\n```text\n.new()\n```\n\n```text\nat()\n```\n\n```text\ndeployedContract.transactionHash\n```\n\n========================================\n\nComments:\n- @Adams Kipnis I seem to be experiencing a similar issue here stackoverflow.com/questions/55662881/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":195,"estimatedTokens":2143}}190{"id":"stack-71254617","source":"stackoverflow","questionId":71254617,"title":"set token URI function","tags":["ethereum","solidity","smartcontracts","nft","erc721"],"text":"Title: set token URI function\nTags: ethereum, solidity, smartcontracts, nft, erc721\nSource: Stack Overflow\n\nQuestion:\nI understood that setTokenURI function isn't in use anymore. How can I change the token URI of the NFT token I want to create?\nfor now my function createCollectible inside the smart contract looks like this:\n\n```\nfunction createCollectible(string memory tokenURI)\n public\n returns (uint256)\n{\n uint256 newItemId = tokenId;\n _safeMint(msg.sender, newItemId);\n _setTokenURI(newItemId, tokenURI);\n tokenId = tokenId + 1;\n return newItemId;\n}\n```\n\n========================================\n\nCode:\n```text\nfunction createCollectible(string memory tokenURI)\n    public\n    returns (uint256)\n{\n    uint256 newItemId = tokenId;\n    _safeMint(msg.sender, newItemId);\n    _setTokenURI(newItemId, tokenURI);\n    tokenId = tokenId + 1;\n    return newItemId;\n}\n```\n\n```text\ncontract NFT is ERC721URIStorage { }\n```\n\n```text\nfunction tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n        require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\n\n        string memory baseURI = _baseURI();\n        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n    }\n```\n\n```text\nfunction _baseURI() internal view virtual returns (string memory) {\n        return \"\";\n    }\n```\n\n```text\ncontract NFT is ERC721{\n    function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {\n       require(_exists(tokenId), \"...\");\n       _tokenURIs[tokenId] = _tokenURI;\n           }\n   }\n```\n\n```text\n_setTokenURI\n```\n\n```text\nERC721URIStorage\n```\n\n```text\ntokenUri\n```\n\n```text\nERC721\n```\n\n```text\n_baseUri()\n```\n\n```text\nERC721\n```\n\n```text\nvirtual\n```\n\n```text\noverride\n```\n\n```text\nERC721URIStorage\n```\n\n```text\nERC721\n```\n\n========================================\n\nComments:\n- So I need to use in my smart contract tokenURI function from ERC721 or setTokenURI from the ERC721URIstorage?\n- either of them. each has its own use case and discussed here: forum.openzeppelin.com/t/&hellip;\n- Thanks. Another question is why _setTokenURI is more expensive that tokenURI as you mentioned above?\n- ERC721URIstorage stores data for tokenURI on-chain @OmerS , this might be one of the reason.\n- _exists(tokenId) method was removed from openzeppelin 5 and should be replaced with `_ownerOf(tokenId) != address(0)`. so answer is outdated","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":113,"estimatedTokens":608}}191{"id":"stack-66735307","source":"stackoverflow","questionId":66735307,"title":"Truffle contract deployment failed, invalid sender","tags":["solidity","truffle"],"text":"Title: Truffle contract deployment failed, invalid sender\nTags: solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nI'm trying to deploy a contract to the ropsten testnet using truffle, but I get the following error:\n\n```\nDeploying 'Migrations'\n ----------------------\n\nError: *** Deployment Failed ***\n\n\"Migrations\" -- invalid sender.\n\n at /home/usr/.npm/lib/node_modules/truffle/build/webpack:/packages/deployer/src/deployment.js:365:1\n at process._tickCallback (internal/process/next_tick.js:68:7)\nTruffle v5.2.5 (core: 5.2.5)\nNode v10.19.0\n```\n\nWhen deploying to ganache locally, it works fine. Also I'm pretty sure my truffle-config.js is correct, it's the same as all the online tutorials, but since I'm here, I guess I'm not completely sure :). The address that hd-wallet is using is also correct (verified with the console.log statement in truffle-config.js) and it has 5 ETH balance, so more than enough. I have 2 migration scripts, it gives exactly the same error with each script.\n\ntruffle-config.js:\n\n```\nrequire(\"dotenv\").config();\nconst HDWalletProvider = require(\"@truffle/hdwallet-provider\");\n\nmodule.exports = {\n networks: {\n ropsten: {\n provider: () => {\n var provider = new HDWalletProvider({\n mnemonic: process.env.MNEMONIC,\n providerOrUrl: `https://ropsten.infura.io/v3/${process.env.INFURA_KEY}`,\n derivationPath: \"m/44'/60'/0'/0/\",\n addressIndex: 0,\n });\n console.log(provider.getAddress());\n return provider;\n },\n network_id: 3,\n gas: 5500000,\n confirmations: 2,\n timeoutBlocks: 200,\n skipDryRun: true,\n },\n development: {\n host: \"127.0.0.1\",\n port: 7545,\n network_id: \"*\",\n },\n },\n compilers: {\n solc: {\n version: \"0.6.0\",\n optimizer: {\n enabled: true,\n runs: 200,\n },\n },\n },\n};\n```\n\n1_initial_migration.js:\n\n```\nconst Migrations = artifacts.require(\"Migrations\");\n\nmodule.exports = function (deployer) {\n deployer.deploy(Migrations);\n};\n```\n\n2_deploy.js:\n\n```\nconst Token = artifacts.require(\"Token\");\n\nmodule.exports = (deployer) => {\n deployer.deploy(Token);\n};\n```\n\nToken.sol:\n\n```\n//SPDX-License-Identifier: MIT\npragma solidity >=0.6.0 Escrow.sol:\n\n```\n//SPDX-License-Identifier: MIT\npragma solidity >=0.6.0 uint256) public deposits;\n\n modifier onlyAgent() {\n require(msg.sender == agent);\n _; // return void\n }\n\n constructor() public {\n // solidity heeft globale var msg\n agent = msg.sender;\n }\n\n function deposit(address payee) payable public onlyAgent {\n uint256 amount = msg.value;\n deposits[payee] = deposits[payee] + amount;\n }\n\n function withdras(address payable payee) public onlyAgent {\n uint256 payment = deposits[payee];\n deposits[payee] = 0;\n\n payee.transfer(payment);\n }\n}\n```\n\n========================================\n\nTop Answer:\nTry a different version @truffle/hdwallet-provider\nWorks for me with 1.2.3\n\nnpm uninstall @truffle/hdwallet-provider\nnpm install @truffle/hdwallet-provider@1.2.3\n\nWith the latest version (1.2.4) there was the same error (invalid sender).\n\n========================================\n\nCode:\n```text\nDeploying 'Migrations'\n   ----------------------\n\nError:  *** Deployment Failed ***\n\n\"Migrations\" -- invalid sender.\n\n    at /home/usr/.npm/lib/node_modules/truffle/build/webpack:/packages/deployer/src/deployment.js:365:1\n    at process._tickCallback (internal/process/next_tick.js:68:7)\nTruffle v5.2.5 (core: 5.2.5)\nNode v10.19.0\n```\n\n```js\nrequire(\"dotenv\").config();\nconst HDWalletProvider = require(\"@truffle/hdwallet-provider\");\n\nmodule.exports = {\n    networks: {\n        ropsten: {\n            provider: () => {\n                var provider = new HDWalletProvider({\n                    mnemonic: process.env.MNEMONIC,\n                    providerOrUrl: `https://ropsten.infura.io/v3/${process.env.INFURA_KEY}`,\n                    derivationPath: \"m/44'/60'/0'/0/\",\n                    addressIndex: 0,\n                });\n                console.log(provider.getAddress());\n                return provider;\n            },\n            network_id: 3,\n            gas: 5500000,\n            confirmations: 2,\n            timeoutBlocks: 200,\n            skipDryRun: true,\n        },\n        development: {\n            host: \"127.0.0.1\",\n            port: 7545,\n            network_id: \"*\",\n        },\n    },\n    compilers: {\n        solc: {\n            version: \"0.6.0\",\n            optimizer: {\n                enabled: true,\n                runs: 200,\n            },\n        },\n    },\n};\n```\n\n```js\nconst Migrations = artifacts.require(\"Migrations\");\n\nmodule.exports = function (deployer) {\n  deployer.deploy(Migrations);\n};\n```\n\n```js\nconst Token = artifacts.require(\"Token\");\n\nmodule.exports = (deployer) => {\n    deployer.deploy(Token);\n};\n```\n\n```js\n//SPDX-License-Identifier: MIT\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\ncontract Token is ERC20 {\n\n    address minter;\n\n    // minterChanged event\n    event minterChanged(address indexed from, address to);\n    \n    constructor() public payable ERC20(\"Decentralized Bank Currency\", \"DCB\") {\n\n        minter = msg.sender;\n    }\n\n    function transferMinterRole(address bank) public returns(bool) {\n        require(msg.sender == minter);\n        minter = bank;\n\n        emit minterChanged(msg.sender, minter);\n        return true;\n    }\n\n    function mint(address account, uint256 amount) public {\n\n        require(msg.sender == minter);\n        _mint(account, amount);\n    }\n}\n```\n\n```js\n//SPDX-License-Identifier: MIT\npragma solidity >=0.6.0 <0.8.0 ;\n\ncontract Escrow {\n    address agent;\n\n    mapping(address => uint256) public deposits;\n\n    modifier onlyAgent() {\n        require(msg.sender == agent);\n        _; // return void\n    }\n\n    constructor() public {\n        // solidity heeft globale var msg\n        agent = msg.sender;\n    }\n\n    function deposit(address payee) payable public onlyAgent {\n        uint256 amount = msg.value;\n        deposits[payee] = deposits[payee] + amount;\n    }\n\n\n    function withdras(address payable payee) public onlyAgent {\n        uint256 payment = deposits[payee];\n        deposits[payee] = 0;\n\n        payee.transfer(payment);\n    }\n}\n```\n\n```text\nropsten: {\n      provider: () =>\n        new HDWalletProvider({\n          mnemonic,\n          providerOrUrl:\n            'wss://ropsten.infura.io/ws/v3/.....',\n          chainId: 3,\n        }),\n      network_id: 3, // Ropsten's id\n      gas: 5500000, // Ropsten has a lower block limit than mainnet\n      confirmations: 0, // # of confs to wait between deployments. (default: 0)\n      timeoutBlocks: 200, // # of blocks before a deployment times out  (minimum/default: 50)\n      skipDryRun: true, // Skip dry run before migrations? (default: false for public nets )\n    },\n```\n\n```text\nganache-cli\n```\n\n```text\nchainId\n```\n\n```js\nropsten: {\n    provider: function () {\n        return new HDWalletProvider(\n            {\n                privateKeys: [\"YourPrivateKey\"],\n                providerOrUrl: \"https://ropsten.infura.io/v3/InfuraKey\",\n                chainId: 3,\n            }\n        )\n    },\n    network_id: '3',\n}\n```\n\n```text\n\"dependencies\": {\n    \"@truffle/hdwallet-provider\": \"^1.3.1\"\n}\n```\n\n```text\ntruffle-config.js\n```\n\n```text\nconst HDWalletProvider = require('truffle-hdwallet-provider');\n```\n\n```text\nconst HDWalletProvider = require('@truffle/hdwallet-provider');\n```\n\n```text\n@truffle/hdwallet-provider\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- Thanks! That does seem to be the most likely scenario. I'll try setting up geth and deploy using the --rpc.allow-unprotected-txs arg. If it works I'll let you know.\n- You saved another life.\n- You still saved another life.\n- A 4th life saved!\n- 6th person :DDD\n- The root reason is the `chainId` parameter is now required. Please see my answer. Downgrading the version will solve this but it's not the perfect choice.\n- This only treats the symptoms, I checked and verified that Yija Su's solution fixes the root cause.\n- You are the hero we need\n- Not the hero we deserve\n- One more here. I saw this error with version 1.3.0, but winding back to 1.2.3 fixed!\n- And another one! To the moon :diamond: :fingers:\n- I just checked with hdwallet-provider 1.3.0, this indeed fixes the root problem. I guess many people prefer the quick and easy solution :)\n- Thanks for this solution. Unfortunately it doesn't work for BSC, when I try to update my `HDWalletProvider` and provide the `chainId`, I get the following error: `Error: Chain with ID 97 not supported`. Rolling back to 1.2.3 DOES fix it though.","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":355,"estimatedTokens":2120}}192{"id":"stack-44991977","source":"stackoverflow","questionId":44991977,"title":"Why can't you pass strings from contract to contract?","tags":["solidity"],"text":"Title: Why can't you pass strings from contract to contract?\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nWhen calling trying to pass a string from contract to contract, I get an error. in getName with error. I'm aware you cannot pass strings but what is the reason?\n\n Return argument type inaccessible dynamic type is not implicitly\n convertible to expected type (type of first return variable) string\n memory. return toBeCalled.getName();\n\n```\npragma solidity ^0.1.0;\n\ncontract ToContract{\n FromContract fromContract = new FromContract();\n\n function getName() constant returns (string) {\n return fromContract.getName();\n }\n\n}\n\ncontract FromContract{\n string name = 'dapp';\n\n function getName() constant return(string){\n return name;\n }\n\n}\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.1.0;\n\ncontract ToContract{\n    FromContract fromContract = new FromContract();\n\n    function getName() constant returns (string) {\n        return fromContract.getName();\n    }\n\n}\n\ncontract FromContract{\n    string name = 'dapp';\n\n    function getName() constant return(string){\n        return name;\n    }\n\n}\n```\n\n========================================\n\nComments:\n- Please have a look at this link - ethereum.stackexchange.com/questions/3727/&hellip; - It explains why dynamic type size cannot be accessed by other contract.","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":62,"estimatedTokens":338}}193{"id":"stack-67611716","source":"stackoverflow","questionId":67611716,"title":"Why does the minting function of ERC721 have an access control?","tags":["blockchain","ethereum","solidity","openzeppelin","nft"],"text":"Title: Why does the minting function of ERC721 have an access control?\nTags: blockchain, ethereum, solidity, openzeppelin, nft\nSource: Stack Overflow\n\nQuestion:\nMost of the ERC721 examples using Open Zeppelin I see require the mint function to have an access control where only the owner of the contract is allowed to call the function. For example,\n\n```\nfunction mint(address to) public virtual {\n require(hasRole(MINTER_ROLE, _msgSender()), \"ERC721PresetMinterPauserAutoId: must have minter role to mint\");\n\n _mint(to, _tokenIdTracker.current());\n _tokenIdTracker.increment();\n}\n```\n\nor the following using the Ownable library.\n\n```\nfunction mint(address receiver) external onlyOwner returns (uint256) {\n _tokenIds.increment();\n\n uint256 newTokenId = _tokenIds.current();\n _mint(receiver, newTokenId);\n\n return newTokenId;\n}\n```\n\nDoes this mean a new contract has to be deployed each time a new token is minted? This seems not only excessive in terms of the gas fee, but also the ERC721 contract has properties for mapping different owners and tokens:\n\n```\n// Mapping from token ID to owner address\nmapping (uint256 => address) private _owners;\n\n// Mapping owner address to token count\nmapping (address => uint256) private _balances;\n```\n\nwhich wouldn't make sense if minting is restricted to the contract owner.\n\nIt makes more sense to me that you deploy a single ERC721 contract (and its dependencies) and have the users call the mint function. What is the best practice for the mint function of ERC721?\n\n========================================\n\nCode:\n```text\nfunction mint(address to) public virtual {\n    require(hasRole(MINTER_ROLE, _msgSender()), \"ERC721PresetMinterPauserAutoId: must have minter role to mint\");\n\n    _mint(to, _tokenIdTracker.current());\n    _tokenIdTracker.increment();\n}\n```\n\n```text\nfunction mint(address receiver) external onlyOwner returns (uint256) {\n    _tokenIds.increment();\n\n    uint256 newTokenId = _tokenIds.current();\n    _mint(receiver, newTokenId);\n\n    return newTokenId;\n}\n```\n\n```text\n// Mapping from token ID to owner address\nmapping (uint256 => address) private _owners;\n\n// Mapping owner address to token count\nmapping (address => uint256) private _balances;\n```\n\n```text\nMINTER_ROLE\n```\n\n```text\nonlyOwner\n```\n\n```text\n_owners\n```\n\n```text\n_balances\n```\n\n```text\n1\n```\n\n```text\n0x123\n```\n\n```text\n_owners[1]\n```\n\n```text\n0x123\n```\n\n```text\n_balances[0x123]\n```\n\n```text\n1\n```\n\n```text\n2\n```\n\n```text\n0x123\n```\n\n```text\n_owners[1]\n```\n\n```text\n0x123\n```\n\n```text\n_owners[2]\n```\n\n```text\n0x123\n```\n\n```text\n_balances[0x123]\n```\n\n```text\n2\n```\n\n========================================\n\nComments:\n- Are the ERC721 contracts mentioned here only useful if the contract owner is minting tokens for certain addresses? I'm actually looking for a structure where users can mint their own tokens without the central figure. Is there any security flaws if I were to simply remove the access control for the mint function and make it public? I'm just trying to make sense of the reason for the access limitation because I'm not sure if it's as important as the access control for transferring or burning a token.\n- If you want to open the minting feature, you can remove the authorization from the `mint()` function. From security standpoint, I can only think of higher probability of reaching the ID max value (if you chose to make it `uint8` or some \"small\" datatype) and possible integer overflow (if you don't prevent it either using Solidity 0.8+, or checking with `require`/`assert`). Otherwise, it's same level of security as if you only had authorized addresses, because they should be treated in the code as untrusted as well (e.g. don't trust but verify that they return some value if they're a contract).\n- Is it a more common approach to deploy a new contract when the URL is different (to signify a different creature as opposed to just a different variant) or is it better to re-use the old contract and keep adding different URLs for different things to the same contract?\n- @KernelJames A general practice is one contract for one collection. So if you have a collection of \"cat NFTs\", you might want to deploy a new contract for another collection of \"dog NFTs\". But if your overal aim is to create a collection of \"animal NFTs\", they you might want to group all these tokens under the one collection.","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":153,"estimatedTokens":1089}}194{"id":"stack-67006583","source":"stackoverflow","questionId":67006583,"title":"IPFS and Editing Permissions","tags":["blockchain","ethereum","solidity","ipfs"],"text":"Title: IPFS and Editing Permissions\nTags: blockchain, ethereum, solidity, ipfs\nSource: Stack Overflow\n\nQuestion:\nI just uploaded a folder of 5 images to IPFS (using the Mac Desktop IPFS Client App, so it was a very simple drag and drop operation.)\n\nSo being that I’m the one that created and published this folder, does that mean that I’m the only one that’s allowed to make further modifications to it - like adding or deleting more images from it? Or can anyone out there on IPFS do that as well?\n\nIf they can, is there a way to prevent that from happening?\n\n=======================================\n\nUPDATED QUESTION:\n\nMy specific use-case has to do with updating the metadata of ERC721 Tokens - ***after*** they’ve already been minted.\n\nImagine for example a game where certain objects - like say a magical sword - gains special powers after a certain amount of usage or after the completion of certain missions by its owner. So we’d want to update this sword’s attributes by editing it’s Metadata and re-committing this updated metadata file to the Blockchain.\n\nIf our game has 100 swords for example, and we initially uploaded to IPFS a folder containing all 100 json files (one for each sword), then I’m pretty sure IPFS still let’s you access the specific files within the hashed-folder by their specific human-readable names (and not only by their hash.)\nSo if our sword happens to be sword #76, and our naming convention for our JSON files was of this format: `“sword000.json”` , then sword#76’s JSON metadata file would have a path such as:\nhttp://ipfs.infura.io/QmY2xxxxxxxxxxxxxxxxxxxxxx/sword076.json\n\nIf we then edited the “sword076.json“ file and drag-n-dropped it back into our master JSON folder, it would obviously cause that folder’s Hash/CID value to change. BUT, as long as we’re able update our Solidity Contract’s “tokenURI” method to look for and serve our “.json” files from this newly updated HASH/CID folder name, we could still refer to the individual files within it by their regular English names. Which means we’d be good to go.\n\nWhether or not this is a good scheme to employ is something we can definitely discuss, but I FIRST want to go back to my original question/concern, which is that I want to make sure that WE are the ONLY ones that can update the contents of our folder - and that no one else has permission to do that.\n\nDoes that make sense?\n\n========================================\n\nCode:\n```text\n“sword000.json”\n```\n\n========================================\n\nComments:\n- @Discoradian Thanks for answering - very much appreciate it! I should have phrased my question differently cause I'm actually very familiar with IPFS, how adding/removing files changes folder Hashes, CID's, etc. What I was trying to understand is - again, if “I’m the only one that’s allowed to make further modifications” to a folder I uploaded to IPFS, or “can anyone out there on IPFS do that as well?” It’s strictly a question re permissions, not practicality or mutability. I updated my question to give the full context of what exactly I’m trying to achieve - please check it out!\n- @Sirab33 I've read your updated question. So you understand when the file is updated, the dir CID changes, you update that in Solidity, great. So wouldn't the question be more \"who can update the tokenuri method?\" as anyone could download your IPFS files, change them, and upload them with a new CID, as IPFS is completely open. However your tokenuri method I'm assuming has permission involved, and that's really the content that's being pointed to. So the real problem to address is \"Who can update the TokenURI?\" and if that's just you, sounds like you're all set.\n- @Discoradian Thanks for responding again. To answer your question: \"wouldn't the question be more 'who can update the tokenuri method?'\" The answer is \"No. My question is and remains what it always was, the gist of it being: can anyone update any directory on IPFS?\" The reason I updated my original question was to provide you with further context re *why* I asked my original question, but I never *changed* my original question. I actually literally ended my updated question by saying “I FIRST want to go back to my original question/concern.” Perhaps you glossed over that.\n- Either way, you did answer my original question now by writing that \"IPFS is completely open\" - which I actually find really surprising, if not downright crazy. Cause if anyone out there can upload anything into any existing IPFS directory - even one they didn’t create, well that seems like an invitation for chaos. I think I’ll have to dig deeper into that. Anyway, thanks again!\n- @Sirab33 I'm not sure where the confusion stems from but the data is immutable, so nobody can add anything into an existing IPFS directory, it'd always be a copy, a different hash, for different data.\n- Perhaps to add more clarity, there's no concept of editing/updating/modifying in IPFS, so therefore no real permissions. There's really fundamentally really only add and pin. I'm sorry for any confusion.","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":45,"estimatedTokens":1262}}195{"id":"stack-49696475","source":"stackoverflow","questionId":49696475,"title":"Web3 + Solidity: Passing in arguments to a contract's constructor","tags":["node.js","solidity","web3js"],"text":"Title: Web3 + Solidity: Passing in arguments to a contract's constructor\nTags: node.js, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI am attempting to write some unit tests for a smart contract I'm writing, but am having difficulty when figuring out how to pass in arguments to my contract's constructor upon creation. Below is my code:\n\n```\nconst assert = require('assert');\nconst ganache = require('ganache-cli');\nconst provider = ganache.provider();\nconst Web3 = require('web3');\nconst web3 = new Web3(provider);\nconst { interface, bytecode } = require('../ethereum/compile');\n\nlet token;\nlet accounts;\n\nbeforeEach(async () => {\n accounts = await web3.eth.getAccounts();\n token = await new web3.eth.Contract(JSON.parse(interface))\n .deploy({ data: bytecode })\n .send({ from: accounts[0], gas: '1000000' });\n token.setProvider(provider);\n});\n\ndescribe('Token Contract', () => { ... });\n```\n\nBased on this set up, how can I pass in arguments to the contract? I got this far by following a solidity course, but the contract in the lessons did not have any options for it's constructor, so it never covered where they should go. Thank you for your help!\n\n========================================\n\nCode:\n```text\nconst assert = require('assert');\nconst ganache = require('ganache-cli');\nconst provider = ganache.provider();\nconst Web3 = require('web3');\nconst web3 = new Web3(provider);\nconst { interface, bytecode } = require('../ethereum/compile');\n\nlet token;\nlet accounts;\n\nbeforeEach(async () => {\n  accounts = await web3.eth.getAccounts();\n  token = await new web3.eth.Contract(JSON.parse(interface))\n    .deploy({ data: bytecode })\n    .send({ from: accounts[0], gas: '1000000' });\n  token.setProvider(provider);\n});\n\ndescribe('Token Contract', () => { ... });\n```\n\n```text\n.deploy({ data: bytecode, arguments: [ ... ] })\n```\n\n```text\ndeploy\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":63,"estimatedTokens":464}}196{"id":"stack-56469332","source":"stackoverflow","questionId":56469332,"title":"Solidity: return array in a public method","tags":["solidity"],"text":"Title: Solidity: return array in a public method\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a public funcion that returns an array,\nthis is the error\n\n Return argument type mapping(uint256 => struct ItemList.Item storage\n ref) is not implicitly convertible to expected type (type of first\n return variable) uint256[] memory.\n\n```\npragma solidity ^0.5.0;\ncontract ItemList {\n uint public itemCount = 0;\n mapping(uint256 => Item) public items;\n\n event ItemCreated (\n uint id,\n string proofdocument\n );\n\n struct Item {\n uint id;\n string proofdocument;\n }\n\n constructor() public {\n }\n\n function createItem(string memory _proofdocument) public {\n itemCount++;\n items[itemCount] = Item(itemCount, _proofdocument);\n emit ItemCreated(itemCount, _proofdocument);\n }\n\n function getItems() public pure returns(uint256[] memory ) {\n return items; Thanks Andrea\n\n========================================\n\nCode:\n```text\npragma solidity ^0.5.0;\ncontract ItemList {\n    uint public itemCount = 0;\n    mapping(uint256 => Item) public items;\n\n    event ItemCreated (\n        uint id,\n        string proofdocument\n    );\n\n    struct Item {\n        uint id;\n        string proofdocument;\n    }\n\n    constructor() public {\n    }\n\n    function createItem(string memory _proofdocument) public {\n        itemCount++;\n        items[itemCount] = Item(itemCount, _proofdocument);\n        emit ItemCreated(itemCount, _proofdocument);\n    }\n\n    function getItems() public pure returns(uint256[] memory ) {\n        return items; <----------ERROR\n    }\n}\n```\n\n```js\nconst array = []\nfor (let i = 0; i < itemCount; itemCount += 1) {\n    array.push(contract.getItem(i)) // where getItem do items[I] in solidity\n}\n```\n\n```text\npragma solidity ^0.5.0;\npragma experimental ABIEncoderV2;\n\ncontract ItemList {\n    uint public itemCount = 0;\n\n    struct Item {\n        uint id;\n        string proofdocument;\n    }\n    Item[] items;\n\n    constructor() public {}\n\n    function createItem(string memory _proofdocument) public {\n        itemCount++;\n        items.push(Item(itemCount, _proofdocument));\n    }\n\n    function getItems() external view returns(Item[] memory) {\n        return items;\n    }\n}\n```\n\n```text\nweb3.js\n```\n\n```text\npragma experimental\n```\n\n========================================\n\nComments:\n- Well, yeah. The error message is pretty clear. What were you *expecting* to happen? What values would be returned?\n- it should returns an array :-( i can't see the error sorry","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":120,"estimatedTokens":620}}197{"id":"stack-72429607","source":"stackoverflow","questionId":72429607,"title":"Why can't we get a returned value from sendTransaction() run on a smart contract?","tags":["javascript","ethereum","solidity","smartcontracts","web3js"],"text":"Title: Why can't we get a returned value from sendTransaction() run on a smart contract?\nTags: javascript, ethereum, solidity, smartcontracts, web3js\nSource: Stack Overflow\n\nQuestion:\nAll discussions on this mention that it's impossible to get a returned value from sendTransaction() run on a contract function, where the contract state is being changed. I don't understand why the returned value can't be recorded in the transaction log on the blockchain, similarly to events, and so then it could be retrieved on the transaction confirmation:\n\n```\nweb3.eth.sendTransaction(...)\n.on('confirmation', function(1, receipt){ ... // retrieving value returned by smart contract function here })\n```\n\n========================================\n\nCode:\n```text\nweb3.eth.sendTransaction(...)\n.on('confirmation', function(1, receipt){ ... // retrieving value returned by smart contract function here })\n```\n\n```text\nstatus\n```\n\n```text\nstatus\n```\n\n========================================\n\nComments:\n- I am also not clear on this one and finding more stuff to understand. I found this to be close enough - consensys.net/blog/developers/&hellip;\n- Short answer is \"because of the quirky design\".","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":33,"estimatedTokens":296}}198{"id":"stack-51355259","source":"stackoverflow","questionId":51355259,"title":"Ethereum Web3.js Invalid JSON RPC response: \"\"","tags":["blockchain","ethereum","solidity"],"text":"Title: Ethereum Web3.js Invalid JSON RPC response: \"\"\nTags: blockchain, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI am using web3.js module for ethereum. While executing a transaction I am getting error response.\n\nError:\n\n```\n\"Error: Invalid JSON RPC response: \"\"\n at Object.InvalidResponse (/home/akshay/WS/ethereum/node_modules/web3-core-helpers/src/errors.js:42:16)\n at XMLHttpRequest.request.onreadystatechange (/home/akshay/WS/ethereum/node_modules/web3-providers-http/src/index.js:73:32)\n at XMLHttpRequestEventTarget.dispatchEvent (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:64:18)\n at XMLHttpRequest._setReadyState (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:354:12)\n at XMLHttpRequest._onHttpResponseEnd (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:509:12)\n at IncomingMessage. (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:469:24)\n at emitNone (events.js:111:20)\n at IncomingMessage.emit (events.js:208:7)\n at endReadableNT (_stream_readable.js:1064:12)\n at _combinedTickCallback (internal/process/next_tick.js:138:11)\n at process._tickCallback (internal/process/next_tick.js:180:9)\"\n```\n\nI am using ropsten test network url for testing my smart contract:\n\n```\nhttps://ropsten.infura.io/API_KEY_HERE\n```\n\nWhen I call the `balanceOf` function, it works fine but when I try to call function `transfer` it send me this error. The code is mentioned below:\n\n```\nrouter.post('/transfer', (req, res, next)=>{\n contractInstance.methods.transfer(req.body.address, req.body.amount).send({from:ownerAccountAddress})\n .on('transactionHash',(hash)=>{\nconsole.log(hash)\n }).on('confirmation',(confirmationNumber, receipt)=>{\n console.log(confirmationNumber)\n console.log(receipt)\n }).on('receipt', (receipt)=>{\n console.log(receipt)\n }).on('error',(err)=>{\n console.log(err)\n })\n})\n```\n\nPlease let me know where I am wrong.\n\nEDIT: I am using web3js version `\"web3\": \"^1.0.0-beta.34\"`\n\n========================================\n\nTop Answer:\nwhen using Web3.js you should sign the transactions. When you call functions which are non-constant, like transfer, you should sign the transaction and after that send the signed transaction (there is a method called sendSignedTransaction). This is very hard using web3js, I recommend using ehtersjs, with it everything is a lot easier.\n\n========================================\n\nCode:\n```text\n\"Error: Invalid JSON RPC response: \"\"\n    at Object.InvalidResponse (/home/akshay/WS/ethereum/node_modules/web3-core-helpers/src/errors.js:42:16)\n    at XMLHttpRequest.request.onreadystatechange (/home/akshay/WS/ethereum/node_modules/web3-providers-http/src/index.js:73:32)\n    at XMLHttpRequestEventTarget.dispatchEvent (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:64:18)\n    at XMLHttpRequest._setReadyState (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:354:12)\n    at XMLHttpRequest._onHttpResponseEnd (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:509:12)\n    at IncomingMessage.<anonymous> (/home/akshay/WS/ethereum/node_modules/xhr2/lib/xhr2.js:469:24)\n    at emitNone (events.js:111:20)\n    at IncomingMessage.emit (events.js:208:7)\n    at endReadableNT (_stream_readable.js:1064:12)\n    at _combinedTickCallback (internal/process/next_tick.js:138:11)\n    at process._tickCallback (internal/process/next_tick.js:180:9)\"\n```\n\n```text\nhttps://ropsten.infura.io/API_KEY_HERE\n```\n\n```text\nrouter.post('/transfer', (req, res, next)=>{\n  contractInstance.methods.transfer(req.body.address, req.body.amount).send({from:ownerAccountAddress})\n  .on('transactionHash',(hash)=>{\nconsole.log(hash)\n  }).on('confirmation',(confirmationNumber, receipt)=>{\n    console.log(confirmationNumber)\n    console.log(receipt)\n  }).on('receipt', (receipt)=>{\n    console.log(receipt)\n  }).on('error',(err)=>{\n    console.log(err)\n  })\n})\n```\n\n```text\nbalanceOf\n```\n\n```text\ntransfer\n```\n\n```text\n\"web3\": \"^1.0.0-beta.34\"\n```\n\n```js\ncontractInstance.methods.aPublicFunctionOrVariableName().call().then( (result) => {console.log(result);})\n```\n\n```js\nweb3.eth.getTransactionCount(functioncalleraddress).then( (nonce) => {\n        let encodedABI = contractInstance.methods.statechangingfunction().encodeABI();\n contractInstance.methods.statechangingfunction().estimateGas({ from: calleraddress }, (error, gasEstimate) => {\n          let tx = {\n            to: contractAddress,\n            gas: gasEstimate,\n            data: encodedABI,\n            nonce: nonce\n          };\n          web3.eth.accounts.signTransaction(tx, privateKey, (err, resp) => {\n            if (resp == null) {console.log(\"Error!\");\n            } else {\n              let tran = web3.eth.sendSignedTransaction(resp.rawTransaction);\n              tran.on('transactionHash', (txhash) => {console.log(\"Tx Hash: \"+ txhash);});\n```\n\n```text\nHTTP_PROXY\n```\n\n```text\nHTTPS_PROXY\n```\n\n```text\ncurl google.com\n```\n\n========================================\n\nComments:\n- Is ethersjs official module for ethereum like web3js?\n- Yes it is, here is a link to the documentation , it is really nice library. There is one more which I have heard that it is also good, but have never used, called ethereal-js.\n- @Anchal you are right. The function that changes the state needs to be signed. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":146,"estimatedTokens":1312}}199{"id":"stack-50437067","source":"stackoverflow","questionId":50437067,"title":"Truffle - Is There Any Way to Auto Generate Test Cases?","tags":["javascript","unit-testing","mocha.js","solidity","truffle"],"text":"Title: Truffle - Is There Any Way to Auto Generate Test Cases?\nTags: javascript, unit-testing, mocha.js, solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nIs there any way to auto-generate test-cases in Truffle?\n\nAs an example, the AutoFixture Library was helping me to auto-generate test-cases in xUnit. I'm looking for a similar functionality.\n\n========================================\n\nCode:\n```text\ndescribe('My tests', () => {\n  for (const testCase of TEST_CASES) {\n     it(`also works for ${testCase.name}`, () => {\n        // check something about testCase\n     });\n  }\n});\n```\n\n```text\nmocha\n```\n\n```text\nchai\n```\n\n```text\ndescribe\n```\n\n========================================\n\nComments:\n- Seems like there is nothing more automated than this. I accept this answer.","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":38,"estimatedTokens":194}}200{"id":"stack-50137954","source":"stackoverflow","questionId":50137954,"title":"Verify smart contract code deployed with Truffle","tags":["ethereum","solidity","truffle"],"text":"Title: Verify smart contract code deployed with Truffle\nTags: ethereum, solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nI am using Truffle to deploy a smart contract on the Rinkeby network. The smart contract contains an import of a library (Ownable).\n\nI am trying to verify the contract on Etherscan but I am not able to :(\n\nIt seems that Truffle \"flatten\" the contract code but I can't find the actual output used to compile.\n\nI checked the build folder and I can find the bytecode and deployedBytecode but not the \"flatten\" contract source.\n\nWhere can I find this information?\n\nDeployment on Rinkeby:\n\n```\nmichael$ truffle deploy --reset --network rinkeby\nUsing network 'rinkeby'.\n\nRunning migration: 1_initial_migration.js\n Replacing Migrations...\n ... 0xe179c58d10d66def5d26a06c89848b88c812458f1c2e92bcff40372e6c476f08\n Migrations: 0xa06c5370a513ad9aa25213db9610d77a9533c4c1\nSaving successful migration to network...\n ... 0xaa08dbc87a185613854689ffe408e3dc441344191c52194d835124e37a2a4fd1\nSaving artifacts...\nRunning migration: 2_deploy_contracts.js\n Replacing BlockBetGameRegistry...\n ... 0x9bc7e990dc4ef9dd87f5c69c8a65b0e22cbcda10102abc7067fcfb451ca429bc\n BlockBetGameRegistry: 0x7be5198a14ff47815a85adc47bb5f1da31d352e6\nSaving successful migration to network...\n ... 0xb942099bc2201d955bf60ce7ecba9edbe2f664b744f8543d43aa5588ff4d2f2f\nSaving artifacts...\n```\n\nContract code:\n\n```\npragma solidity 0.4.18;\n\nimport 'zeppelin-solidity/contracts/ownership/Ownable.sol';\n\ncontract BlockBetGameRegistry is Ownable {\n address[] public games;\n\n event eventGameAdded(address game);\n\n function addGame (address _contractAddress) onlyOwner public {\n require(_contractAddress != address(0));\n games.push(_contractAddress);\n eventGameAdded(_contractAddress);\n }\n\n function numberOfGames () view public returns (uint256) {\n return games.length;\n }\n}\n```\n\n========================================\n\nTop Answer:\nAs the other answer stated, there is no native Truffle functionality to help with this. However, the Truffle team did release plugin functionality early this year. So I created `truffle-plugin-verify` to automate Truffle contract verification on Etherscan.\n\n- Install the plugin with npm\n\n```\nnpm install truffle-plugin-verify\n```\n\n- Add the plugin to your `truffle.js` or `truffle-config.js` file\n\n```\nmodule.exports = {\n /* ... rest of truffle-config */\n\n plugins: [\n 'truffle-plugin-verify'\n ]\n}\n```\n\n- Generate an API Key on your Etherscan account (see the Etherscan website)\n\n- Add your Etherscan API key to your truffle config\n\n```\nmodule.exports = {\n /* ... rest of truffle-config */\n\n api_keys: {\n etherscan: 'MY_API_KEY'\n }\n}\n```\n\nAfter migrating your contract to to a public network, you are able to verify it on Etherscan by running:\n\n```\ntruffle run verify ContractName [--network networkName]\n```\n\nMore information can be found on the repository or in my article Automatically verify Truffle smart contracts on Etherscan.\n\n========================================\n\nCode:\n```text\nmichael$ truffle deploy --reset --network rinkeby\nUsing network 'rinkeby'.\n\nRunning migration: 1_initial_migration.js\n  Replacing Migrations...\n  ... 0xe179c58d10d66def5d26a06c89848b88c812458f1c2e92bcff40372e6c476f08\n  Migrations: 0xa06c5370a513ad9aa25213db9610d77a9533c4c1\nSaving successful migration to network...\n  ... 0xaa08dbc87a185613854689ffe408e3dc441344191c52194d835124e37a2a4fd1\nSaving artifacts...\nRunning migration: 2_deploy_contracts.js\n  Replacing BlockBetGameRegistry...\n  ... 0x9bc7e990dc4ef9dd87f5c69c8a65b0e22cbcda10102abc7067fcfb451ca429bc\n  BlockBetGameRegistry: 0x7be5198a14ff47815a85adc47bb5f1da31d352e6\nSaving successful migration to network...\n  ... 0xb942099bc2201d955bf60ce7ecba9edbe2f664b744f8543d43aa5588ff4d2f2f\nSaving artifacts...\n```\n\n```text\npragma solidity 0.4.18;\n\nimport 'zeppelin-solidity/contracts/ownership/Ownable.sol';\n\ncontract BlockBetGameRegistry is Ownable {\n  address[] public games;\n\n  event eventGameAdded(address game);\n\n  function addGame (address _contractAddress) onlyOwner public {\n    require(_contractAddress != address(0));\n    games.push(_contractAddress);\n    eventGameAdded(_contractAddress);\n  }\n\n  function numberOfGames () view public returns (uint256) {\n    return games.length;\n  }\n}\n```\n\n```sh\nnpm install truffle-plugin-verify\n```\n\n```js\nmodule.exports = {\n  /* ... rest of truffle-config */\n\n  plugins: [\n    'truffle-plugin-verify'\n  ]\n}\n```\n\n```js\nmodule.exports = {\n  /* ... rest of truffle-config */\n\n  api_keys: {\n    etherscan: 'MY_API_KEY'\n  }\n}\n```\n\n```text\ntruffle run verify ContractName [--network networkName]\n```\n\n```text\ntruffle-plugin-verify\n```\n\n```text\ntruffle.js\n```\n\n```text\ntruffle-config.js\n```\n\n========================================\n\nComments:\n- Just used this. So much awesome. Wish I had this back in 17/18 when I was actively writing/deploying/verifying contracts! Great job!","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":195,"estimatedTokens":1217}}201{"id":"stack-50299431","source":"stackoverflow","questionId":50299431,"title":"How to check if an address is an existing address on the ethereum blockchain?","tags":["ethereum","solidity","smartcontracts"],"text":"Title: How to check if an address is an existing address on the ethereum blockchain?\nTags: ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nWhat if I want to check in Solidity if an address exist on my Etherum blockchain? \n\nWhen looking at the solidity.readthedocs there is a function `balance` which could be used / misused to check if the address is valid / has balance:\n\n```\naddress x = 0x4e5d039c5516b69a4b6b1f006cbf4e10accb5cfa; // this is an example address which does not have valid checksum....\nif (x.balance > 0) // Return true when valid ??\n```\n\nIs this possible ?\n\nI found also some references on how-to-find-out-if-an-ethereum-address-is-a-contract, but I'm not sure that will help.\n\n========================================\n\nCode:\n```text\naddress x = 0x4e5d039c5516b69a4b6b1f006cbf4e10accb5cfa; // this is an example address which does not have valid checksum....\nif (x.balance > 0) // Return true when valid ??\n```\n\n```text\nbalance\n```\n\n========================================\n\nComments:\n- Thanks for your answer. Currently I've already built some account management functionality in my contract. And I've added require to the functions. So that should work for my functions, but I actually wanted to build login functionality on my API which only allows specific accounts to use the private blockchain.","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":34,"estimatedTokens":335}}202{"id":"stack-68611352","source":"stackoverflow","questionId":68611352,"title":"I want to find the substring (index 0 to 13) of bytes32 data and convert it into uint256 data","tags":["solidity"],"text":"Title: I want to find the substring (index 0 to 13) of bytes32 data and convert it into uint256 data\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI am stuck in solidity code. I want substring of below data and convert it to uint256 data\n\n```\nbytes32 hmacSha256 = 0xf83bf40815929b2448b230d51fa2eaa5b8ccffd87691db7e62bf817b2cbb56ad;\n```\n\nI want first 13 chars of above hmacSha256 data i.e. 'f83bf40815929' and its uint256 ie. 4366982094870825.\nI tried a number of things but to failure.\nCode and tried code is below:\n\n```\n// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @title Storage\n * @dev Store & retrieve value in a variable\n */\ncontract TestContract {\n \n \n function getsubstring1() public pure returns (string memory, uint256, string memory) {\n bytes32 hmacSha256 = 0xf83bf40815929b2448b230d51fa2eaa5b8ccffd87691db7e62bf817b2cbb56ad;\n bytes memory tempH = bytes(abi.encodePacked(hmacSha256));\n uint256 uintHash = uint256(hmacSha256);\n \n //I want below values as result. \n // _hs is first 13 chars of hmacSha256.\n //neither i could derive the _hs and nor _h from _hs.\n string memory _hs = '0xf83bf40815929'; \n uint256 _h = 0xf83bf40815929;\n \n //What I tried\n //bytes13 _hs1 = bytes13(hmacSha256); \n //but its returning 0xf83bf40815929b2448b230d51f which is double the length of expected value 0xf83bf40815929\n \n //string memory _hs1 = substring(string(abi.encodePacked(hmacSha256)), 0, 13); \n //above code is throwing error:Failed to decode output: null: invalid codepoint at offset 0; bad codepoint prefix\n \n // bytes memory _hs2 = tempH[0:13] ;\n //above giving error that its for bytes calldata dynamic array\n\n //uint256 _h1 = uint256(bytes(abi.encodePacked(_hs)));\n \n return (_hs, _h, _hs1);\n }\n \n function substring(string memory str, uint startIndex, uint endIndex) public pure returns (string memory) {\n bytes memory strBytes = bytes(str);\n bytes memory result = new bytes(endIndex-startIndex);\n for(uint i = startIndex; i < endIndex; i++) {\n result[i-startIndex] = strBytes[i];\n }\n return string(result);\n }\n}\n```\n\n========================================\n\nCode:\n```text\nbytes32 hmacSha256 = 0xf83bf40815929b2448b230d51fa2eaa5b8ccffd87691db7e62bf817b2cbb56ad;\n```\n\n```text\n// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @title Storage\n * @dev Store & retrieve value in a variable\n */\ncontract TestContract {\n    \n        \n    function getsubstring1() public pure returns (string memory, uint256, string memory) {\n        bytes32 hmacSha256 = 0xf83bf40815929b2448b230d51fa2eaa5b8ccffd87691db7e62bf817b2cbb56ad;\n        bytes memory tempH = bytes(abi.encodePacked(hmacSha256));\n        uint256 uintHash = uint256(hmacSha256);\n        \n        //I want below values as result. \n        // _hs is first 13 chars of hmacSha256.\n        //neither i could derive the _hs and nor _h from _hs.\n        string memory _hs = '0xf83bf40815929'; \n        uint256 _h = 0xf83bf40815929;\n        \n        //What I tried\n        //bytes13 _hs1 = bytes13(hmacSha256); \n        //but its returning 0xf83bf40815929b2448b230d51f which is double the length of expected value 0xf83bf40815929\n        \n        //string memory _hs1 = substring(string(abi.encodePacked(hmacSha256)), 0, 13); \n        //above code is throwing error:Failed to decode output: null: invalid codepoint at offset 0; bad codepoint prefix\n        \n        // bytes memory _hs2 = tempH[0:13] ;\n        //above giving error that its for bytes calldata dynamic array\n\n        //uint256 _h1 = uint256(bytes(abi.encodePacked(_hs)));\n        \n        return (_hs, _h, _hs1);\n    }\n    \n    function substring(string memory str, uint startIndex, uint endIndex) public pure returns (string memory) {\n        bytes memory strBytes = bytes(str);\n        bytes memory result = new bytes(endIndex-startIndex);\n        for(uint i = startIndex; i < endIndex; i++) {\n            result[i-startIndex] = strBytes[i];\n        }\n        return string(result);\n    }\n}\n```\n\n```text\npragma solidity ^0.8;\n\ncontract TestContract {\n    \n    function getsubstring() external pure returns (bytes7, uint256) {\n        bytes32 hmacSha256 = 0xf83bf40815929b2448b230d51fa2eaa5b8ccffd87691db7e62bf817b2cbb56ad;\n\n        bytes7 first7Bytes = bytes7(hmacSha256); // get the first 7 bytes (14 hex characters): 0xf83bf40815929b\n        bytes7 thirteenHexCharacters = first7Bytes >> 4; // move 4 bytes (1 hex character) to the right: 0x0f83bf40815929\n\n        bytes32 castBytes = bytes32(thirteenHexCharacters); // cast the bytes7 to bytes32 so that we can cast it to integer later\n        bytes32 castBytesMoved = castBytes >> 200; // move 200 bytes (50 hex characters) to the right: 0x000000000000000000000000000000000000000000000000000f83bf40815929\n        uint256 integerValue = uint256(castBytesMoved); // cast the bytes32 to uint256\n\n        return (thirteenHexCharacters, integerValue);\n    }\n}\n```\n\n```text\nbytes7: 0x0f83bf40815929\nuint256: 4366982094870825\n```\n\n========================================\n\nComments:\n- You saved my life @Petr, I tried my best but could never have reached to this solution without you help. Thanks alot.","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":149,"estimatedTokens":1282}}203{"id":"stack-71051955","source":"stackoverflow","questionId":71051955,"title":"How to transfer eth from an account to a contract?","tags":["blockchain","ethereum","solidity","smartcontracts"],"text":"Title: How to transfer eth from an account to a contract?\nTags: blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI'm fresh on solidity, when I use remix to test my contract, I want to transfer some eth from my account to the smart contract. I have tried this code, but it seems to transfer the eth from the contract but not my account.\n\n```\nfunction addStaker (uint _stakeAmount) public membership(master, msg.sender) returns(bool) {\n if(!members[msg.sender].alreadyExist) {\n Member memory newMember = Member(msg.sender, true);\n members[msg.sender] = newMember;\n bool sent = payable(address(this)).send(_stakeAmount);\n require(sent, \"invalid balance\");\n return true;\n } else {\n return false;\n }\n}\n```\n\nHow could I transfer eth from my account to the smart contract?\n\n========================================\n\nTop Answer:\nIf you want to implement a defi contract (since your function name is `addStaker`) that accepts staked coins from ERC20 tokens, the implementation is different. But if you just want to send money to contract from your metamask account, you have to mark the function `payable`.\n\n```\nfunction pay() public payable {\n // msg.value is the amount of wei sent with the message to the contract. \n // with this you are setting a minimum amount\n require(msg.value > .01 ether);\n // add your logic\n }\n```\n\n========================================\n\nCode:\n```text\nfunction addStaker (uint _stakeAmount) public membership(master, msg.sender) returns(bool) {\n    if(!members[msg.sender].alreadyExist) {\n        Member memory newMember = Member(msg.sender, true);\n        members[msg.sender] = newMember;\n        bool sent = payable(address(this)).send(_stakeAmount);\n        require(sent, \"invalid balance\");\n        return true;\n    } else {\n        return false;\n    }\n}\n```\n\n```text\nfunction addStaker() public payable {\n    require(msg.value == 1 ether);\n}\n```\n\n```text\nfunction pay() public payable {\n            //  msg.value is the amount of wei sent with the message to the contract. \n            // with this you are setting a minimum amount\n            require(msg.value > .01 ether);\n            // add your logic\n    }\n```\n\n```text\naddStaker\n```\n\n```text\npayable\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":76,"estimatedTokens":555}}204{"id":"stack-68697805","source":"stackoverflow","questionId":68697805,"title":"Solidity long string constants over multiple lines","tags":["ethereum","solidity"],"text":"Title: Solidity long string constants over multiple lines\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nJust wondering if there is a way to split long strings over more than one line in solidity? I can't find any kind of line continuation character, and compile error is thrown if you try to use two lines like this. Concatenating strings appears to be complex as well\n\n```\nstring memory s = \"This is a very long line of text which I would like to split over\n several lines\";\n```\n\nConcatenating strings appears to be complex as well. Do I just have to put the very long string on a very long line?\n\n========================================\n\nCode:\n```text\nstring memory s = \"This is a very long line of text which I would like to split over\n several lines\";\n```\n\n```text\npragma solidity ^0.8;\n\ncontract MyContract {\n    string s = \"This is a very \"\n        \"long line of text \"\n        \"which I would like to split \"\n        \"over several lines\";\n}\n```\n\n```text\npragma solidity ^0.8;\n\ncontract MyContract {\n    string s1 = \"Lorem\";\n    string s2 = \"ipsum\";\n    \n    function foo() external view returns (string memory) {\n        return string(abi.encodePacked(s1, \" \", s2));\n    }\n}\n```\n\n```text\npragma solidity ^0.8.12;\n\ncontract MyContract {\n    string s1 = \"Lorem\";\n    string s2 = \"ipsum\";\n\n    function foo() external view returns (string memory) {\n        return string.concat(s1, \" \", s2);\n    }\n}\n```\n\n```text\nabi.encodePacked()\n```\n\n```text\nbytes\n```\n\n```text\nbytes\n```\n\n```text\nstring\n```\n\n```text\nstring.concat()\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":78,"estimatedTokens":385}}205{"id":"stack-72475214","source":"stackoverflow","questionId":72475214,"title":"Solidity: Why use Initialize function instead of constructor?","tags":["architecture","state","ethereum","solidity","smartcontracts"],"text":"Title: Solidity: Why use Initialize function instead of constructor?\nTags: architecture, state, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI am doing audit smart contract where somebody prefer use initialize functions like this:\n\n```\nbool private isInit=false;\n string private hello;\n \n function init(string _hello) public onlyOwner {\n hello = _hello;\n isInit = true;\n } \n\n function doSomething() public {\n require(isInit, \"Wait for initialize\");\n ...doSomething\n }\n```\n\nCan you explain why the constructor was not used?\n\n========================================\n\nTop Answer:\nopenzeppelin docs explains:\n\n**The Constructor Caveat**\n\nIn Solidity, code that is inside a constructor or part of a global\nvariable declaration is not part of a deployed contract’s runtime\nbytecode. This code is executed only once, when the contract instance\nis deployed. As a consequence of this, the code within a logic\ncontract’s constructor will never be executed in the context of the\nproxy’s state. To rephrase, proxies are completely oblivious to the\nexistence of constructors. It’s simply as if they weren’t there for\nthe proxy.\n\nThe problem is easily solved though. Logic contracts should move the\ncode within the constructor to a regular 'initializer' function, and\nhave this function be called whenever the proxy links to this logic\ncontract. Special care needs to be taken with this initializer\nfunction so that it can only be called once, which is one of the\nproperties of constructors in general programming.\n\nhttps://i.sstatic.net/b9rvN.png\n\nIn proxy implementation, we want the `proxy` contract to store all the state because if in the future implementation changes, we will still have access to all transactions or other state variables. But if your implementation has a constructor, the state inside the implementation will be stored inside the implementation instead of `proxy`.\n\n`iNitialize` is just a function that set the state and it is called after the contract is deployed. when we calling it we initialize the state inside the `proxy` contract, but we need to make sure that this function is called only once.\n\n========================================\n\nCode:\n```text\nbool private isInit=false;\n string private hello;\n \n function init(string _hello) public onlyOwner {\n   hello = _hello;\n   isInit = true;\n } \n\n function doSomething() public {\n   require(isInit, \"Wait for initialize\");\n   ...doSomething\n }\n```\n\n```text\nfoo()\n```\n\n```text\nfoo()\n```\n\n```text\nmsg.sender\n```\n\n```text\nmsg.value\n```\n\n```text\nfoo()\n```\n\n```text\nfoo()\n```\n\n```text\nmsg.sender\n```\n\n```text\nproxy\n```\n\n```text\nproxy\n```\n\n```text\niNitialize\n```\n\n```text\nproxy\n```\n\n========================================\n\nComments:\n- great explanation & diagram!\n- great explanation thank you. Could you also add a short explanation for static call to complete your post?","metadata":{"transformedAt":"2026-08-18T18:33:36.129Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":120,"estimatedTokens":715}}206{"id":"stack-38109578","source":"stackoverflow","questionId":38109578,"title":"How do Smart Contracts handle multiple users and different storage?","tags":["blockchain","ethereum","solidity","smartcontracts"],"text":"Title: How do Smart Contracts handle multiple users and different storage?\nTags: blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI am experimenting with Smart Contracts on the Ethereum Blockchain. Let's say I have a contract, something like SimpleStorage.sol found in the Solidity documentation , that has a storage state accessible by anyone. As the link describes, \n\n anyone could just call set again with a different value and overwrite your number\n\nThis would result in problems, and the solution of restricting the accessibility of that function to specific accounts is not appropriate in my use case. In my contract, I want the data each account sets to later be accessible by a different predetermined account (think of a relationship where person A->B so B uses the data exclusively from A, and x->y where y uses the data exclusively from x. No overlap can exist where y can use A's data). From my understanding, there are 2 solutions to the problem:\n\n- Map addresses to each other and keep track of all the data within this single smart contract.\n\n- Have a smart contract \"template\" that the initial account would access, and generate a separate smart contract for each new account to simply hold data that interacts with the template.\n\nThe problem with **1** occurs when the relationship between accounts becomes more complex (map separate structs?) or a large volume of people try to store their information in the contract.\n\nThe problem with **2** is redundancy. Do I really need to produce a separate \"contract\" for every single person trying to access the main template? \n\nIf my question is vague, I can explain more but I am mostly looking for a conceptual answer. Most smart contract examples I have found are either extremely simple or unnecessarily complex and don't provide concrete use-case.\n\n========================================\n\nCode:\n```text\ncontract example {\n\n    // Define variable owner of the type address\n    address owner;\n\n    // this function is executed at initialization and sets the owner of the contract\n    function example() {\n        owner = msg.sender; \n    }\n\n    function doSomething() {\n        if (msg.sender == owner) {\n            // only the owner can do something, like storage access\n        }\n    }\n}\n```\n\n========================================\n\nComments:\n- Automating the **deployment** of a separate smart contract for every new user will be really cumbersome and will also increase application access time.","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":47,"estimatedTokens":625}}207{"id":"stack-74443594","source":"stackoverflow","questionId":74443594,"title":"How to slice bytes memory in solidity?","tags":["solidity","smartcontracts","inline-assembly"],"text":"Title: How to slice bytes memory in solidity?\nTags: solidity, smartcontracts, inline-assembly\nSource: Stack Overflow\n\nQuestion:\nIm trying to slice bytes such as\n\n```\nbytes memory bytesData = result[32:64];\n```\n\nand its throwing:\n\n```\nTypeError: Index range access is only supported for dynamic calldata arrays.\n```\n\nit works fine with calldata...\n\nwhat about memory?\n\n========================================\n\nTop Answer:\nAccording to the Solidity docs, slicing `memory` arrays is not supported for now. As you've said, it does work on `calldata bytes`. This answer on EthereumSE seems to agree.\n\nAccording to this question on EthSE, you *can* convert the `memory` to `calldata` with a workaround.\n\n========================================\n\nCode:\n```text\nbytes memory bytesData = result[32:64];\n```\n\n```text\nTypeError: Index range access is only supported for dynamic calldata arrays.\n```\n\n```js\npragma solidity >=0.8.0 <0.9.0;\n\n\nlibrary BytesLib {  \n  function slice(\n        bytes memory _bytes,\n        uint256 _start,\n        uint256 _length\n    )\n        internal\n        pure\n        returns (bytes memory)\n    {\n        require(_length + 31 >= _length, \"slice_overflow\");\n        require(_bytes.length >= _start + _length, \"slice_outOfBounds\");\n\n        bytes memory tempBytes;\n\n        // Check length is 0. `iszero` return 1 for `true` and 0 for `false`.\n        assembly {\n            switch iszero(_length)\n            case 0 {\n                // Get a location of some free memory and store it in tempBytes as\n                // Solidity does for memory variables.\n                tempBytes := mload(0x40)\n\n                // Calculate length mod 32 to handle slices that are not a multiple of 32 in size.\n                let lengthmod := and(_length, 31)\n\n                // tempBytes will have the following format in memory: <length><data>\n                // When copying data we will offset the start forward to avoid allocating additional memory\n                // Therefore part of the length area will be written, but this will be overwritten later anyways.\n                // In case no offset is require, the start is set to the data region (0x20 from the tempBytes)\n                // mc will be used to keep track where to copy the data to.\n                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))\n                let end := add(mc, _length)\n\n                for {\n                    // Same logic as for mc is applied and additionally the start offset specified for the method is added\n                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)\n                } lt(mc, end) {\n                    // increase `mc` and `cc` to read the next word from memory\n                    mc := add(mc, 0x20)\n                    cc := add(cc, 0x20)\n                } {\n                    // Copy the data from source (cc location) to the slice data (mc location)\n                    mstore(mc, mload(cc))\n                }\n\n                // Store the length of the slice. This will overwrite any partial data that \n                // was copied when having slices that are not a multiple of 32.\n                mstore(tempBytes, _length)\n\n                // update free-memory pointer\n                // allocating the array padded to 32 bytes like the compiler does now\n                // To set the used memory as a multiple of 32, add 31 to the actual memory usage (mc) \n                // and remove the modulo 32 (the `and` with `not(31)`)\n                mstore(0x40, and(add(mc, 31), not(31)))\n            }\n            // if we want a zero-length slice let's just return a zero-length array\n            default {\n                tempBytes := mload(0x40)\n                // zero out the 32 bytes slice we are about to return\n                // we need to do it because Solidity does not garbage collect\n                mstore(tempBytes, 0)\n\n                // update free-memory pointer\n                // tempBytes uses 32 bytes in memory (even when empty) for the length.\n                mstore(0x40, add(tempBytes, 0x20))\n            }\n        }\n\n        return tempBytes;\n    }\n}\n```\n\n```text\nmemory\n```\n\n```text\ncalldata bytes\n```\n\n```text\nmemory\n```\n\n```text\ncalldata\n```\n\n========================================\n\nComments:\n- is there a way around it for data returned from `.staticcall`?\n- Unfortunately I'm not very familiar with `staticcall`. But I've edited my answer with a link for converting `memory` to `calldata` which might help you along.","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":138,"estimatedTokens":1138}}208{"id":"stack-71941928","source":"stackoverflow","questionId":71941928,"title":"How to transfer ERC20 tokens to another address using solidity?","tags":["solidity","polygon","erc20"],"text":"Title: How to transfer ERC20 tokens to another address using solidity?\nTags: solidity, polygon, erc20\nSource: Stack Overflow\n\nQuestion:\nI create ERC20 tokens, and i want to transfer my tokens to another address.\n\nI have two accounts in my metamask.(Account A/B)\n\nMy ERC20 code's here (I deployed and save tokens in **account A**)\n\n```\npragma solidity ^0.8.0;\n// SPDX-License-Identifier: MIT\n\nimport \"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol\";\n\ncontract MyToken is ERC20 {\n constructor(string memory name, string memory symbol) ERC20(name,symbol) {\n // mint 1000 token\n _mint(msg.sender, 1000*10**uint(decimals()));\n }\n}\n```\n\n**Question : how can I transfer my ERC20 tokens from the current address to another? (A->B)**\n\nI use this code in **account A**, but not work.\n\n```\npragma solidity ^0.8.7;\n// SPDX-License-Identifier: MIT\n\nimport \"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol\";\n\ncontract TokenTransfer {\n IERC20 _token;\n\n // token = MyToken's contract address\n constructor(address token) public {\n _token = IERC20(token);\n }\n \n // to = Account B's address\n function stake(address to, uint amount) public {\n _token.approve(address(this), amount);\n \n require(_token.allowance(address(this), address(this)) >= amount);\n _token.transferFrom(msg.sender, to, amount);\n }\n}\n```\n\nerror message\n\n```\ntransact to TokenTransfer.stake errored: Internal JSON-RPC error.\n{\n \"code\": 3,\n \"message\": \"execution reverted: ERC20: insufficient allowance\",\n \"data\": \"0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001d45524332303a20696e73756666696369656e7420616c6c6f77616e6365000000\"\n}\n```\n\nhow to fix it?\n\n========================================\n\nCode:\n```text\npragma solidity ^0.8.0;\n// SPDX-License-Identifier: MIT\n\nimport \"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol\";\n\ncontract MyToken is ERC20 {\n    constructor(string memory name, string memory symbol) ERC20(name,symbol) {\n        // mint 1000 token\n        _mint(msg.sender, 1000*10**uint(decimals()));\n    }\n}\n```\n\n```text\npragma solidity ^0.8.7;\n// SPDX-License-Identifier: MIT\n\nimport \"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol\";\n\ncontract TokenTransfer {\n    IERC20 _token;\n\n    // token = MyToken's contract address\n    constructor(address token) public {\n        _token = IERC20(token);\n    }\n    \n    // to = Account B's address\n    function stake(address to, uint amount) public {\n        _token.approve(address(this), amount);\n        \n        require(_token.allowance(address(this), address(this)) >= amount);\n        _token.transferFrom(msg.sender, to, amount);\n    }\n}\n```\n\n```text\ntransact to TokenTransfer.stake errored: Internal JSON-RPC error.\n{\n  \"code\": 3,\n  \"message\": \"execution reverted: ERC20: insufficient allowance\",\n  \"data\": \"0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001d45524332303a20696e73756666696369656e7420616c6c6f77616e6365000000\"\n}\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.7;\n\nimport \"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol\";\n\ncontract TokenTransfer {\n    IERC20 _token;\n\n    // token = MyToken's contract address\n    constructor(address token) {\n        _token = IERC20(token);\n    }\n\n    // Modifier to check token allowance\n    modifier checkAllowance(uint amount) {\n        require(_token.allowance(msg.sender, address(this)) >= amount, \"Error\");\n        _;\n    }\n\n    // In your case, Account A must to call this function and then deposit an amount of tokens \n    function depositTokens(uint _amount) public checkAllowance(_amount) {\n        _token.transferFrom(msg.sender, address(this), _amount);\n    }\n    \n    // to = Account B's address\n    function stake(address to, uint amount) public {\n        _token.transfer(to, amount);\n    }\n\n    // Allow you to show how many tokens owns this smart contract\n    function getSmartContractBalance() external view returns(uint) {\n        return _token.balanceOf(address(this));\n    }\n    \n}\n```\n\n```text\n_token.approve(address(this), amount)\n```\n\n```text\napprove()\n```\n\n```text\n_token.transferFrom(msg.sender, to, amount);\n```\n\n```text\nmsg.sender\n```\n\n```text\ntransfer()\n```\n\n```text\ntransferFrom()\n```\n\n```text\ntransfer()\n```\n\n========================================\n\nComments:\n- It's just what I was looking for! Thanks Antonio. I'm trying to use visual code + remix + ganache and if I run this code, the GetSmartContractBalance function gives me error \"there are errors sending the data\". Unfortunately the error message doesn't help. I entered the address of a known token (TUSD,...) but without success. Do you have suggestions? thanks Lorenzo\n- Please, you open another thread on StackOverflow with adding more details about your issue.","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":187,"estimatedTokens":1266}}209{"id":"stack-70459922","source":"stackoverflow","questionId":70459922,"title":"ParserError: Source file requires different compiler version","tags":["python","ethereum","solidity","smartcontracts","brownie"],"text":"Title: ParserError: Source file requires different compiler version\nTags: python, ethereum, solidity, smartcontracts, brownie\nSource: Stack Overflow\n\nQuestion:\nI tried all that you mentioned in the discussion here (in other questions) and at https://github.com/smartcontractkit/full-blockchain-solidity-course-py/discussions/522 , however it is not solving the issue for me, I also noticed that the current compiler version remains (current compiler is 0.6.12+commit.27d51765.Windows.msvc). But when I right click and select Solidty:Compiler information, it shows 0.8.0.\n\n**from output:**\n\n```\nRetrieving compiler information:\nCompiler using remote version: 'v0.8.0+commit.c7dfd78e', solidity version: 0.8.0+commit.c7dfd78e.Emscripten.clang\n```\n\nNot sure if that is related to the issue I face. Anyways starting with the problem I see when running brownie compile. I get the error below:\n\n**error in terminal:**\n\n```\nPS D:\\Python projects\\Solidity dev\\demo\\smartcontract-lottery> brownie compile\nINFO: Could not find files for the given pattern(s).\nBrownie v1.17.2 - Python development framework for Ethereum\n\nCompiling contracts...\n Solc version: 0.6.12\n Optimizer: Enabled Runs: 200\n EVM Version: Istanbul\nCompilerError: solc returned the following errors:\n\nC:/Users/rosne/.brownie/packages/OpenZeppelin/openzeppelin-contracts@4.3.0/contracts/access/Ownable.sol:3:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version\npragma solidity ^0.8.0;\n^---------------------^\n\nC:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.8/VRFConsumerBase.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version\npragma solidity ^0.8.0;\n^---------------------^\n\nPS D:\\Python projects\\Solidity dev\\demo\\smartcontract-lottery>\n```\n\n**My .sol file is Lottery.sol:**\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity ^0.6.0;\n\nimport \"@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@chainlink/contracts/src/v0.8/VRFConsumerBase.sol\";\n\ncontract Lottery is VRFConsumerBase, Ownable {\n uint256 usdEntryFee;\n address payable[] public players;\n address payable public recentWinner;\n uint256 public randomness;\n AggregatorV3Interface internal ethUsdPriceFeed;\n enum LOTTERY_STATE {\n OPEN,\n CLOSED,\n CALCULATING_WINNER\n }\n\n LOTTERY_STATE public lottery_state;\n uint256 public fee;\n bytes32 public keyhash;\n\n constructor(\n address _priceFeedAddress,\n address _vrfCoordinator,\n address _link,\n uint256 _fee,\n bytes32 _keyhash\n ) public VRFConsumerBase(_vrfCoordinator, _link) {\n usdEntryFee = 50 * (10**18);\n ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);\n lottery_state = LOTTERY_STATE.CLOSED;\n fee = _fee;\n keyhash = _keyhash;\n }\n\n function enter() public payable {\n //$50 min\n require(lottery_state == LOTTERY_STATE.OPEN);\n require(msg.value >= getEntranceFee(), \"Not enough ETH!\");\n players.push(payable(msg.sender));\n }\n\n function getEntranceFee() public view returns (uint256) {\n (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();\n uint256 adjustedPrice = uint256(price) * 10**12; //18 decimals\n //$50, 2000 ETH\n //50/2000\n //50*10000/2000\n uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice;\n return costToEnter;\n }\n\n function startLottery() public onlyOwner {\n require(\n lottery_state == LOTTERY_STATE.CLOSED,\n \"cant start a new lottery yet\"\n );\n lottery_state = LOTTERY_STATE.OPEN;\n }\n\n function endLottery() public onlyOwner {\n lottery_state = LOTTERY_STATE.CALCULATING_WINNER;\n bytes32 requestId = requestRandomness(keyhash, fee);\n }\n\n function FulfillRandomness(bytes32 _requestId, uint256 _randomness)\n internal\n override\n {\n require(\n lottery_state == LOTTERY_STATE.CALCULATING_WINNER,\n \"you arent there yet!\"\n );\n\n require(_randomness > 0, \"random not found\");\n uint256 indexOfWinner = _randomness % players.length;\n recentWinner = players[indexOfWinner];\n recentWinner.transfer(address(this).balance);\n\n //reset\n\n players = new address payable[](0);\n lottery_state = LOTTERY_STATE.CLOSED;\n randomness = _randomness;\n }\n}\n```\n\nI also tried to google some solutions so my settings.json file is a bit different but that didnt help too.\n\n**settings.json:**\n\n```\n{\n \"solidity.compileUsingRemoteVersion\": \"v0.8.0+commit.c7dfd78e\",\n \"solidity.defaultCompiler\": \"remote\",\n \"solidity.compileUsingLocalVersion\": \"d:\\\\Python projects\\\\Solidity dev\\\\demo\\\\smartcontract-lottery\\\\soljson-v0.8.0+commit.c7dfd78e.js\"\n // \"solidity.compileUsingRemoteVersion\": \"v0.7.4+commit.3f05b770\",\n // \"solidity.enableLocalNodeCompiler\": false\n}\n```\n\nIn the brownie-config.yaml, I tried all the versions of openzepplin contracts too from old to latest (4.4.0, 4.3.0,4.3.2 etc), but same error.\n\n**brownie-config.yaml**\n\n```\ndependencies:\n - smartcontractkit/chainlink-brownie-contracts@1.1.1\n - OpenZeppelin/openzeppelin-contracts@4.3.0\ncompiler:\n solc:\n remappings:\n - '@chainlink=smartcontractkit/chainlink-brownie-contracts@0.2.1'\n - '@openzeppelin=OpenZeppelin/openzeppelin-contracts@4.3.0'\nnetworks:\n mainnet-fork:\n eth_usd_price_feed: '0xaEA2808407B7319A31A383B6F8B60f04BCa23cE2'\n```\n\nI also tried to change the compiler in lottery.sol file with\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n```\n\nNow I get a different error.\nCompletely lost here :(\n\n**terminal:**\n\n```\nINFO: Could not find files for the given pattern(s).\nBrownie v1.17.2 - Python development framework for Ethereum\n\nCompiling contracts...\n Solc version: 0.8.11\n Optimizer: Enabled Runs: 200\n EVM Version: Istanbul\nCompilerError: solc returned the following errors:\n\nParserError: Source file requires different compiler version (current compiler is 0.8.11+commit.d7f03943.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version\n --> C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol:2:1:\n |\n2 | pragma solidity ^0.6.0;\n | ^^^^^^^^^^^^^^^^^^^^^^^\n\nPS D:\\Python projects\\Solidity dev\\demo\\smartcontract-lottery>\n```\n\nI am very new to programing in solidity and this is the first course I am following, I don't want to give up so easily, any help is much appreciated.\n\n========================================\n\nTop Answer:\nThe solution to the error is\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity >=0.6.0 Use this instead, hope this helps\n\n========================================\n\nCode:\n```text\nRetrieving compiler information:\nCompiler using remote version: 'v0.8.0+commit.c7dfd78e', solidity version: 0.8.0+commit.c7dfd78e.Emscripten.clang\n```\n\n```text\nPS D:\\Python projects\\Solidity dev\\demo\\smartcontract-lottery> brownie compile\nINFO: Could not find files for the given pattern(s).\nBrownie v1.17.2 - Python development framework for Ethereum\n\nCompiling contracts...\n  Solc version: 0.6.12\n  Optimizer: Enabled  Runs: 200\n  EVM Version: Istanbul\nCompilerError: solc returned the following errors:\n\nC:/Users/rosne/.brownie/packages/OpenZeppelin/openzeppelin-contracts@4.3.0/contracts/access/Ownable.sol:3:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version\npragma solidity ^0.8.0;\n^---------------------^\n\nC:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.8/VRFConsumerBase.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version\npragma solidity ^0.8.0;\n^---------------------^\n\nPS D:\\Python projects\\Solidity dev\\demo\\smartcontract-lottery>\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.6.0;\n\nimport \"@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@chainlink/contracts/src/v0.8/VRFConsumerBase.sol\";\n\ncontract Lottery is VRFConsumerBase, Ownable {\n    uint256 usdEntryFee;\n    address payable[] public players;\n    address payable public recentWinner;\n    uint256 public randomness;\n    AggregatorV3Interface internal ethUsdPriceFeed;\n    enum LOTTERY_STATE {\n        OPEN,\n        CLOSED,\n        CALCULATING_WINNER\n    }\n\n    LOTTERY_STATE public lottery_state;\n    uint256 public fee;\n    bytes32 public keyhash;\n\n    constructor(\n        address _priceFeedAddress,\n        address _vrfCoordinator,\n        address _link,\n        uint256 _fee,\n        bytes32 _keyhash\n    ) public VRFConsumerBase(_vrfCoordinator, _link) {\n        usdEntryFee = 50 * (10**18);\n        ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);\n        lottery_state = LOTTERY_STATE.CLOSED;\n        fee = _fee;\n        keyhash = _keyhash;\n    }\n\n    function enter() public payable {\n        //$50 min\n        require(lottery_state == LOTTERY_STATE.OPEN);\n        require(msg.value >= getEntranceFee(), \"Not enough ETH!\");\n        players.push(payable(msg.sender));\n    }\n\n    function getEntranceFee() public view returns (uint256) {\n        (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();\n        uint256 adjustedPrice = uint256(price) * 10**12; //18 decimals\n        //$50, 2000 ETH\n        //50/2000\n        //50*10000/2000\n        uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice;\n        return costToEnter;\n    }\n\n    function startLottery() public onlyOwner {\n        require(\n            lottery_state == LOTTERY_STATE.CLOSED,\n            \"cant start a new lottery yet\"\n        );\n        lottery_state = LOTTERY_STATE.OPEN;\n    }\n\n    function endLottery() public onlyOwner {\n        lottery_state = LOTTERY_STATE.CALCULATING_WINNER;\n        bytes32 requestId = requestRandomness(keyhash, fee);\n    }\n\n    function FulfillRandomness(bytes32 _requestId, uint256 _randomness)\n        internal\n        override\n    {\n        require(\n            lottery_state == LOTTERY_STATE.CALCULATING_WINNER,\n            \"you arent there yet!\"\n        );\n\n        require(_randomness > 0, \"random not found\");\n        uint256 indexOfWinner = _randomness % players.length;\n        recentWinner = players[indexOfWinner];\n        recentWinner.transfer(address(this).balance);\n\n        //reset\n\n        players = new address payable[](0);\n        lottery_state = LOTTERY_STATE.CLOSED;\n        randomness = _randomness;\n    }\n}\n```\n\n```text\n{\n    \"solidity.compileUsingRemoteVersion\": \"v0.8.0+commit.c7dfd78e\",\n    \"solidity.defaultCompiler\": \"remote\",\n    \"solidity.compileUsingLocalVersion\": \"d:\\\\Python projects\\\\Solidity dev\\\\demo\\\\smartcontract-lottery\\\\soljson-v0.8.0+commit.c7dfd78e.js\"\n    // \"solidity.compileUsingRemoteVersion\": \"v0.7.4+commit.3f05b770\",\n    // \"solidity.enableLocalNodeCompiler\": false\n}\n```\n\n```text\ndependencies:\n  - smartcontractkit/chainlink-brownie-contracts@1.1.1\n  - OpenZeppelin/openzeppelin-contracts@4.3.0\ncompiler:\n  solc:\n    remappings:\n      - '@chainlink=smartcontractkit/chainlink-brownie-contracts@0.2.1'\n      - '@openzeppelin=OpenZeppelin/openzeppelin-contracts@4.3.0'\nnetworks:\n  mainnet-fork:\n    eth_usd_price_feed: '0xaEA2808407B7319A31A383B6F8B60f04BCa23cE2'\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n```\n\n```text\nINFO: Could not find files for the given pattern(s).\nBrownie v1.17.2 - Python development framework for Ethereum\n\nCompiling contracts...\n  Solc version: 0.8.11\n  Optimizer: Enabled  Runs: 200\n  EVM Version: Istanbul\nCompilerError: solc returned the following errors:\n\nParserError: Source file requires different compiler version (current compiler is 0.8.11+commit.d7f03943.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version\n --> C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol:2:1:\n  |\n2 | pragma solidity ^0.6.0;\n  | ^^^^^^^^^^^^^^^^^^^^^^^\n\nPS D:\\Python projects\\Solidity dev\\demo\\smartcontract-lottery>\n```\n\n```text\nfunction FulfillRandomness(bytes32 _requestId, uint256 _randomness)\n        internal\n        override\n```\n\n```text\npragma solidity >=0.4.22 <0.9.0;\n```\n\n```text\npragma solidity >=0.4.22 <0.8.0;\n```\n\n```text\nopenzeppelin\n```\n\n```text\npragma solidity ^0.8.0;\n```\n\n```text\nopenzeppelin\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity >=0.6.0 <0.9.0;\n```\n\n```text\ncompiler:\n solc:\n  version: '0.8.4'\n```\n\n```text\npragma\n```\n\n```text\n.sol\n```\n\n```text\nbrownie-config.yaml\n```\n\n========================================\n\nComments:\n- I also noticed that in the brownie-config.yaml file :smartcontractkit/chainlink-brownie-contracts@1.1.1 was written differently in dependencies and remappings. However, after making both of them the same it still has the same errors. I am trying several things to try and see if I can match the versions somehow. I think I cannot proceed ahead if the code doesn't compile right?\n- Please trim your code to make it easier to find your problem. these guidelines to create a minimal reproducible example.\n- I managed to find the issue, it was because the function name should be fullfillRandomness instead of FullfillRandomness. So much problem because of a capital F. function FulfillRandomness(bytes32 _requestId, uint256 _randomness) internal override","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":431,"estimatedTokens":3423}}210{"id":"stack-69894001","source":"stackoverflow","questionId":69894001,"title":"How to generate arbitrary wallet seeded with eth in hardhat tests using ethers.js?","tags":["ethereum","solidity","ethers.js","hardhat"],"text":"Title: How to generate arbitrary wallet seeded with eth in hardhat tests using ethers.js?\nTags: ethereum, solidity, ethers.js, hardhat\nSource: Stack Overflow\n\nQuestion:\nI'm currently trying to run a test in hardhat/waffle that requires hundreds of unique wallets to call a contract, using new ethers.Wallet.createRandom(). However, none of these wallets are supplied with eth, so I can't call/send transactions with them.\n\nWhat would be the simplest/most effective way to supply an arbitrary amount of randomly generated wallets with eth? Thanks!\n\n========================================\n\nTop Answer:\nI think you'll probably want to use the hardhat network method hardhat_setBalance, the docs use an example like this:\n\n```\nawait network.provider.send(\"hardhat_setBalance\", [\n \"\",\n \"0x1000\", # 4096 wei\n]);\n```\n\nI'm not developing in javascript though, but I've been doing something similar in python using web3.py and eth-account with code like this:\n\n```\nfrom web3 import Web3\nfrom eth_account import Account\n\nchain = Web3(HTTPProvider(\"http://127.0.0.1:8545\"))\n\nacct = Account.create('')\naddress = Web3.toChecksumAddress(acct.address)\nprint(chain.eth.get_balance(address)) # 0 wei\n\n# add a balance of eth tokens to the address\nchain.provider.make_request(\"hardhat_setBalance\", [address, \"0x1000\"])\n\nprint(chain.eth.get_balance(address)) # 4096 wei\n```\n\n========================================\n\nCode:\n```text\nmodule.exports = {\n    networks: {\n        hardhat: {\n            accounts: {\n                count: 1000\n            }\n        }\n    }\n}\n```\n\n```text\naccounts\n```\n\n```text\ncount\n```\n\n```text\nhardhat\n```\n\n```text\nnew ethers.Wallet.createRandom()\n```\n\n```text\nconst wallet = ethers.Wallet.createRandom().connect(provider);\n```\n\n```text\nawait network.provider.send(\"hardhat_setBalance\", [\n  \"<ACCOUNT ADDRESS>\",\n  \"0x1000\", # 4096 wei\n]);\n```\n\n```text\nfrom web3 import Web3\nfrom eth_account import Account\n\n\nchain = Web3(HTTPProvider(\"http://127.0.0.1:8545\"))\n\nacct = Account.create('<RANDOM VALUE>')\naddress = Web3.toChecksumAddress(acct.address)\nprint(chain.eth.get_balance(address)) # 0 wei\n\n# add a balance of eth tokens to the address\nchain.provider.make_request(\"hardhat_setBalance\", [address, \"0x1000\"])\n\nprint(chain.eth.get_balance(address)) # 4096 wei\n```\n\n```js\n// Generates random wallet and connects it to hardhat provider, sets balance to 100 ETH\nexport async function generateRandomWallet(): Promise<Wallet> {\n   // Connect to Hardhat Provider\n   const wallet = ethers.Wallet.createRandom().connect(ethers.provider);\n   // Set balance\n   await ethers.provider.send(\"hardhat_setBalance\", [\n       wallet.address\n       \"0x56BC75E2D63100000\", // 100 ETH\n   ]);\n   return wallet;\n}\n```\n\n========================================\n\nComments:\n- This allows you to create more default wallets, which will all be pre-funded with Ether, but Jaymon's answer illustrates how to set the account balance for even new random wallets that you create, once you connect them to the Hardhat provider, as shown in Ricardo Martins' answer.\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- I was originally using this implementation, but I had trouble connecting the provider. I solved my problem by configuring the hardhat settings (see below).\n- This is the correct way to create wallets and connect them with the ethers provider (use `ethers.provider` in the place of `provider`). However the correct answer for how to fund these wallets was given by Jaymon.","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":119,"estimatedTokens":915}}211{"id":"stack-49239451","source":"stackoverflow","questionId":49239451,"title":"Write smart contract using Solidity over Intellij","tags":["intellij-idea","solidity"],"text":"Title: Write smart contract using Solidity over Intellij\nTags: intellij-idea, solidity\nSource: Stack Overflow\n\nQuestion:\nI'm trying to write a basic smart contract using solidity over Intellij.\nI've installed Intellij. I've installed the intellij-solidity plugin and started Intellij --> Create new Project.\nI expect to see an option that relates to solidity but can't see such.\n\nHow do I start using Solidity over Intellij?\n\nhttps://i.sstatic.net/QGY1R.png\n\n========================================\n\nTop Answer:\nIntellij-Solidity\ngives only highlight syntax\nand no autocomplete\n\n========================================\n\nComments:\n- Just to add to this. It is possible to create .sol files (with the ethereum logo as a file icon) just not entire projects.","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":24,"estimatedTokens":189}}212{"id":"stack-67930178","source":"stackoverflow","questionId":67930178,"title":"Must all nodes on the blockchain execute every smart contract function cal?","tags":["ethereum","solidity"],"text":"Title: Must all nodes on the blockchain execute every smart contract function cal?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI understand why it's important that all nodes on the Ethereum mainnet must execute any smart contract function call which changes the internal state of the contract or the chain. (For example, transfers from one account to another ec.)\n\nWhat I'm wondering is, if its true that every node must execute **every** function called on any smart contract, even if the function doesn't result in a state change.\n\nFor example, if an ERC721 smart contract has a function \"getName()\" which just returns the name of the artwork the NFT represents which is stored in the NFt. Let's say joe connects to the network, and wants executes getName() on a contract. Does that mean that all 9,000 nodes end up spinning cycles executing getName(), even though Joe only needs it to be executed once? Does the gas cost of running \"getName()\" compensate each of the nodes for the overhead of running \"getName()\"? If that is true (that every node gets paid) will gas get even more expensive as more nodes join the pool?\n\nIs one of the reasons gas prices are high is because of the inefficiency of every node having to execute every function called on a smart contract, even those that have no effect on state?\n\nIf so it would seem to be a very (and perhaps unnecessarily) expensive proposition to execute a computationally intensive but \"pure\" (no side effects) function on Ethereum, right?\n\nThanks. apologies for the possibly naive question!\n\n========================================\n\nCode:\n```text\nstring name;\n\nfunction getName() external view returns (string memory) {\n    // reads from storage, stores to memory, returns from memory\n    return name;\n}\n```\n\n```text\nstring name;\n\nfunction setName(string memory _name) external {\n    // reads from memory, stores to storage\n    name = _name;\n}\n```\n\n```text\ngetName()\n```\n\n========================================\n\nComments:\n- 1/That's extremely helpful Petr, thank you. A couple of ups. 1/ is a node paid for the execution of a call? what if a smart contract provided a service which was computationally expensive (say, a fluid dynamics problem) but made no state changes? If the service function was requested as a call would the single node just have to bear the cost of running that for free. Could gas be required?).\n- 2/ On the other hand, lets say there was a smart contract which provided an answer to a computationally intensive problem for a fee paid by the caller. Could the function be constructed in some way where the hard work was done by a signle node, but the fee transaction is propagated to all nodes>\n- 1) Node is not paid for an execution of a call. At least not in the form of \"gas fees\" in the native currency of the network (ETH on Ethereum network, BNB on BSC network, etc.) that is usual for transactions. But there might be another forms of payment. E.g. node provider Infura offers limited free plan and paid plans with higher limits. But the limits apply only to a number of requests so they probably calculate the limits based on some average computational cost.\n- 2) I haven't seen this approach on the public networks, and since all nodes are considered equal it's most likely impossible on a public network. It might be possible to set up using a private network (e.g. Hyperledger Fabric) with a set of rules defining execution on node A and validation on node B, or no validation at all.\n- thanks for your great answer. you said above, If Joe requests a call, getName() is executed only on one node (where Joe is connected to). is there a possibility that the node is a malicious one and send fake data as response to the getName() call, if so, how to prevent it.\n- @TylerXue Yes, a malicious node is a possibility. If you can't trust a single 3rd party node, you can either request the data from multiple nodes to lower the risk of receiving data from a malicious node, or you can run your own node.","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":51,"estimatedTokens":1001}}213{"id":"stack-69931208","source":"stackoverflow","questionId":69931208,"title":"Solidity inheritance override public constant","tags":["inheritance","solidity"],"text":"Title: Solidity inheritance override public constant\nTags: inheritance, solidity\nSource: Stack Overflow\n\nQuestion:\nSimple code:\n\n```\npragma solidity 0.8.4;\n\ncontract A {\n uint256 public constant X = 1;\n}\n\ncontract B is A {\n uint256 override public constant X = 2;\n}\n```\n\nUnfortunately that errors on compile:\n\n```\nTypeError: Cannot override public state variable.\n --> contracts/mocks/StakePoolMock.sol:4:5:\n |\n4 | uint256 public constant X = 1;\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nNote: Overriding public state variable is here:\n --> contracts/mocks/StakePoolMock.sol:8:5:\n |\n8 | uint256 override public constant X = 2;\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n```\n\nIs there any way to override public constants?\n\n========================================\n\nTop Answer:\n**Short answer**: No. You can only override functions in Solidity.\n\n**Long answer**:\n\nInterestingly, since the compiler generates getter functions for public state variables (including constants), you can actually use them to override functions (Contracts > Inheritance > Function Overriding):\n\nPublic state variables can override external functions if the parameter and return types of the function matches the getter function of the variable\n\nWhile public state variables can override external functions, they themselves cannot be overridden.\n\nSo if `X` were a function, this would be completely fine:\n\n```\ncontract A {\n function X() external virtual returns (uint256) {\n return 1;\n }\n}\n\ncontract B is A {\n uint256 public constant override X = 2;\n}\n```\n\nYou cannot do it the other way around though and the reason is that this might require removing the slot already reserved for the state variable. The base contract might contain code that accesses that slot through the variable so it would not be safe for the compiler to allow that.\n\nHowever this reasoning does not apply to constants - they do not occupy any storage. It's also not a problem when overriding a variable with a variable or a constant with a constant. This seems to be a purely syntactical limitation so if you have a strong use case, you might try submitting a feature request. The thing is - is it really a constant if you want to change its value, even if it's only once? I think that in most languages this would not work. You might be able to shadow the constant with a new one but not really override in the full sense of the word - i.e. in such a way that functions called from the base class would see the changed value.\n\nYour use case might be better served with an `immutable`, which is a kind of \"runtime constant\". Unlike a compile-time constant, it's not subject to all the same optimizations the compiler can perform on constants and cannot be used in contexts where a true constant is required (e.g. you cannot use it to define the length of a static array) but it cannot be changed at runtime and does not occupy any storage so it might still fit your requirements. It can be assigned to only once, at construction time and the result is then hard-coded in the bytecode produced by the constructor.\n\n```\ncontract A {\n uint256 public immutable X;\n\n constructor(uint256 _x) {\n X = _x;\n }\n}\n\ncontract B is A(2) {}\n```\n\n========================================\n\nCode:\n```text\npragma solidity 0.8.4;\n\ncontract A {\n    uint256 public constant X = 1;\n}\n\ncontract B is A {\n    uint256 override public constant X = 2;\n}\n```\n\n```text\nTypeError: Cannot override public state variable.\n --> contracts/mocks/StakePoolMock.sol:4:5:\n  |\n4 |     uint256 public constant X = 1;\n  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nNote: Overriding public state variable is here:\n --> contracts/mocks/StakePoolMock.sol:8:5:\n  |\n8 |     uint256 override public constant X = 2;\n  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n```\n\n```text\nfunction changeValue(uint256 newValue) public onlyOwner {\n    X = newValue;\n}\n```\n\n```text\nX\n```\n\n```solidity\ncontract A {\n    function X() external virtual returns (uint256) {\n        return 1;\n    }\n}\n\ncontract B is A {\n    uint256 public constant override X = 2;\n}\n```\n\n```solidity\ncontract A {\n    uint256 public immutable X;\n\n    constructor(uint256 _x) {\n        X = _x;\n    }\n}\n\ncontract B is A(2) {}\n```\n\n```text\nX\n```\n\n```text\nimmutable\n```\n\n========================================\n\nComments:\n- This was just a minimal example, but in the actual code I have multiple of those constants in an existing contract ... now I realized that constants like that are not ideal for reusability, it was a bad implementation, it should be like you recommend or vars that can be changed on constructor","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":155,"estimatedTokens":1139}}214{"id":"stack-66932198","source":"stackoverflow","questionId":66932198,"title":"Error: SimpleSmartContract has not been deployed to detected network (network/artifact mismatch)","tags":["solidity","truffle","network-error-logging"],"text":"Title: Error: SimpleSmartContract has not been deployed to detected network (network/artifact mismatch)\nTags: solidity, truffle, network-error-logging\nSource: Stack Overflow\n\nQuestion:\ni have develop a simple smartContract. when i run truffle test it showed the following error:i am new in this so i cant figure it out.\n\nPS F:\\pracdap> truffle test\n\n```\nCompiling your contracts...\n===========================\n√ Fetching solc version list from solc-bin. Attempt #1\n> Compiling .\\contracts\\Migrations.sol\n> Compiling .\\contracts\\SimpleSmartContract.sol \n√ Fetching solc version list from solc-bin. Attempt #1\n> Compilation warnings encountered:\n\n Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing \"urce file. Use \"SPDX-License-Identifier: UNLICENSED\" for non-open-source code. Please see https://spdx.org for more informa\n--> /F/pracdap/contracts/SimpleSmartContract.sol\n\n> Artifacts written to C:\\Users\\HP\\AppData\\Local\\Temp\\test--1224-GWVOn3NGyps8\n> Compiled successfully using:\n - solc: 0.8.3+commit.8d00100c.Emscripten.clang\n\n Contract: SimpleSmartContract\n 1) should be deployed\n > No events were emitted\n\n 0 passing (128ms)\n 1 failing\n\n 1) Contract: SimpleSmartContract\n should be deployed:\n Error: SimpleSmartContract has not been deployed to detected network (network/artifact mismatch)\n at Object.checkNetworkArtifactMatch (F:\\node\\node_modules\\truffle\\build\\webpack:\\packages\\contract\\lib\\utils\\index.js\n at Function.deployed (F:\\node\\node_modules\\truffle\\build\\webpack:\\packages\\contract\\lib\\contract\\constructorMethods.j\n at processTicksAndRejections (internal/process/task_queues.js:93:5)\n at Context. (test\\simpleSmartContract.js:5:33)\n```\n\nSolidity code\n\n```\npragma solidity >=0.4.22 Node js. test code\n\n```\nconst SimpleSmartContract = artifacts.require('SimpleSmartContract');\n\ncontract('SimpleSmartContract', () => {\n it('should be deployed', async () => {\n const simpleSmartContract = await SimpleSmartContract.deployed();\n assert(simpleSmartContract.address !== '');\n });\n});\n```\n\n========================================\n\nTop Answer:\nLooks like you have not added a **Migration** file for your `SimpleSmartContract`.\nCreate a file named `2_deploy_contracts.js` in your Migrations directory. The add the following code in it :\n\n const SimpleSmartContract = artifacts.require(\"SimpleSmartContract\");\n \n module.exports = function (deployer) {\n deployer.deploy(SimpleSmartContract);\n };\n\nThen try running the test.\n\n========================================\n\nCode:\n```text\nCompiling your contracts...\n===========================\n√ Fetching solc version list from solc-bin. Attempt #1\n> Compiling .\\contracts\\Migrations.sol\n> Compiling .\\contracts\\SimpleSmartContract.sol       \n√ Fetching solc version list from solc-bin. Attempt #1\n> Compilation warnings encountered:\n\n    Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing \"urce file. Use \"SPDX-License-Identifier: UNLICENSED\" for non-open-source code. Please see https://spdx.org for more informa\n--> /F/pracdap/contracts/SimpleSmartContract.sol\n\n\n> Artifacts written to C:\\Users\\HP\\AppData\\Local\\Temp\\test--1224-GWVOn3NGyps8\n> Compiled successfully using:\n   - solc: 0.8.3+commit.8d00100c.Emscripten.clang\n\n\n\n  Contract: SimpleSmartContract\n    1) should be deployed\n    > No events were emitted\n\n\n  0 passing (128ms)\n  1 failing\n\n  1) Contract: SimpleSmartContract\n       should be deployed:\n     Error: SimpleSmartContract has not been deployed to detected network (network/artifact mismatch)\n      at Object.checkNetworkArtifactMatch (F:\\node\\node_modules\\truffle\\build\\webpack:\\packages\\contract\\lib\\utils\\index.js\n      at Function.deployed (F:\\node\\node_modules\\truffle\\build\\webpack:\\packages\\contract\\lib\\contract\\constructorMethods.j\n      at processTicksAndRejections (internal/process/task_queues.js:93:5)\n      at Context.<anonymous> (test\\simpleSmartContract.js:5:33)\n```\n\n```text\npragma solidity >=0.4.22 <0.9.0;\n\ncontract SimpleSmartContract {\n}\n```\n\n```text\nconst SimpleSmartContract = artifacts.require('SimpleSmartContract');\n\ncontract('SimpleSmartContract', () => {\n    it('should be deployed', async () => {\n        const simpleSmartContract = await SimpleSmartContract.deployed();\n        assert(simpleSmartContract.address !== '');\n    });\n});\n```\n\n```text\nconst SimpleSmartContract = artifacts.require(\"SimpleSmartContract\");\n    \n    module.exports = function (deployer) {\n      deployer.deploy(SimpleSmartContract);\n    };\n```\n\n```text\nSimpleSmartContract\n```\n\n```text\n2_deploy_contracts.js\n```\n\n```text\nconst SimpleSmartContract = artifacts.require(\"SimpleSmartContract\");\n\nmodule.exports = async function(deployer, _network, accounts) {\n  await deployer.deploy(SimpleSmartContract);\n};\n```\n\n```text\ndeployer\n```\n\n```text\n_network\n```\n\n```text\naccounts\n```\n\n```text\nMyContract.setNetwork(<network id from console migrate>)\n```\n\n========================================\n\nComments:\n- Welcome to StackOverflow. Please edit your question so that it contains a reproducible code that produces the error (in your case, that's probably going to be both Solidity contract and the javascript test/deployer). You can find more tips in the How to Ask section.\n- @Pete Hejda solution?","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":173,"estimatedTokens":1326}}215{"id":"stack-70377502","source":"stackoverflow","questionId":70377502,"title":"What is the best way to access historical price data from Chainlink on a token in a decentralised manner?","tags":["blockchain","ethereum","solidity","chainlink","thegraph"],"text":"Title: What is the best way to access historical price data from Chainlink on a token in a decentralised manner?\nTags: blockchain, ethereum, solidity, chainlink, thegraph\nSource: Stack Overflow\n\nQuestion:\nI need to get the Chainlink prices of a token from a specific time to the most recent round. This time varies based on user input but will be relatively short windows (1 day to 2 weeks max) based on the heartbeat of the token. This is used to calculate the price of a payout both in the smart contract and on the application homepage.\n\nTo get historical price data Chainlink needs a 'roundId' which is a non-incremental value.\n\nWhat is the best way to either get all roundIds for the given time window from Chainlink or record them in a way that is open, decentralised and can be accessed in a solidity smart contract?\n\n========================================\n\nCode:\n```text\nreturn uint80(uint256(_phaseId) << 64 | _aggregatorRoundId);\n```\n\n```text\naggregator\n```\n\n```text\nlatestRound\n```\n\n```text\ngetRoundData\n```\n\n```text\n36893488147419113293\n```\n\n```text\ngetRoundData\n```\n\n```text\ngetRoundData\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":41,"estimatedTokens":277}}216{"id":"stack-71152833","source":"stackoverflow","questionId":71152833,"title":"Why am I getting this error Error: Transaction reverted without a reason string. When trying to swap tokens on uniswap?","tags":["blockchain","solidity","smartcontracts","uniswap"],"text":"Title: Why am I getting this error Error: Transaction reverted without a reason string. When trying to swap tokens on uniswap?\nTags: blockchain, solidity, smartcontracts, uniswap\nSource: Stack Overflow\n\nQuestion:\nI'm trying to swap tokens on uniswap unsing hardhat's mainnet fork but I'm getting this error: `Error: Transaction reverted without a reason string`. And I don't really know why.\n\nHere is my swap function:\n\n```\nfunction swap(address router, address _tokenIn, address _tokenOut, uint _amount) public {\n IERC20(router).approve(router, _amount);\n address[] memory path;\n path = new address[](2);\n path[0] = _tokenIn;\n path[1] = _tokenOut;\n uint deadline = block.timestamp + 300; \n IUniswapV2Router(router).swapExactTokensForTokens(_amount, 1, path, address(this), deadline); \n}\n```\n\nIt is a simple function and it should work. This is how I'm calling it:\n\n```\nawait arb.swap(\n uniAddress,\n wethAddress,\n daiAddress,\n ethers.utils.parseEther('0.5')\n);\n```\n\nThanks for answers!\n\nAlso here are the addresses I'm calling just to verify if they are the right ones but I'm pretty sure they are:\n\n```\nconst wethAddress = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';\nconst daiAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F';\nconst uniAddress = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D';\n```\n\n========================================\n\nTop Answer:\nJust adding for reffernce but you can also get this error from provider/hardhat if the gas price you set is too high or too low. at the time of writing 5 gwei seems about right\n\n========================================\n\nCode:\n```text\nfunction swap(address router, address _tokenIn, address _tokenOut, uint _amount) public {\n        IERC20(router).approve(router, _amount);\n        address[] memory path;\n        path = new address[](2);\n        path[0] = _tokenIn;\n        path[1] = _tokenOut;\n        uint deadline = block.timestamp + 300;  \n        IUniswapV2Router(router).swapExactTokensForTokens(_amount, 1, path, address(this), deadline);  \n}\n```\n\n```text\nawait arb.swap(\n    uniAddress,\n    wethAddress,\n    daiAddress,\n    ethers.utils.parseEther('0.5')\n);\n```\n\n```text\nconst wethAddress = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';\nconst daiAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F';\nconst uniAddress = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D';\n```\n\n```text\nError: Transaction reverted without a reason string\n```\n\n```text\nfunction swapEth(address router, address _tokenIn, address _tokenOut, uint _amount) public {\n    IERC20(router).approve(router, _amount);\n    address[] memory path;\n    path = new address[](2);\n    path[0] = _tokenIn;\n    path[1] = _tokenOut;\n    uint deadline = block.timestamp + 300;\n    IUniswapV2Router(router). swapExactETHForTokens(... parameters);  \n}\n```\n\n```text\nconst dataOption = { gasPrice: ethers.getDefaultProvider().getGasPrice(), gasLimit: 310000, value: ethers.utils.parseEther('0.5') }\n\nawait arb.swap(`enter code here`\n    uniAddress,\n    wethAddress,\n    daiAddress,\n    ethers.utils.parseEther('0.5'), // this parameter should be remove from the function declaration as well as in this Javascript\n    dataOption\n);\n```\n\n```text\nWeth\n```\n\n```text\nswapTokensForTokens\n```\n\n```text\nswapEthForTokens\n```\n\n```text\nError: Transaction reverted without a reason string\n```\n\n========================================\n\nComments:\n- Ohh ok I thought those functions were for native eth but I didin't realize that uniswap v2 doesn't take the native token. You saved me hours of debugging thanks a lot!\n- I am facing similar problem here: stackoverflow.com/questions/75960250/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":126,"estimatedTokens":901}}217{"id":"stack-54320320","source":"stackoverflow","questionId":54320320,"title":"How to Call contract inside another contarct in solidity version 0.5.2?","tags":["blockchain","ethereum","solidity","smartcontracts","remix"],"text":"Title: How to Call contract inside another contarct in solidity version 0.5.2?\nTags: blockchain, ethereum, solidity, smartcontracts, remix\nSource: Stack Overflow\n\nQuestion:\n**I'm using solidity version 0.5.2**\n\n```\npragma solidity ^0.5.2;\n\ncontract CampaignFactory{\naddress[] public deployedCampaigns;\n\nfunction createCampaign(uint minimum) public{\n address newCampaign = new Campaign(minimum,msg.sender); //Error \n//here!!!\n deployedCampaigns.push(newCampaign);\n} \n\nfunction getDeployedCampaigns() public view returns(address[] memory){\n return deployedCampaigns;\n}\n}\n```\n\nI'm getting the **error while assigning calling the Campaign contract inside CampaignFactory contract**\n\n```\nTypeError: Type contract Campaign is not implicitly convertible to expected \ntype address. \naddress newCampaign = new Campaign(minimum,msg.sender);\n```\n\nI have another contract called Campaign which i want to access inside CampaignFactory.\n\n```\ncontract Campaign{\n//some variable declarations and some codes here......\n```\n\nand I have the constructor as below\n\n```\nconstructor (uint minimum,address creator) public{\n manager=creator;\n minimumContribution=minimum;\n\n}\n```\n\n========================================\n\nTop Answer:\nTo call an existing contract from another contract ,pass the contract address inside cast\n\n```\npragma solidity ^0.5.1;\n\ncontract D {\n uint x;\n constructor (uint a) public {\n x = a;\n }\n function getX() public view returns(uint a)\n {\n return x;\n }\n}\n\ncontract C {\n//DAddress : is the exsiting contract instance address after deployment\n function getValue(address DAddress) public view returns(uint a){\n D d =D(DAddress);\n a=d.getX();\n }\n}\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.5.2;\n\ncontract CampaignFactory{\naddress[] public deployedCampaigns;\n\nfunction createCampaign(uint minimum) public{\n    address newCampaign  = new Campaign(minimum,msg.sender);  //Error \n//here!!!\n    deployedCampaigns.push(newCampaign);\n} \n\nfunction getDeployedCampaigns() public view returns(address[] memory){\n    return deployedCampaigns;\n}\n}\n```\n\n```text\nTypeError: Type contract Campaign is not implicitly convertible to expected \ntype address.        \naddress newCampaign  = new Campaign(minimum,msg.sender);\n```\n\n```text\ncontract Campaign{\n//some variable declarations and some codes here......\n```\n\n```text\nconstructor (uint minimum,address creator) public{\n    manager=creator;\n    minimumContribution=minimum;\n\n}\n```\n\n```text\naddress newCampaign = address(new Campaign(minimum,msg.sender));\n```\n\n```text\npragma solidity ^0.5.2;\n\ncontract CampaignFactory{\n    Campaign[] public deployedCampaigns;\n\n    function createCampaign(uint minimum) public {\n        Campaign newCampaign = new Campaign(minimum, msg.sender);\n        deployedCampaigns.push(newCampaign);\n    } \n\n    function getDeployedCampaigns() public view returns(Campaign[] memory) {\n        return deployedCampaigns;\n    }\n}\n```\n\n```text\naddress\n```\n\n```text\nCampaign\n```\n\n```text\npragma solidity ^0.5.1;\n\ncontract D {\n    uint x;\n    constructor (uint a) public  {\n        x = a;\n    }\n    function getX() public view returns(uint a)\n    {\n        return x;\n    }\n}\n\ncontract C {\n//DAddress : is the exsiting contract instance address after deployment\n    function getValue(address DAddress) public view returns(uint a){\n        D d =D(DAddress);\n        a=d.getX();\n    }\n}\n```\n\n========================================\n\nComments:\n- It worked!. Thank you @smarkx, I will keep in mind the suggestion you gave.","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":174,"estimatedTokens":877}}218{"id":"stack-71100362","source":"stackoverflow","questionId":71100362,"title":"How do I change the linter/formatter in VS Code?","tags":["visual-studio-code","solidity"],"text":"Title: How do I change the linter/formatter in VS Code?\nTags: visual-studio-code, solidity\nSource: Stack Overflow\n\nQuestion:\nI'm on Ubuntu. Pushing `Ctrl + Shift + i` in VS Code auto formats the file.\n\nI was editing a solidity contract and pushed `Ctrl + Shift + i`, VS Code didn't have a formatter configured so it asked me to pick one - I accidentally chose my JS prettifier extension instead of the solidity one. This badgered up my code by trying to use single quotes instead of double quotes (not allowed in solidity) and some other non-solidity friendly changes.\n\nPushing `Ctrl + Shift + i` now just auto formats with the wrong formatter with no option to pick a different one.\n\nHow can I change which linter/formatter is associated to which file types in VS Code?\n\n========================================\n\nCode:\n```text\nCtrl + Shift + i\n```\n\n```text\nCtrl + Shift + i\n```\n\n```text\nCtrl + Shift + i\n```\n\n```text\nCtrl+Shift+P\n```\n\n```text\nfile\n```\n\n```text\npreferences\n```\n\n```text\nsettings\n```\n\n```text\nText Editor\n```\n\n```text\nEditor: Default Formatter\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":51,"estimatedTokens":266}}219{"id":"stack-75019935","source":"stackoverflow","questionId":75019935,"title":"How to define TYPEHASH for EIP712 typed data signing with nested struct in Solidity?","tags":["ethereum","solidity"],"text":"Title: How to define TYPEHASH for EIP712 typed data signing with nested struct in Solidity?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI am wondering what the correct way is to define the TYPEHASH for a nested struct data structure for the EIP-712. I am trying to do this, as I want to retrieve the signer of a request struct using ECDSA and the EIP-712 standard for hashing structs.\n\nThis is the contract:\n\n```\nimport \"@openzeppelin/contracts/utils/cryptography/EIP712.sol\";\nimport \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\n\ncontract SignatureChecker is EIP712 {\n using ECDSA for bytes32;\n\n struct Fee {\n address recipient;\n uint256 value;\n }\n\n struct Request {\n address to;\n address from;\n Fee[] fees;\n }\n\n bytes32 public TYPEHASH = keccak256(\"Request(address to,address from, Fee[] fees)\");\n\n constructor() EIP712(\"SignatureChecker\", \"1\") {}\n\n function verify(\n Request calldata request,\n bytes calldata signature,\n address supposedSigner\n ) external view returns (bool) {\n return recoverAddress(request, signature) == supposedSigner;\n }\n\n function recoverAddress(\n Request calldata request,\n bytes calldata signature\n ) public view returns (address) {\n return _hashTypedDataV4(keccak256(encodeRequest(request))).recover(signature);\n }\n\n function encodeRequest(Request calldata request) public view returns (bytes memory) {\n return abi.encode(TYPEHASH, request.to, request.from, request.fees);\n }\n}\n```\n\nI just want to make sure that I am encoding the request correctly in the encodeRequest function. Unfortunately I could not find anything on how to create a typehash of a nested struct. Is the way I am creating the typehash correct?\n\nWhen I tried out the verify function without the fees property and the different TYPEHASH without the fee, it worked completely fine. However when I try to retrieve the address of a signature of the request struct with the fees array, it returns a wrong address.\n\nI have also seen an example where someone tried to do this:\n\n`bytes32 public constant TYPEHASH = keccak256(\"Request(address to,address from, Fee[] fees)Fee(address recipient, uint256 value)\");`\n\nUnfortunately it also produces a wrong address.\n\n========================================\n\nCode:\n```text\nimport \"@openzeppelin/contracts/utils/cryptography/EIP712.sol\";\nimport \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\n\ncontract SignatureChecker is EIP712 {\n    using ECDSA for bytes32;\n\n    struct Fee {\n        address recipient;\n        uint256 value;\n    }\n\n    struct Request {\n        address to;\n        address from;\n        Fee[] fees;\n    }\n\n    bytes32 public TYPEHASH = keccak256(\"Request(address to,address from, Fee[] fees)\");\n\n    constructor() EIP712(\"SignatureChecker\", \"1\") {}\n\n    function verify(\n        Request calldata request,\n        bytes calldata signature,\n        address supposedSigner\n    ) external view returns (bool) {\n        return recoverAddress(request, signature) == supposedSigner;\n    }\n\n    function recoverAddress(\n        Request calldata request,\n        bytes calldata signature\n    ) public view returns (address) {\n        return _hashTypedDataV4(keccak256(encodeRequest(request))).recover(signature);\n    }\n\n    function encodeRequest(Request calldata request) public view returns (bytes memory) {\n        return abi.encode(TYPEHASH, request.to, request.from, request.fees);\n    }\n}\n```\n\n```text\nbytes32 public constant TYPEHASH = keccak256(\"Request(address to,address from, Fee[] fees)Fee(address recipient, uint256 value)\");\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport \"@openzeppelin/contracts/utils/cryptography/EIP712.sol\";\nimport \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\n\ncontract SignatureChecker is EIP712 {\n    using ECDSA for bytes32;\n\n    struct Fee {\n        address recipient;\n        uint256 value;\n    }\n\n    struct Request {\n        address to;\n        address from;\n        Fee[] fees;\n    }\n\n    bytes32 public constant FEE_TYPEHASH = keccak256(\"Fee(address recipient,uint256 value)\");\n    bytes32 public constant REQUEST_TYPEHASH =\n        keccak256(\n            \"Request(address to,address from,Fee[] fees)Fee(address recipient,uint256 value)\"\n        );\n\n    constructor() EIP712(\"SignatureChecker\", \"1\") {}\n\n    function verify(\n        Request calldata request,\n        bytes calldata signature,\n        address signer\n    ) external view returns (bool) {\n        return recoverAddressOfRequest(request, signature) == signer;\n    }\n\n    function recoverAddressOfRequest(\n        Request calldata request,\n        bytes calldata signature\n    ) public view returns (address) {\n        return _hashTypedDataV4(keccak256(encodeRequest(request))).recover(signature);\n    }\n\n    function recoverAddressOfFee(\n        Fee calldata fee,\n        bytes calldata signature\n    ) public view returns (address) {\n        return _hashTypedDataV4(keccak256(encodeFee(fee))).recover(signature);\n    }\n\n    function encodeFee(Fee calldata fee) public pure returns (bytes memory) {\n        return abi.encode(FEE_TYPEHASH, fee.recipient, fee.value);\n    }\n\n    function encodeRequest(Request calldata request) public pure returns (bytes memory) {\n        bytes32[] memory encodedFees = new bytes32[](request.fees.length);\n        for (uint256 i = 0; i < request.fees.length; i++) {\n            encodedFees[i] = keccak256(encodeFee(request.fees[i]));\n        }\n\n        return\n            abi.encode(\n                REQUEST_TYPEHASH,\n                request.to,\n                request.from,\n                keccak256(abi.encodePacked(encodedFees))\n            );\n    }\n}\n```\n\n========================================\n\nComments:\n- Thanks for this! Do you know why we use `abi.encodePacked` rather than `abi.encode` for the `encodedFees`? I cannot work this out from the EIP.","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":188,"estimatedTokens":1455}}220{"id":"stack-69178874","source":"stackoverflow","questionId":69178874,"title":"Solidity v0.6.0. Fallback functions. What are they needed for?","tags":["blockchain","ethereum","solidity","smartcontracts"],"text":"Title: Solidity v0.6.0. Fallback functions. What are they needed for?\nTags: blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nAfter reading the documentation for Solidity v0.6.0 docs, I still don't understand the meaning of the `fallback` functions. I read that it was split into 2 functions: `fallback () external payable` and`receive () external payable`. That they are anonymous and do not accept any parameters, and in the overwhelming majority of cases, `receive () external payable` is used to receive funds. Can you please explain with the example of my code, some use cases for these functions, in order to understand all their features, otherwise somehow everything is in a vacuum, but I understand that this is an important concept? Even the meaning of the `receive () external payable` function is not clear, in which I call on the `buyToken ()` method, why is it needed if I call on `the buyToken ()` in the `Remix` directly, bypassing the `receive () external payable` since she is not visible and anonymous.\n\n```\npragma solidity ^0.7.0;\n // SPDX-License-Identifier: MIT\n \n contract BuyToken {\n mapping(address => uint256) public balances;\n address payable wallet;\n \n event Purchase(\n address indexed buyer,\n uint256 amount\n );\n \n constructor(address payable _wallet) {\n wallet = _wallet;\n }\n \n \n fallback() external payable {\n }\n \n \n receive() external payable {\n buyToken();\n }\n \n function buyToken() public payable {\n balances[msg.sender] += 1;\n wallet.transfer(msg.value);\n emit Purchase(msg.sender, 1);\n }\n }\n```\n\n========================================\n\nTop Answer:\nI'm not sure about your code example but here it goes:\n\n**Fallback function** - I think here is a good explanation. So if not marked payable, it will throw exception if contract receives plain ether without data.\n\n**External payable** - This post explains External well. So it costs less gas to call external than public. Only in your example it would make sense to change buyToken() from \"public\" to \"external\". Far as I understand there is no benefit to call public from external...\n\n========================================\n\nCode:\n```text\npragma solidity ^0.7.0;\n    // SPDX-License-Identifier: MIT\n    \n    contract BuyToken {\n      mapping(address => uint256) public balances;\n      address payable wallet;\n    \n      event Purchase(\n        address indexed buyer,\n        uint256 amount\n      );\n    \n      constructor(address payable _wallet) {\n        wallet = _wallet;\n      }\n    \n    \n      fallback() external payable {\n      }\n    \n    \n      receive() external payable {\n        buyToken();\n      }\n    \n      function buyToken() public payable {\n        balances[msg.sender] += 1;\n        wallet.transfer(msg.value);\n        emit Purchase(msg.sender, 1);\n      }\n    }\n```\n\n```text\nfallback\n```\n\n```text\nfallback () external payable\n```\n\n```text\nreceive () external payable\n```\n\n```text\nreceive () external payable\n```\n\n```text\nreceive () external payable\n```\n\n```text\nbuyToken ()\n```\n\n```text\nthe buyToken ()\n```\n\n```text\nRemix\n```\n\n```text\nreceive () external payable\n```\n\n```text\npragma solidity ^0.8;\n\ncontract MyContract {\n    mapping (address => uint256) public balances;\n\n    receive() external payable {\n        balances[msg.sender] += msg.value;\n    }\n\n    function withdraw(uint256 _amount) external {\n        require(_amount <= balances[msg.sender], 'Insufficient balance');\n        balances[msg.sender] -= _amount;\n        payable(msg.sender).transfer(_amount);\n    }\n}\n```\n\n```text\npragma solidity ^0.8;\n\ncontract MyContract {\n    uint256 public constant unlockAfter = 1640995200; // 2022-01-01\n\n    receive() external payable {\n        // anyone can send funds to this contract\n    }\n\n    function withdraw() external {\n        require(msg.sender == address(0x123), 'Not authorized');\n        require(block.timestamp >= unlockAfter, 'Not unlocked yet');\n        payable(msg.sender).transfer(address(this).balance);\n    }\n}\n```\n\n```text\npragma solidity ^0.8;\n\ncontract MyContract {\n    function foo() external {\n        // executed when the `data` field starts with `0xc2985578`, the signature of `foo()`\n    }\n    \n    fallback() external {\n        // executed when the `data` field is empty or starts with an unknown function signature\n    }\n}\n```\n\n```text\ndata\n```\n\n```text\nreceive()\n```\n\n```text\nreceive()\n```\n\n```text\nbuyToken()\n```\n\n```text\nbuyToken()\n```\n\n```text\nreceive()\n```\n\n```text\nfallback()\n```\n\n```text\ndata\n```\n\n```text\ncontract Fallback {\n    fallback () external payable {\n    }\n}\n```\n\n```text\nfunction _fallback() internal virtual {\n      _beforeFallback();\n       // calling the target function code\n      _delegate(_implementation());\n  }\n```\n\n```text\nEthereum Virtual Machine (EVM)\n```\n\n```text\nexternal\n```\n\n```text\nreturn\n```\n\n```text\npragma solidity  ^0.8.12;\n```\n\n```text\nfallback\n```\n\n```text\nreturn\n```\n\n```text\nfallback()\n```\n\n```text\nfallback\n```\n\n```text\npayable\n```\n\n```text\nfallback\n```\n\n```text\nreceive\n```\n\n```text\nreceive\n```\n\n```text\nfallback\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.130Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":36,"totalLines":271,"estimatedTokens":1257}}221{"id":"stack-68810515","source":"stackoverflow","questionId":68810515,"title":"totalsupply() is not a function openzeppelin contracts","tags":["ethereum","solidity","openzeppelin"],"text":"Title: totalsupply() is not a function openzeppelin contracts\nTags: ethereum, solidity, openzeppelin\nSource: Stack Overflow\n\nQuestion:\nI'm trying to import some contract files from open zeppelin so my solidity smart contracts can inherit their functionality, when trying to write chai tests that run on my smart contracts at compile time I get an error in my chai test.\n\n```\n3 passing (2s)\n 1 failing\n\n 1) Contract: Color\n minting\n creates a new token:\n TypeError: contract.totalSupply is not a function\n```\n\nmy contract importing the openzeppelin contracts\n\n```\npragma solidity 0.8.7;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\"; //import base functionality\nimport \"@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol\"; //import totalsupply()\n\ncontract color is ERC721 {\n string[] public colors;\n mapping(string => bool) _colorExists; //mappings are like json objects where value a is searched and its value is returned\n constructor() ERC721(\"Color\", \"COLOR\") {\n }\n\n function mint(string memory _color) public{\n colors.push(_color);\n uint _id = colors.length -1;\n\n _mint(msg.sender,_id);\n _colorExists[_color] = true;\n \n }\n}\n```\n\nand lastly my test file ( I have shortened it to show only the test giving me errors)\n\n```\nconst { assert } = require('chai')\nconst Color = artifacts.require('./Color.sol')\n\nrequire('chai')\n.use(require('chai-as-promised'))\n.should()\n\ncontract('Color', (accounts) =>{\n let FormControlStatic\n\n before(async ()=>{\n contract = \n await Color.deployed()\n })\n \n describe('minting', async ()=>{\n \n it('creates a new token', async ()=>{\n const result = await contract.mint('#EC058E')\n console.log(result)\n const totalSupply = await contract.totalSupply()\n\n assert.equal(totalSupply,1)\n console.log(result)\n })\n })\n})\n```\n\nalso if we look at the file containing the function `totalSupply()` it is publicly scoped so it should be visible outside the function via import\n\nI did some digging and imported the file that the actual function IS in from openzeppelin however it seems that I still get the same error, I tried compiling separately to see if recompiling after changing would resolve but it didn't\n\nnot sure if anyone else has gone through this recently or might have a solution\nalso I'm importing the current version here\nhttps://www.npmjs.com/package/@openzeppelin/contracts\n\nthanks!\n\n========================================\n\nTop Answer:\nWe must extend `IERC721Enumerable` contracts, and, implements its virtual functions.\n\n```\ncontract Color is ERC721, IERC721Enumerable { // We must extends IERC721Enumerable \n string[] public colors;\n mapping(string => bool) _colorExists;\n\n constructor() ERC721(\"Color\", \"COLOR\") {}\n\n function mint(string memory _color) public {\n colors.push(_color);\n uint256 _id = colors.length - 1;\n\n // _mint(msg.sender,_id);\n _colorExists[_color] = true;\n }\n \n\n // And must override below three functions\n\n function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {\n // You need update this logic.\n // ...\n return 3;\n }\n\n function totalSupply() external view override returns (uint256) {\n // You need update this logic.\n // ...\n return 1;\n }\n\n function tokenByIndex(uint256 index) external view override returns (uint256) {\n // You need update this logic.\n // ...\n return 5;\n }\n}\n```\n\nhttps://i.sstatic.net/p456u.png\n\nThen, we can call `totalSupply()` method\n\n========================================\n\nCode:\n```text\n3 passing (2s)\n  1 failing\n\n  1) Contract: Color\n       minting\n         creates a new token:\n     TypeError: contract.totalSupply is not a function\n```\n\n```text\npragma solidity 0.8.7;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\"; //import base functionality\nimport \"@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol\"; //import totalsupply()\n\ncontract color is ERC721 {\n    string[] public colors;\n    mapping(string => bool) _colorExists; //mappings are like json objects where value a is searched and its value is returned\n    constructor() ERC721(\"Color\", \"COLOR\") {\n    }\n\n    function mint(string memory _color) public{\n      colors.push(_color);\n      uint _id = colors.length -1;\n\n      _mint(msg.sender,_id);\n      _colorExists[_color] = true;\n \n    }\n}\n```\n\n```text\nconst { assert } = require('chai')\nconst Color = artifacts.require('./Color.sol')\n\nrequire('chai')\n.use(require('chai-as-promised'))\n.should()\n\ncontract('Color', (accounts) =>{\n    let FormControlStatic\n\n    before(async ()=>{\n        contract = \n        await Color.deployed()\n    })\n    \n    describe('minting', async ()=>{\n        \n        it('creates a new token', async ()=>{\n            const result = await contract.mint('#EC058E')\n            console.log(result)\n            const totalSupply = await contract.totalSupply()\n\n            assert.equal(totalSupply,1)\n            console.log(result)\n        })\n    })\n})\n```\n\n```text\ntotalSupply()\n```\n\n```text\npragma solidity ^0.8.0; // Note that this is using a newer version than in \n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol\";\n\n\ncontract Color is ERC721, ERC721Enumerable {\n    string[] public colors;\n    mapping(string => bool) _colorExists;\n\n    constructor() ERC721(\"Color\", \"COLOR\") public {\n    }\n\n    function _beforeTokenTransfer(address from, address to, uint256 tokenId)\n    internal\n    override(ERC721, ERC721Enumerable)\n    {\n        super._beforeTokenTransfer(from, to, tokenId);\n    }\n\n    function supportsInterface(bytes4 interfaceId)\n    public\n    view\n    override(ERC721, ERC721Enumerable)\n    returns (bool)\n    {\n        return super.supportsInterface(interfaceId);\n    }\n\n\n    function mint(string memory _color) public {\n        colors.push(_color);\n        uint _id = colors.length - 1;\n        _mint(msg.sender, _id);\n        _colorExists[_color] = true;\n    }\n}\n```\n\n```text\noverrides\n```\n\n```text\nsuper\n```\n\n```text\ncontract Color is ERC721, IERC721Enumerable { // We must extends IERC721Enumerable \n    string[] public colors;\n    mapping(string => bool) _colorExists;\n\n    constructor() ERC721(\"Color\", \"COLOR\") {}\n\n    function mint(string memory _color) public {\n        colors.push(_color);\n        uint256 _id = colors.length - 1;\n\n        // _mint(msg.sender,_id);\n        _colorExists[_color] = true;\n    }\n    \n\n    // And must override below three functions\n\n    function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {\n        // You need update this logic.\n        // ...\n        return 3;\n    }\n\n    function totalSupply() external  view override returns (uint256) {\n      // You need update this logic.\n      // ...\n      return 1;\n    }\n\n    function tokenByIndex(uint256 index) external view  override returns (uint256) {\n      // You need update this logic.\n      // ...\n      return 5;\n    }\n}\n```\n\n```text\nIERC721Enumerable\n```\n\n```text\ntotalSupply()\n```\n\n```text\n./node_modules/.bin/truffle-flattener ./node_modules/@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol > contracts/ERC721Enumerable.sol\n```\n\n```text\nimport \"./ERC721Enumerable.sol\";\n     \ncontract Color is ERC721Enumerable {\n         // \n     }\n```\n\n========================================\n\nComments:\n- Hey @lutherwardle I'm having the same issue. Any more specifics on how it can be fixed? I've added the three functions to the Color.test.js file under the ERC721 constructor (presume you're working through the same example luther). Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":311,"estimatedTokens":1881}}222{"id":"stack-51226875","source":"stackoverflow","questionId":51226875,"title":"Solidity ParserError: Expected identifier but got '='","tags":["constructor","ethereum","identifier","solidity","parsing-error"],"text":"Title: Solidity ParserError: Expected identifier but got '='\nTags: constructor, ethereum, identifier, solidity, parsing-error\nSource: Stack Overflow\n\nQuestion:\nWhy does the code below contain an error (`ParserError: Expected identifier but got '='`).\n\n```\ncontract Test {\n\n struct Box {\n uint size;\n }\n\n Box public box;\n box.size = 3; //It works if I put the `box.size = 3;` into the `constructor`!\n\n```\ncontract Test {\n\n struct Box {\n uint size;\n }\n\n Box public box;\n\n constructor() public {\n box.size = 3;\n }\n\n}\n```\n\n========================================\n\nCode:\n```text\ncontract Test {\n\n    struct Box {\n        uint size;\n    }\n\n    Box public box;\n    box.size = 3;    //<-- error here\n\n    constructor() public {\n    }\n\n}\n```\n\n```text\ncontract Test {\n\n    struct Box {\n        uint size;\n    }\n\n    Box public box;\n\n    constructor() public {\n        box.size = 3;\n    }\n\n}\n```\n\n```text\nParserError: Expected identifier but got '='\n```\n\n```text\nbox.size = 3;\n```\n\n```text\nconstructor\n```\n\n```text\nBox public box = Box({ size: 3 });\n```\n\n```text\nBox public box = Box(3);\n```\n\n========================================\n\nComments:\n- I don't use Solidity, but I guess you can't have assignments outside a function.","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":92,"estimatedTokens":305}}223{"id":"stack-76251324","source":"stackoverflow","questionId":76251324,"title":"Why does `eth_estimateGas` on Hedera return an unexpectedly high value?","tags":["solidity","rpc","hedera-hashgraph","hedera"],"text":"Title: Why does `eth_estimateGas` on Hedera return an unexpectedly high value?\nTags: solidity, rpc, hedera-hashgraph, hedera\nSource: Stack Overflow\n\nQuestion:\nI am aware that `eth_estimateGas` is not intended to be exact,\nbut currently, I'm getting actual `gasUsed` values\nthat are approximately 6% of the value returned by `eth_estimateGas`.\n\nIn the following example,\nI invoke the same smart contract with the exact same inputs twice, with only 1 difference:\n\n- In the 1st invocation, `gasLimit = eth_estimateGas`\nIn the 2nd invocation, `gasLimit = eth_estimateGas * 0.064`\n\n- This value is a very small fraction of the estimate\n\n- This value was obtained through trial-and-error ... not through any calculations\n\n```\n// with exact estimated amount of gas\n const estimatedGas2 = (await expendGasSc.estimateGas.updateState(1_000_000_123n)).toBigInt();\n console.log('estimatedGas2', estimatedGas2);\n const gasLimit2 = estimatedGas2 * 1n;\n console.log('gasLimit2', gasLimit2);\n const txResponse2 = await (await expendGasSc\n .updateState(\n 1_000_000_123n,\n { gasLimit: gasLimit2 },\n ))\n .wait();\n const gasUsed2 = txResponse2.gasUsed.toBigInt();\n console.log('gasUsed2', gasUsed2);\n\n // with small fraction of estimated amount of gas\n const estimatedGas4 = (await expendGasSc.estimateGas.updateState(1_000_000_123n)).toBigInt();\n console.log('estimatedGas4', estimatedGas4);\n const gasLimit4 = estimatedGas4 * 64n / 1000n; // Here are the results:\n\nWhen `gasLimit` is 400,000, `gasUsed` is 320,000\n\nThis is exactly 80% of the specified `gasLimit`,\nindicating that HIP-185's gas over-reservation penalty **is likely* to have kicked in.\n\n- See this answer to my previous related question for context.\n\nWhen `gasLimit` is 25,600, `gasUsed` is 23,816\n\nThis is greater than 80% of the specified `gasLimit`,\nindicating that HIP-185's gas over-reservation penalty **has not** kicked in\n\n```\nestimatedGas2 400000n\ngasLimit2 400000n\ngasUsed2 320000n\nestimatedGas4 400000n\ngasLimit4 25600n\ngasUsed4 23816n\n```\n\nTherefore, I am expecting `eth_estimateGas` to return a value\nthat is much closer to 23,816 than 400,000.\nWhy is it returning such an unexpectedly high estimate\ncompared to the actual?\n\nHere's the smart contract:\n\n```\n// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.18;\n\ncontract ExpendSomeGasDemo {\n uint256 public state;\n\n function updateState(\n uint256 newState\n )\n public\n returns (uint256 updatedState)\n {\n state = newState;\n updatedState = newState;\n }\n}\n```\n\nNote that this contract is deployed on Hedera Testnet:\n`0x9C58D0159495F7a8853A24574f2B8F348a72424c`\n\nNote that the Javascript example above is using ethers.js.\n\nNote that this question is a up to my previous one:\nLarge discrepancy in `gasUsed` values in near-identical transactions on Hedera - why?\n\n========================================\n\nCode:\n```js\n// with exact estimated amount of gas\n    const estimatedGas2 = (await expendGasSc.estimateGas.updateState(1_000_000_123n)).toBigInt();\n    console.log('estimatedGas2', estimatedGas2);\n    const gasLimit2 = estimatedGas2 * 1n;\n    console.log('gasLimit2', gasLimit2);\n    const txResponse2 = await (await expendGasSc\n        .updateState(\n            1_000_000_123n,\n            { gasLimit: gasLimit2 },\n        ))\n        .wait();\n    const gasUsed2 = txResponse2.gasUsed.toBigInt();\n    console.log('gasUsed2', gasUsed2);\n\n    // with small fraction of estimated amount of gas\n    const estimatedGas4 = (await expendGasSc.estimateGas.updateState(1_000_000_123n)).toBigInt();\n    console.log('estimatedGas4', estimatedGas4);\n    const gasLimit4 = estimatedGas4 * 64n / 1000n; // <--- 🚨🚨🚨 6.4% 🚨🚨🚨\n    console.log('gasLimit4', gasLimit4);\n    const txResponse4 = await (await expendGasSc\n        .updateState(\n            1_000_000_123n,\n            { gasLimit: gasLimit4 },\n        ))\n        .wait();\n    console.log('txResponse4', txResponse4);\n    const gasUsed4 = txResponse4.gasUsed.toBigInt();\n    console.log('gasUsed4', gasUsed4);\n```\n\n```text\nestimatedGas2 400000n\ngasLimit2 400000n\ngasUsed2 320000n\nestimatedGas4 400000n\ngasLimit4 25600n\ngasUsed4 23816n\n```\n\n```text\n// SPDX-License-Identifier: GPL-3.0\npragma solidity 0.8.18;\n\ncontract ExpendSomeGasDemo {\n    uint256 public state;\n\n    function updateState(\n        uint256 newState\n    )\n        public\n        returns (uint256 updatedState)\n    {\n        state = newState;\n        updatedState = newState;\n    }\n}\n```\n\n```text\neth_estimateGas\n```\n\n```text\ngasUsed\n```\n\n```text\neth_estimateGas\n```\n\n```text\ngasLimit = eth_estimateGas\n```\n\n```text\ngasLimit = eth_estimateGas * 0.064\n```\n\n```text\ngasLimit\n```\n\n```text\ngasUsed\n```\n\n```text\ngasLimit\n```\n\n```text\ngasLimit\n```\n\n```text\ngasUsed\n```\n\n```text\ngasLimit\n```\n\n```text\neth_estimateGas\n```\n\n```text\n0x9C58D0159495F7a8853A24574f2B8F348a72424c\n```\n\n```text\ngasUsed\n```\n\n```js\n{\n    // ...\n    TX_BASE_COST: 21_000,\n    TX_HOLLOW_ACCOUNT_CREATION_GAS: 587_000,\n    TX_DEFAULT_GAS_DEFAULT: 400_000,\n    TX_CREATE_EXTRA: 32_000,\n    TX_DATA_ZERO_COST: 4,\n    // ...\n}\n```\n\n```js\nasync estimateGas(transaction: any, _blockParam: string | null, requestId?: string) {\n    const requestIdPrefix = formatRequestIdMessage(requestId);\n    this.logger.trace(`${requestIdPrefix} estimateGas(transaction=${JSON.stringify(transaction)}, _blockParam=${_blockParam})`);\n    // this checks whether this is a transfer transaction and not a contract function execution\n    if (transaction && transaction.to && (!transaction.data || transaction.data === '0x')) {\n      const value = Number(transaction.value);\n      if (value > 0) {\n        const accountCacheKey = `${constants.CACHE_KEY.ACCOUNT}_${transaction.to}`;\n        let toAccount: object | null = this.cache.get(accountCacheKey);\n        if (!toAccount) {\n          toAccount = await this.mirrorNodeClient.getAccount(transaction.to, requestId);\n        }\n​\n        // when account exists return default base gas, otherwise return the minimum amount of gas to create an account entity\n        if (toAccount) {\n          this.logger.trace(`${requestIdPrefix} caching ${accountCacheKey}:${JSON.stringify(toAccount)} for ${constants.CACHE_TTL.ONE_HOUR} ms`);\n          this.cache.set(accountCacheKey, toAccount);\n​\n          return EthImpl.gasTxBaseCost;\n        }\n​\n        return EthImpl.gasTxHollowAccountCreation;\n      }\n​\n      return predefined.INVALID_PARAMETER(0, `Invalid 'value' field in transaction param. Value must be greater than 0`);\n    } else {\n      return this.defaultGas;\n    }\n  }\n​\n```\n\n```text\neth_estimateGas\n```\n\n```text\npackages/relay/src/lib/constants.ts\n```\n\n```text\nestimateGas\n```\n\n```text\npackages/relay/src/lib/eth.ts\n```\n\n```text\nreturn this.defaultGas;\n```\n\n```text\nTX_DEFAULT_GAS_DEFAULT\n```\n\n```text\neth_estimateGas\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":26,"totalLines":284,"estimatedTokens":1686}}224{"id":"stack-68874808","source":"stackoverflow","questionId":68874808,"title":"Converting string memory to string calldata?","tags":["ethereum","solidity"],"text":"Title: Converting string memory to string calldata?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nWondering if its possible to convert between string memory and string calldata in order to use indexing of the form string[start : end] which only works string calldata. This function seems to works:\n\n```\nfunction splice(string calldata source, int startPos, int numchars) public pure returns(string memory) {\n if (startPos > int(length(sourcestring))) return \"\";\n int start = startPos -1;\n int end = startPos + (numchars -1);\n string memory retval = string(source[uint(start) : uint(end)]);\n return retval;\n\n }\n```\n\nbut if I change the parameter `source` to string memory, then I get an error on\n`string memory retval = string(source([uint(start) : uint(end)])`\nbecause apparently the form `sourcestring[start : end]` to get a substring works on `calldata` strings not on `memory` strings, and there is no obvious way to convert a `string memory` to a `string calldata`.\n\nIs there any means to do this?\n\n========================================\n\nTop Answer:\nProbably not since calldata is for data supplied while making an external transaction. Very different purpose compared to storage.\n\n========================================\n\nCode:\n```text\nfunction splice(string calldata source, int startPos, int numchars) public pure returns(string memory) {\n        if (startPos > int(length(sourcestring))) return \"\";\n        int start = startPos -1;\n        int end = startPos + (numchars -1);\n        string memory retval = string(source[uint(start) : uint(end)]);\n        return retval;\n\n    }\n```\n\n```text\nsource\n```\n\n```text\nstring memory retval = string(source([uint(start) : uint(end)])\n```\n\n```text\nsourcestring[start : end]\n```\n\n```text\ncalldata\n```\n\n```text\nmemory\n```\n\n```text\nstring memory\n```\n\n```text\nstring calldata\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":70,"estimatedTokens":460}}225{"id":"stack-68417684","source":"stackoverflow","questionId":68417684,"title":"How can I make the data provided by some ChainLink aggregator get updated every time I click on my \"getLatestPrice\" button?","tags":["javascript","solidity","smartcontracts","chainlink"],"text":"Title: How can I make the data provided by some ChainLink aggregator get updated every time I click on my \"getLatestPrice\" button?\nTags: javascript, solidity, smartcontracts, chainlink\nSource: Stack Overflow\n\nQuestion:\nthis is my very first time deploying a contract on Remix as well as learning how to code on Solidity.\n\nI have already read this guide and deployed successfully the Smart Contract template provided:\n\n```\npragma solidity ^0.6.7;\n\nimport \"@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol\";\n\ncontract PriceConsumerV3 {\n\nAggregatorV3Interface internal priceFeed;\n\n/**\n * Network: Kovan\n * Aggregator: BTC/USD\n * Address: 0x6135b13325bfC4B00278B4abC5e20bbce2D6580e\n */\nconstructor() public {\n priceFeed = AggregatorV3Interface(0x6135b13325bfC4B00278B4abC5e20bbce2D6580e);\n}\n\n/**\n * Returns the latest price\n */\nfunction getThePrice() public view returns (int) {\n (\n uint80 roundID, \n int price,\n uint startedAt,\n uint timeStamp,\n uint80 answeredInRound\n ) = priceFeed.latestRoundData();\n return price;\n}\n}\n```\n\nHowever, I thought that after deploying the template above, whenever I clicked on the getLatestPrice button the price of such pair would get instantly updated, I was very wrong, the price actually turned out getting \"frozen\" after the first click.\n\nSo, I would like to know what would be mandatory to type in the template above to fulfill that aim\n\nAlso, I tried to print the `timeStamp` by typing `return timeStamp;` right below `return price;` but when compiling, the Remix compiler replied:\n\nTypeError: Return argument type uint256 is not implicitly convertible to expected type (type of first return variable) int256. return timeStamp; ^-------^\n\nSo, just for curiosity, how do I convert a uint256 variable to an int256 one in order to get the timeStamp of each updated price (for every time I click on `getLatestPrice button`) ?\n\nthanks for reading\n\n========================================\n\nTop Answer:\nThe price feed contracts are actually independently updated by a group of chainlink nodes, and your contract is just reading from that contract.\n\nWhen you call `getLatestPrice` it's actually just reading from that contract.\n\nAdditionally, the price feed contracts are updated based on certain thresholds and deviations. Especially on testnet, they are updated pretty sporatically.\n\nIf you could make a separate question for your `TypeError` that would be ideal, thanks!\n\n========================================\n\nCode:\n```text\npragma solidity ^0.6.7;\n\nimport \"@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol\";\n\ncontract PriceConsumerV3 {\n\nAggregatorV3Interface internal priceFeed;\n\n/**\n * Network: Kovan\n * Aggregator: BTC/USD\n * Address: 0x6135b13325bfC4B00278B4abC5e20bbce2D6580e\n */\nconstructor() public {\n    priceFeed = AggregatorV3Interface(0x6135b13325bfC4B00278B4abC5e20bbce2D6580e);\n}\n\n/**\n * Returns the latest price\n */\nfunction getThePrice() public view returns (int) {\n    (\n        uint80 roundID, \n        int price,\n        uint startedAt,\n        uint timeStamp,\n        uint80 answeredInRound\n    ) = priceFeed.latestRoundData();\n    return price;\n}\n}\n```\n\n```text\ntimeStamp\n```\n\n```text\nreturn timeStamp;\n```\n\n```text\nreturn price;\n```\n\n```text\ngetLatestPrice button\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.6.6;\npragma experimental ABIEncoderV2;\n\n//To run on remix use Injected Web3 with Metamask on Rinkeby network activated\n\nimport \"@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol\";\n\ncontract ChainlinkPriceFeed {\n    \n    int public countButtonClicks;\n    int public kovanEthPrice;\n    uint public kovanTimestamp;\n    uint80 public kovanRoundID;\n    \n    /**\n     * Network: Kovan\n     * Aggregator: ETH/USD\n     */\n    constructor() public {\n        countButtonClicks = 0;\n        kovanEthPrice = -1;\n        kovanTimestamp = 0;\n        kovanRoundID = 0;\n        // Examples -> Rinkeby network \n        // See https://docs.chain.link/docs/reference-contracts/ for available feeds and blockchains\n        // priceData[\"ETHUSD\"] = 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e;\n        // priceData[\"BTCUSD\"] = 0xECe365B379E1dD183B20fc5f022230C044d51404;\n        // priceData[\"LINKUSD\"] = 0xd8bD0a1cB028a31AA859A21A3758685a95dE4623;\n        // priceData[\"AUDUSD\"]= 0x21c095d2aDa464A294956eA058077F14F66535af;\n        //Examples -> Kovan Netowrk see https://docs.chain.link/docs/ethereum-addresses/\n    }\n\n    /**\n     * Returns the latest price information from the asset address\n     */\n    function getLatestPrice(address assetAddress) public view returns \n    (int price, uint80 roundID, int decimals, string memory description, uint timestamp) \n    {\n        AggregatorV3Interface priceFeed = AggregatorV3Interface(assetAddress);\n        (            \n            roundID, \n            price,\n            uint startedAt,\n            timeStamp,\n            uint80 answeredInRound\n        ) = priceFeed.latestRoundData();\n        description = priceFeed.description();\n        decimals = priceFeed.decimals();\n\n        return (price, roundID, decimals, description, timestamp);\n    }\n    \n    function getKovanEthPrice() public view returns (int price, uint timeStamp, uint80 roundID) {\n        AggregatorV3Interface priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331);\n        (            \n            uint80 roundID, \n            int price,\n            uint startedAt,\n            uint timeStamp,\n            uint80 answeredInRound\n        ) = priceFeed.latestRoundData();\n        \n        return (price, timeStamp, roundID);\n    }\n    \n    function counterKovanEthPrice() public {\n        countButtonClicks = countButtonClicks+1;\n        (kovanEthPrice, kovanTimestamp, kovanRoundID) = getKovanEthPrice();\n        \n    }\n}\n```\n\n```text\ngetLatestPrice\n```\n\n```text\nTypeError\n```\n\n========================================\n\nComments:\n- Typically, you want to have 1 question per stackoverflow question. Could you make another one for your second question?\n- Sure sir @PatrickCollins I just made it, here it is: stackoverflow.com/questions/68422733/&hellip;\n- Lovely, thank you!\n- How we can update the price of MATIC/USD using your solution, please? ethereum.stackexchange.com/questions/127865/&hellip;\n- You'll need to use the price data from Polygon for this. Simply change the aggregator to the Polygon address instead of using the ethereum address (see constructor for commented out info)\n- Also update to this code - you could also use hardhats console module to check functionality: hardhat.org/guides/hardhat-console.html\n- Can we trigger these nodes to update the price sooner than their regular updates, for example by paying link coin? Otherwise, should we run a node to update the price ourselves?\n- If you want to trigger updates yourself, yes, you'd want to run your own price feed. This is a much harder task though.","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":213,"estimatedTokens":1723}}226{"id":"stack-66449576","source":"stackoverflow","questionId":66449576,"title":"Importing ethers via Hardhat fails despite official testing documentation","tags":["javascript","ethereum","solidity","smartcontracts","hardhat"],"text":"Title: Importing ethers via Hardhat fails despite official testing documentation\nTags: javascript, ethereum, solidity, smartcontracts, hardhat\nSource: Stack Overflow\n\nQuestion:\nAccording to the official testing documentation for Hardhat, `ethers` should be available implicitly within the global scope; however, it can optionally be `require`d explicitly, like so:\n\n```\nconst { ethers } = require(\"hardhat\");\n```\n\nThis fails for my local project.\n\nMy package manifest seems to include the correct dependencies:\n\n```\n{\n \"dependencies\": {\n \"@nomiclabs/hardhat-ethers\": \"^2.0.1\",\n \"@nomiclabs/hardhat-waffle\": \"^2.0.1\",\n \"@openzeppelin/contracts\": \"https://github.com/OpenZeppelin/openzeppelin-contracts#v4.0.0-beta.0\",\n \"chai\": \"^4.3.1\",\n \"hardhat\": \"^2.0.11\"\n }\n}\n```\n\nMy unit tests file seems to match the worked example in the Hardhat documentation also:\n\n```\nconst { ethers } = require(\"hardhat\");\nconst { expect } = require(\"chai\");\n\ndescribe(\"Distributor.sol\", function() {\n it(\"Distribution should fail for non-owners\", async function() {\n const DistributorFactory = await ethers.getContractFactory(\"Distributor\");\n const Distributor = await Distributor.deploy();\n\n Distributor.distribute([], []);\n\n expect(await hardhatToken.totalSupply()).to.be.revertedWith(\"foobar\");\n });\n});\n```\n\nDespite this, running the tests fails with:\n\n```\n$ yarn hardhat test\nyarn run v1.22.5\n$ /home/bob/dev/misc/token-distributor/node_modules/.bin/hardhat test\n\n Distributor.sol\nundefined\n 1) Distribution should fail for non-owners\n\n 0 passing (9ms)\n 1 failing\n\n 1) Distributor.sol\n Distribution should fail for non-owners:\n TypeError: Cannot read property 'getContractFactory' of undefined\n at Context. (test/Distributor.js:8:49)\n at processImmediate (internal/timers.js:461:21)\n\nerror Command failed with exit code 1.\ninfo Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\n```\n\n**How do I fix this?**\n\n========================================\n\nTop Answer:\nTwo things:\n\nyou need to install `ethers` separately too, as given in the instructions for `hardhat-ethers`, e.g.\n\n`npm install --save-dev @nomiclabs/hardhat-ethers 'ethers@^5.0.0'`\n\nEvery Hardhat plugin needs to be registered in the Hardhat config file (`hardhat.config.js`):\n\n`require(\"@nomiclabs/hardhat-ethers\");`\n\nThere is no need to remove the explicit import in your test file, however, Hardhat docs recommend following this style:\n\n```\nconst hre = require(\"hardhat\");\nconst { ethers } = hre;\n```\n\n========================================\n\nCode:\n```js\nconst { ethers } = require(\"hardhat\");\n```\n\n```json\n{\n  \"dependencies\": {\n    \"@nomiclabs/hardhat-ethers\": \"^2.0.1\",\n    \"@nomiclabs/hardhat-waffle\": \"^2.0.1\",\n    \"@openzeppelin/contracts\": \"https://github.com/OpenZeppelin/openzeppelin-contracts#v4.0.0-beta.0\",\n    \"chai\": \"^4.3.1\",\n    \"hardhat\": \"^2.0.11\"\n  }\n}\n```\n\n```js\nconst { ethers } = require(\"hardhat\");\nconst { expect } = require(\"chai\");\n\ndescribe(\"Distributor.sol\", function() {\n    it(\"Distribution should fail for non-owners\", async function() {\n        const DistributorFactory = await ethers.getContractFactory(\"Distributor\");\n        const Distributor = await Distributor.deploy();\n\n        Distributor.distribute([], []);\n\n        expect(await hardhatToken.totalSupply()).to.be.revertedWith(\"foobar\");\n    });\n});\n```\n\n```sh\n$ yarn hardhat test\nyarn run v1.22.5\n$ /home/bob/dev/misc/token-distributor/node_modules/.bin/hardhat test\n\n\n  Distributor.sol\nundefined\n    1) Distribution should fail for non-owners\n\n\n  0 passing (9ms)\n  1 failing\n\n  1) Distributor.sol\n       Distribution should fail for non-owners:\n     TypeError: Cannot read property 'getContractFactory' of undefined\n      at Context.<anonymous> (test/Distributor.js:8:49)\n      at processImmediate (internal/timers.js:461:21)\n\n\n\nerror Command failed with exit code 1.\ninfo Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\n```\n\n```text\nethers\n```\n\n```text\nrequire\n```\n\n```text\nrequire(\"@nomiclabs/hardhat-waffle\");\n```\n\n```text\nconst { ethers } = require(\"hardhat\");\n```\n\n```text\nhardhat.config.js\n```\n\n```text\nethers\n```\n\n```text\nethers\n```\n\n```text\nconst hre = require(\"hardhat\");\nconst { ethers } = hre;\n```\n\n```text\nethers\n```\n\n```text\nhardhat-ethers\n```\n\n```text\nnpm install --save-dev @nomiclabs/hardhat-ethers 'ethers@^5.0.0'\n```\n\n```text\nhardhat.config.js\n```\n\n```text\nrequire(\"@nomiclabs/hardhat-ethers\");\n```\n\n```text\nreading ethers undefined\n```\n\n```text\nyarn hardhat\n```\n\n```text\nnpm install --save-dev @nomicfoundation/hardhat-ethers ethers\n```\n\n```text\nrequire(\"@nomicfoundation/hardhat-ethers\");\n```\n\n```text\nimport \"@nomicfoundation/hardhat-ethers\";\n```\n\n```text\nimport { ethers } from \"hardhat\";\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":228,"estimatedTokens":1179}}227{"id":"stack-50281597","source":"stackoverflow","questionId":50281597,"title":"Pass String [ ] to constructor in Solidity","tags":["solidity","smartcontracts"],"text":"Title: Pass String [ ] to constructor in Solidity\nTags: solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\ni m using remix IDE to deploy a smart contract and i m passing a string[] which will contains candidatesnames like so [\"alice\",\"bob\"] ....\n\nthis is my smart contract \n\n```\npragma solidity ^0.4.18;\n// We have to specify what version of compiler this code will compile with\n\ncontract Voting {\n /* mapping field below is equivalent to an associative array or hash.\n The key of the mapping is candidate name stored as type bytes32 and value is\n an unsigned integer to store the vote count\n */\n\n mapping (bytes32 => uint8) public votesReceived;\n\n /* Solidity doesn't let you pass in an array of strings in the constructor (yet).\n We will use an array of bytes32 instead to store the list of candidates\n */\n\n bytes32[] public candidateList;\n\n /* This is the constructor which will be called once when you\n deploy the contract to the blockchain. When we deploy the contract,\n we will pass an array of candidates who will be contesting in the election\n */\n function Voting(string[] candidateNames) public {\n for(uint i = 0; i but i m having this error that i didn't know how to solve \n\n```\nUnimplementedFeatureError: Nested arrays not yet implemented.\n```\n\nCan anyone help me plz\n\n========================================\n\nTop Answer:\nAs the error suggests, Solidity doesn't support passing in an array of arrays (a `string` is just a bytes array).\n\nFrom the Solidity docs:\n\nIs it possible to return an array of strings (string[]) from a Solidity function?\n\nNot yet, as this requires two levels of dynamic arrays (string is a dynamic array itself).\n\nWhat you CAN do is change it to an array of bytes32 (which are strings) and send the array of hex for your parameters:\n\n```\npragma solidity ^0.4.19;\n\ncontract Names {\n bytes32[] public names;\n \n function Names(bytes32[] _names) public {\n names = _names;\n }\n \n function get(uint i) public constant returns (bytes32) {\n return names[i];\n }\n}\n```\n\nDeploy with\n\n```\n[\"0x616c696365000000000000000000000000000000000000000000000000000000\",\"0x626f620000000000000000000000000000000000000000000000000000000000\"]\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.18;\n// We have to specify what version of compiler this code will compile with\n\ncontract Voting {\n  /* mapping field below is equivalent to an associative array or hash.\n  The key of the mapping is candidate name stored as type bytes32 and value is\n  an unsigned integer to store the vote count\n  */\n\n  mapping (bytes32 => uint8) public votesReceived;\n\n  /* Solidity doesn't let you pass in an array of strings in the constructor (yet).\n  We will use an array of bytes32 instead to store the list of candidates\n  */\n\n  bytes32[] public candidateList;\n\n\n  /* This is the constructor which will be called once when you\n  deploy the contract to the blockchain. When we deploy the contract,\n  we will pass an array of candidates who will be contesting in the election\n  */\n  function Voting(string[] candidateNames) public {\n        for(uint i = 0; i < candidateNames.length; i++) {\n            candidateList[i]= stringToBytes32(candidateNames[i]);\n\n        }\n\n }\n  function totalVotesFor(bytes32 candidate) view public returns (uint8) {\n\n    return votesReceived[candidate];\n  }\n\n  function stringToBytes32(string memory source) returns (bytes32 result) {\n    bytes memory tempEmptyStringTest = bytes(source);\n    if (tempEmptyStringTest.length == 0) {\n        return 0x0;\n    }\n\n    assembly {\n        result := mload(add(source, 32))\n    }\n}\n\n\n  function voteForCandidate(bytes32 candidate) public {\n\n    votesReceived[candidate] += 1;\n  }\n\n\n}\n```\n\n```text\nUnimplementedFeatureError: Nested arrays not yet implemented.\n```\n\n```text\nfunction stringToBytes32(string memory source)view public returns (bytes32 result) {\n    bytes memory tempEmptyStringTest = bytes(source);\n    if (tempEmptyStringTest.length == 0) {\n        return 0x0;\n    }\n\n    assembly {\n        result := mload(add(source, 32))\n    }\n}\n```\n\n```text\npragma solidity ^0.4.19;\n\ncontract Names {\n    bytes32[] public names;\n    \n    function Names(bytes32[] _names) public {\n        names = _names;\n    }\n    \n    function get(uint i) public constant returns (bytes32) {\n        return names[i];\n    }\n}\n```\n\n```text\n[\"0x616c696365000000000000000000000000000000000000000000000000000000\",\"0x626f620000000000000000000000000000000000000000000000000000000000\"]\n```\n\n```text\nstring\n```\n\n```text\nfunction something(bytes32[] _thing) public{\n  for(i=0; i<Array.length ; i++){\n    StructArray.push({ thing = _thing[i]});\n  }\n}\n```\n\n```text\nfunction getThing()\n    public\n    returns (bytes32[] memory)\n{\n    bytes32[] memory addrs = new address[](indexes.length);        \n    for (uint i = 0; i < StructArray.length; i++) {\n        Struct storage structs = StructArray[array[i]];\n        thing[i] = structs.thing;    \n    }\n    return (thing);\n}\n```\n\n```text\npragma solidity ^0.8.7;\n\ncontract Strings  {  \n    string[] public stringParam;\n   \n    constructor(string[] memory _stringParam) {\n        stringParam = _stringParam;\n    }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":208,"estimatedTokens":1284}}228{"id":"stack-70216805","source":"stackoverflow","questionId":70216805,"title":"Why assertion is used on this Smart Contract?","tags":["solidity","assert","evm"],"text":"Title: Why assertion is used on this Smart Contract?\nTags: solidity, assert, evm\nSource: Stack Overflow\n\nQuestion:\n```\ncontract Sharer {\n function sendHalf(address payable addr) public payable returns (uint balance) {\n require(msg.value % 2 == 0, \"Even value required.\");\n uint balanceBeforeTransfer = address(this).balance;\n addr.transfer(msg.value / 2);\n // Since transfer throws an exception on failure and\n // cannot call back here, there should be no way for us to\n // still have half of the money.\n assert(address(this).balance == balanceBeforeTransfer - msg.value / 2);\n return address(this).balance;\n }\n}\n```\n\nFor contract above, on which condition the assertion fails / address(this).balance is not decreased by (msg.value / 2)? Why we need assertion here?\n\n========================================\n\nTop Answer:\nIf the `addr.transfer(msg.value / 2)` fails, it reverts the execution of `sendHalf()`.\n\nSo the `assert()` is redundant in this case.\n\n========================================\n\nCode:\n```text\ncontract Sharer {\n    function sendHalf(address payable addr) public payable returns (uint balance) {\n        require(msg.value % 2 == 0, \"Even value required.\");\n        uint balanceBeforeTransfer = address(this).balance;\n        addr.transfer(msg.value / 2);\n        // Since transfer throws an exception on failure and\n        // cannot call back here, there should be no way for us to\n        // still have half of the money.\n        assert(address(this).balance == balanceBeforeTransfer - msg.value / 2);\n        return address(this).balance;\n    }\n}\n```\n\n```text\nassert()\n```\n\n```text\nif\n```\n\n```text\nsendHalf()\n```\n\n```text\nreceive()\n```\n\n```text\nfallback()\n```\n\n```text\nselfdestruct\n```\n\n```text\ntransfer()\n```\n\n```text\nsendHalf()\n```\n\n```text\ntransfer()\n```\n\n```text\ntransfer()\n```\n\n```text\nselfdestruct\n```\n\n```text\ntransfer()\n```\n\n```text\nselfdestruct\n```\n\n```text\naddr.transfer(msg.value / 2)\n```\n\n```text\nsendHalf()\n```\n\n```text\nassert()\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":110,"estimatedTokens":492}}229{"id":"stack-71074447","source":"stackoverflow","questionId":71074447,"title":"When is function reverted?","tags":["solidity","smartcontracts","reentrancy"],"text":"Title: When is function reverted?\nTags: solidity, smartcontracts, reentrancy\nSource: Stack Overflow\n\nQuestion:\nso because of reentrancy attacks I'm structuring my function to not get hacked. So first updating mappings and so on and then sending the payment.\n\nMy question is what if the payment fails to go through. Will entire function be reverted of just the payment?\n\nBecause if only the payment than that would mean my mappings would be updated as if the payment went through.\n\nIs this the case?\n\nThanks for answers!\n\n========================================\n\nTop Answer:\nIf you're preventing the reentrancy attacks, you might probably use the modifiers. Therefore, when the Reentrancy is detected, the function would be reverted and even not allowed to enter the function. That is, there would be no other parameters updated.\n\nBesides, I can show you some demo code to answer your question.\n\n```\ncontract test {\n uint public a = 0;\n\n // a will still be a\n function addRevert() public{\n a += 1;\n goRevert();\n }\n\n // a = a + 1\n function addNoRevert() public{\n a += 1;\n }\n\n function goRevert() pure public{\n revert();\n }\n}\n```\n\n========================================\n\nCode:\n```text\nfunction withdraw(uint256 _amount) external {\n    balances[msg.sender] -= _amount;\n    (bool success, ) = payable(msg.sender).call{value: _amount}(\"\");\n}\n```\n\n```text\n(bool success, ) = payable(msg.sender).call{value: _amount}(\"\");\nrequire(success);\n```\n\n```text\nfunction withdraw(uint256 _amount) external {\n    balances[msg.sender] -= _amount;\n    payable(msg.sender).transfer(_amount);\n}\n```\n\n```text\n.call()\n```\n\n```text\nsuccess\n```\n\n```text\nfalse\n```\n\n```text\nbalances\n```\n\n```text\nrequire()\n```\n\n```text\n.transfer()\n```\n\n```text\naddress payable\n```\n\n```text\ncontract test {\n    uint public a = 0;\n\n    // a will still be a\n    function addRevert() public{\n        a += 1;\n        goRevert();\n    }\n\n    // a = a + 1\n    function addNoRevert() public{\n        a += 1;\n    }\n\n    function goRevert() pure public{\n        revert();\n    }\n}\n```\n\n========================================\n\nComments:\n- This explains it perfectly thanks a lot!","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":118,"estimatedTokens":532}}230{"id":"stack-64236628","source":"stackoverflow","questionId":64236628,"title":"How to set owner address when deploying a smart contract","tags":["ethereum","solidity"],"text":"Title: How to set owner address when deploying a smart contract\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nHere is simple smart contract with `owner`:\n\n```\npragma ^0.7.2\n\ncontract simple {\n address owner;\n\n constructor() public {\n //do something \n }\n\n modifier() {\n require(\n owner == msg.sender,\n 'No sufficient right'\n )\n }\n\n function setOwner() ownerOnly external {\n owner = msg.sender;\n }\n}\n```\n\nMy question is how to securely set owner address to the address of the smart contract owner?\n\n========================================\n\nCode:\n```text\npragma ^0.7.2\n\ncontract simple {\n  address owner;\n\n  constructor() public {\n    //do something \n  }\n\n  modifier() {\n    require(\n      owner == msg.sender,\n      'No sufficient right'\n    )\n  }\n\n  function setOwner() ownerOnly external {\n     owner = msg.sender;\n  }\n}\n```\n\n```text\nowner\n```\n\n```text\nconstructor ()  {\n       owner = msg.sender;\n   }\n```\n\n```text\nfunction setOwner(address newOwner) ownerOnly external {\n     owner = newOwner;\n  }\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":73,"estimatedTokens":255}}231{"id":"stack-46491123","source":"stackoverflow","questionId":46491123,"title":"String parameter not automatically parsing into bytes32 when used with form","tags":["javascript","ethereum","solidity","web3js"],"text":"Title: String parameter not automatically parsing into bytes32 when used with form\nTags: javascript, ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI have a solidity function which looks like this-\n\n```\nfunction issueCertificate(address _recipient, bytes32 _certi_name)\n```\n\nWhen I call the function using truffle console, I am able to run it using-\n\n```\nissueCertificate(\"0x0213e3852b8afeb08929a0f448f2f693b0fc3ebe\", \"random\")\n```\n\nBut when I run it using web3 and forms with same data in string format, it gives error-\n\nError: Given parameter is not bytes: \"random\"\n\n========================================\n\nTop Answer:\nTry:\n\n```\nissueCertificate(\"0x0213e3852b8afeb08929a0f448f2f693b0fc3ebe\", bytes32(\"random\"))\n```\n\nBasically, wrap the string with bytes32()\n\nEdit, missed the call being made from Web3 try:\n\n```\nissueCertificate(\"0x0213e3852b8afeb08929a0f448f2f693b0fc3ebe\", web3.fromAscii(\"random\"))\n```\n\nBasically, in Web3 wrap the string with web3.fromAscii()\n\nUpdate: \n\nLatest version uses:\n\n```\nissueCertificate(\"0x0213e3852b8afeb08929a0f448f2f693b0fc3ebe\", web3.utils.fromAscii(\"random\"))\n```\n\n========================================\n\nCode:\n```text\nfunction issueCertificate(address _recipient, bytes32 _certi_name)\n```\n\n```text\nissueCertificate(\"0x0213e3852b8afeb08929a0f448f2f693b0fc3ebe\", \"random\")\n```\n\n```text\nweb3.utils.asciiToHex(\"random\")\n```\n\n```text\nissueCertificate(\"0x0213e3852b8afeb08929a0f448f2f693b0fc3ebe\", bytes32(\"random\"))\n```\n\n```text\nissueCertificate(\"0x0213e3852b8afeb08929a0f448f2f693b0fc3ebe\", web3.fromAscii(\"random\"))\n```\n\n```text\nissueCertificate(\"0x0213e3852b8afeb08929a0f448f2f693b0fc3ebe\", web3.utils.fromAscii(\"random\"))\n```\n\n========================================\n\nComments:\n- There is no \"bytes32()\" in javascript.\n- Sorry, missed that you were calling it from web3 try wrapping the string with web3.fromAscii(\"random\")\n- Thanks. It worked. It is \"web3.utils.fromAscii\" in latest version.\n- Deprecated again - use web3.utils.asciiToHex as suggested by the other answer","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":82,"estimatedTokens":507}}232{"id":"stack-70514336","source":"stackoverflow","questionId":70514336,"title":"solidity TypeError: Object of type set is not JSON serializable","tags":["python","solidity","smartcontracts","nsjsonserialization"],"text":"Title: solidity TypeError: Object of type set is not JSON serializable\nTags: python, solidity, smartcontracts, nsjsonserialization\nSource: Stack Overflow\n\nQuestion:\nI ran the code in VSCode and got a TypeError: `Object of type set is not JSON serializable`. I just start to learn to code, really don't get it, and googled it, also didn't know what does JSON serializable means.\n\n```\nfrom solcx import compile_standard\nimport json\n\n# get the contract content\nwith open(\"./SimpleStorage.sol\", \"r\") as file:\n simple_storage_file = file.read()\n\n# compile the contract\n\ncompiled_sol = compile_standard(\n {\n \"language\": \"Solidity\",\n \"sources\": {\"SimpleStorage.sol\": {\"content\": simple_storage_file}},\n \"settings\": {\n \"outputSelection\": {\n \"*\": {\n \"*\": {\"abi\", \"metadata\", \"evm.bytecode\", \"evm.bytecode.sourceMap\"}\n }\n }\n },\n },\n solc_version=\"0.6.0\",\n)\n\n# creat json file dump the comiled code in it to make it more readable.\nwith open(\"compiled_code.json\", \"w\") as file:\n json.dump(compiled_sol, file)\n\nprint(compiled_sol)\n```\n\nThe full error information is below:\n\n```\n(env) (base) liwei@liweideMacBook-Pro practice % python3 deploy.py\nTraceback (most recent call last):\n File \"deploy.py\", line 10, in \n compiled_sol = compile_standard(\n File \"/Users/liwei/Desktop/demos/practice/env/lib/python3.8/site-packages/solcx/main.py\", line 375, in compile_standard\n stdin=json.dumps(input_data),\n File \"/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py\", line 231, in dumps\n return _default_encoder.encode(obj)\n File \"/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py\", line 199, in encode\n chunks = self.iterencode(o, _one_shot=True)\n File \"/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py\", line 257, in iterencode\n return _iterencode(o, 0)\n File \"/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py\", line 179, in default\n raise TypeError(f'Object of type {o.__class__.__name__} '\nTypeError: Object of type set is not JSON serializable\n```\n\n========================================\n\nCode:\n```text\nfrom solcx import compile_standard\nimport json\n\n# get the contract content\nwith open(\"./SimpleStorage.sol\", \"r\") as file:\n    simple_storage_file = file.read()\n\n# compile the contract\n\ncompiled_sol = compile_standard(\n    {\n        \"language\": \"Solidity\",\n        \"sources\": {\"SimpleStorage.sol\": {\"content\": simple_storage_file}},\n        \"settings\": {\n            \"outputSelection\": {\n                \"*\": {\n                    \"*\": {\"abi\", \"metadata\", \"evm.bytecode\", \"evm.bytecode.sourceMap\"}\n                }\n            }\n        },\n    },\n    solc_version=\"0.6.0\",\n)\n\n# creat json file dump the comiled code in it to make it more readable.\nwith open(\"compiled_code.json\", \"w\") as file:\n    json.dump(compiled_sol, file)\n\nprint(compiled_sol)\n```\n\n```text\n(env) (base) liwei@liweideMacBook-Pro practice % python3 deploy.py\nTraceback (most recent call last):\n  File \"deploy.py\", line 10, in <module>\n    compiled_sol = compile_standard(\n  File \"/Users/liwei/Desktop/demos/practice/env/lib/python3.8/site-packages/solcx/main.py\", line 375, in compile_standard\n    stdin=json.dumps(input_data),\n  File \"/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py\", line 231, in dumps\n    return _default_encoder.encode(obj)\n  File \"/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py\", line 199, in encode\n    chunks = self.iterencode(o, _one_shot=True)\n  File \"/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py\", line 257, in iterencode\n    return _iterencode(o, 0)\n  File \"/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py\", line 179, in default\n    raise TypeError(f'Object of type {o.__class__.__name__} '\nTypeError: Object of type set is not JSON serializable\n```\n\n```text\nObject of type set is not JSON serializable\n```\n\n```text\n{\"abi\", \"metadata\", \"evm.bytecode\", \"evm.bytecode.sourceMap\"}\n```\n\n```text\n[\"abi\", \"metadata\", \"evm.bytecode\", \"evm.bytecode.sourceMap\"]\n```\n\n========================================\n\nComments:\n- Welcome welcome. Serialization - `process of translating data structures or object state into a format that can be stored and reconstructed later in the same or another computer environment`. Source. Which also gives a little hint *why* some things aren't serializable. In this case, the `set` type is unique enough that JSON isn't familiar with it. More complex examples can be a *open network connection*; How can you reliably restore it in another environment? Maybe the recipient is no longer available and *open* is impossible to store\n- Have you done any research? Take a look at How to JSON serialize sets?\n- thanks , didn't know about the concept\"set\" in python before ,seems it's different data type , let me work on that, thank you for the helpl!\n- yes,it's this problem .After fix it , the code runs correct,thank you !\n- Welcome to Stack Overflow! If my answer helped you consider marking it as right.\n- Sorry for the rookie mistake , I only find the Vote up arrow ,didn't find how to mark it right , also the help instructor told me I can accept this anwer as the the one who raises the question , also no button found ,could you please give a hint.\n- It's entirely ok :) See this.\n- Got it,interesting stuff!","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":135,"estimatedTokens":1344}}233{"id":"stack-56720654","source":"stackoverflow","questionId":56720654,"title":"How to get an account address from Metamask?","tags":["ethereum","solidity","web3js"],"text":"Title: How to get an account address from Metamask?\nTags: ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\n`accounts[0]` returns `undefined` in this code.\n\n```\nconst accounts = await web3.eth.getAccounts()\nconsole.log(accounts[0])\n```\n\nI uninstalled Metamask and reset the account, but that didn't work.\n\nweb3 version is web3@1.0.0-beta.37.\n\nCould you give me any advise, why I cannot get an account address from Metamask?\n\n========================================\n\nCode:\n```text\nconst accounts = await web3.eth.getAccounts()\nconsole.log(accounts[0])\n```\n\n```text\naccounts[0]\n```\n\n```text\nundefined\n```\n\n```text\nWeb3(window.web3.currentProvider)\n```\n\n```text\nweb3 = new Web3(window.ethereum)\n    window.ethereum.enable().catch(error => {\n        // User denied account access\n        console.log(error)\n    })\n```\n\n========================================\n\nComments:\n- `web3.eth.accounts[0]` works fine for me, make sure that you log in into your metamask account","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":50,"estimatedTokens":244}}234{"id":"stack-58188832","source":"stackoverflow","questionId":58188832,"title":"Solidity - Generate unpredictable random number that does not depend on input","tags":["random","ethereum","solidity","smartcontracts"],"text":"Title: Solidity - Generate unpredictable random number that does not depend on input\nTags: random, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI know that the \"how to generate random number\" in solidity is a very common question. However, after reading the great majority of answers I did not find one to fit my case. \n\nA short description of what I want to do is: I have a list of objects that each have a unique id, a number. I need to produce a list that contains 25% of those objects, **randomly selected each time the function is called**. The person calling the function cannot be depended on to provide input that will somehow influence predictably the resulting list. \n\nThe only answer I found that gives a secure random number was Here. However, it depends on input coming from the participants and it is meant to address a gambling scenario. I cannot use it in my implementation. \n\nAll other cases mention that the number generated is going to be predictable, and even some of those depend on a singular input to produce a single random number. Once again, does not help me.\n\nSummarising, I need a function that will give me **multiple, non-predictable, random numbers.** \n\nThanks for any help.\n\n========================================\n\nTop Answer:\nSmart Contracts are deterministic, so, basically every functions are predictable - if we know input, we will be and we should be know output. And you cannot get random number without any input - almost every language generates \"pseudo random number\" using clock. This means, you will not get random number in blockchain using simple method.\n\nThere are many interesting methods to generate random number using Smart Contract - using DAO, Oracle, etc. - but they all have some trade-offs.\n\nSo in conclusion, There is no method you are looking for. You need to sacrifice something.\n\n:(\n\n========================================\n\nCode:\n```text\nfunction rand()\n    public\n    view\n    returns(uint256)\n{\n    uint256 seed = uint256(keccak256(abi.encodePacked(\n        block.timestamp + block.difficulty +\n        ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)) +\n        block.gaslimit + \n        ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)) +\n        block.number\n    )));\n\n    return (seed - ((seed / 1000) * 1000));\n}\n```\n\n========================================\n\nComments:\n- Does this answer your question? How-to generate a random number\n- And here stackoverflow.com/questions/52467248/&hellip;\n- I think it is not a perfect solution, you still can make another smartcontract with this same logic (just hijacking msg.sender), execute it on the same tx calling the smartcontract to be attacked, and you will be knowing what random number will be given\n- @AlbertoPerez True, so you have to check is the tx sender address a contract or not.","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":56,"estimatedTokens":714}}235{"id":"stack-70986854","source":"stackoverflow","questionId":70986854,"title":"What is the benefit of using uncheked?","tags":["ethereum","solidity","openzeppelin"],"text":"Title: What is the benefit of using uncheked?\nTags: ethereum, solidity, openzeppelin\nSource: Stack Overflow\n\nQuestion:\nIn OpenZeppelin ERC20 implementation, there is a _transfer method:\n\n```\nfunction _transfer(\n address sender,\n address recipient,\n uint256 amount\n) internal virtual {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(sender, recipient, amount);\n\n uint256 senderBalance = _balances[sender];\n require(senderBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[sender] = senderBalance - amount;\n }\n _balances[recipient] += amount;\n\n emit Transfer(sender, recipient, amount);\n\n _afterTokenTransfer(sender, recipient, amount);\n}\n```\n\nWhy do they use uncheked arithmetic for decreasing the balance? I know that in case of unchecked, 2-3 will return 2**256-1 and not case an exception. But why do we need this?\n\n========================================\n\nCode:\n```text\nfunction _transfer(\n    address sender,\n    address recipient,\n    uint256 amount\n) internal virtual {\n    require(sender != address(0), \"ERC20: transfer from the zero address\");\n    require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n    _beforeTokenTransfer(sender, recipient, amount);\n\n    uint256 senderBalance = _balances[sender];\n    require(senderBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n    unchecked {\n        _balances[sender] = senderBalance - amount;\n    }\n    _balances[recipient] += amount;\n\n    emit Transfer(sender, recipient, amount);\n\n    _afterTokenTransfer(sender, recipient, amount);\n}\n```\n\n```text\nuint256 senderBalance = _balances[sender];\nrequire(senderBalance >= amount, \"ERC20: transfer amount exceeds balance\");\nunchecked {\n\n    // no validation here as it's already validated in the `require()` condition\n    _balances[sender] = senderBalance - amount;\n}\n```\n\n```text\nuint256 senderBalance = _balances[sender];\nrequire(senderBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n\n// redundant validation here\n_balances[sender] = senderBalance - amount;\n```\n\n```text\n// contains the check and fails without custom message in case of underflow\n_balances[sender] -= amount;\n```\n\n```text\nunchecked {\n    // UNSAFE, DO NOT USE\n    _balances[sender] -= amount;\n}\n```\n\n```text\nunchecked\n```\n\n========================================\n\nComments:\n- i got it, thank you so much for detailed answer!!","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":98,"estimatedTokens":625}}236{"id":"stack-62525758","source":"stackoverflow","questionId":62525758,"title":"HashSet data structure in Solidity","tags":["ethereum","solidity"],"text":"Title: HashSet data structure in Solidity\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nIs there any way of implementing a set in Solidity, in order to check if an element exists, in O(1) average? I have been thinking of using a mapping object with no values, is that faster than using an array and iterating in order to find elements?\n\n========================================\n\nCode:\n```text\nmapping (address => bool) yourMapping; // maps address (key) to boolean (value)\n```\n\n```text\ncontract Contract {\n\n    struct Set {\n        uint[] values;\n        mapping (uint => bool) is_in;\n    }\n\n    Set my_set;\n\n    function add(uint a) public {\n         if (!my_set.is_in[a]) {\n             my_set.values.push(a);\n             my_set.is_in[a] = true;\n         }\n    }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":32,"estimatedTokens":196}}237{"id":"stack-44058803","source":"stackoverflow","questionId":44058803,"title":"Why can't I send ether to my smart contract's address?","tags":["ethereum","solidity"],"text":"Title: Why can't I send ether to my smart contract's address?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\n```\ncontract_file = 'contract.sol'\ncontract_name = ':SimpleContract'\n\nSolc = require('solc')\nWeb3 = require('web3')\n\nweb3 = new Web3(new Web3.providers.HttpProvider(\"http://localhost:8545\"));\nsource_code = fs.readFileSync(contract_file).toString()\n\nadmin_account = web3.eth.accounts[0]\n\ncompiledContract = Solc.compile(source_code)\nabi = compiledContract.contracts[contract_name].interface\nbytecode = compiledContract.contracts[contract_name].bytecode;\nContractClass = web3.eth.contract(JSON.parse(abi))\n\ncontract_init_data = {\n data: bytecode,\n from: admin_account,\n gas: 1000000,\n}\n\ndeployed_contract = ContractClass.new(contract_init_data)\ncontract_instance = ContractClass.at(deployed_contract.address)\n```\n\nup until here, this works. However, one surprise was that the line\n msg.sender.transfer(amount);\nin my contract wouldn't compile on web3, despite getting that line straight from the common pattern section of the solidity docs. Had to use Solc instead, because transfer() wasn't in 0.4.6...\n\nIsn't transfer() a core part of ethereum? I would have expected that to exist in v 0.1 \n\nAnyway, I then try to add ether to the contract like this:\n\n```\nload_up = {\n from: admin_account, \n to: deployed_contract.address, \n value: web3.toWei(1, 'ether'),\n}\nweb3.eth.sendTransaction(load_up)\n```\n\nand I get:\n\n```\nError: VM Exception while processing transaction: invalid opcode\n```\n\nwhich doesn't give me much to work with. What am I doing wrong, and how do I debug issues like this in the future?\n\n========================================\n\nCode:\n```text\ncontract_file = 'contract.sol'\ncontract_name = ':SimpleContract'\n\nSolc = require('solc')\nWeb3 = require('web3')\n\nweb3 = new Web3(new Web3.providers.HttpProvider(\"http://localhost:8545\"));\nsource_code = fs.readFileSync(contract_file).toString()\n\nadmin_account = web3.eth.accounts[0]\n\ncompiledContract = Solc.compile(source_code)\nabi = compiledContract.contracts[contract_name].interface\nbytecode = compiledContract.contracts[contract_name].bytecode;\nContractClass =  web3.eth.contract(JSON.parse(abi))\n\ncontract_init_data = {\n    data: bytecode,\n    from: admin_account,\n    gas: 1000000,\n}\n\ndeployed_contract = ContractClass.new(contract_init_data)\ncontract_instance = ContractClass.at(deployed_contract.address)\n```\n\n```text\nload_up = {\n    from: admin_account, \n    to: deployed_contract.address, \n    value: web3.toWei(1, 'ether'),\n}\nweb3.eth.sendTransaction(load_up)\n```\n\n```text\nError: VM Exception while processing transaction: invalid opcode\n```\n\n```text\nload_up = {\n    from: admin_account, \n    to: deployed_contract.address, \n    value: web3.toWei(10, 'ether'),\n}\ndeployed_contract.AddEth.sendTransaction(load_up)\n```\n\n```text\npayable\n```\n\n```text\nfunction AddEth () payable {}\n```\n\n========================================\n\nComments:\n- Can you post the code of your contract? Which version of solc are you using? And what kind of node do you use (main,test or local testrpc?)\n- check this ethereum.stackexchange.com/questions/3613/&hellip;\n- how do i get transaction receipt from this function?","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":123,"estimatedTokens":796}}238{"id":"stack-67164953","source":"stackoverflow","questionId":67164953,"title":"Check if msg.sender is a specific type of contract","tags":["ethereum","solidity","smartcontracts","web3js"],"text":"Title: Check if msg.sender is a specific type of contract\nTags: ethereum, solidity, smartcontracts, web3js\nSource: Stack Overflow\n\nQuestion:\nAs it is now, anyone can call the `setMyString` function in the `FirstContract`. I'm trying to restrict access to that function to an instance of `SecondContract`. But not one specific instance, any contract of type `SecondContract` should be able to call `setMyString`.\n\n```\ncontract FirstContract{\n String public myString;\n\n function setMyString(String memory what) public {\n myString=what;\n }\n}\n\ncontract SecondContract{\n address owner;\n address firstAddress;\n FirstContract firstContract;\n constructor(address _1st){\n owner=msg.sender;\n firstAddress=_1st;\n firstContract=FirstContract(firstAddress);\n }\n function callFirst(String memory what){\n require(msg.sender==owner);\n firstContract.setMyString(\"hello\");\n }\n}\n```\n\n========================================\n\nTop Answer:\nYou should have a look at ERC-165 Standard Interface Detection.\n\nAssuming the contract you want to check implements the ERC165 standard below you can then call supportsInterface to check for compatibility.\n\n```\ninterface ERC165 {\n function supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n```\n\n========================================\n\nCode:\n```text\ncontract FirstContract{\n    String public myString;\n\n    function setMyString(String memory what) public {\n        myString=what;\n    }\n}\n\ncontract SecondContract{\n    address owner;\n    address firstAddress;\n    FirstContract firstContract;\n    constructor(address _1st){\n        owner=msg.sender;\n        firstAddress=_1st;\n        firstContract=FirstContract(firstAddress);\n    }\n    function callFirst(String memory what){\n        require(msg.sender==owner);\n        firstContract.setMyString(\"hello\");\n    }\n}\n```\n\n```text\nsetMyString\n```\n\n```text\nFirstContract\n```\n\n```text\nSecondContract\n```\n\n```text\nSecondContract\n```\n\n```text\nsetMyString\n```\n\n```text\ncontract FirstContract{\n    String public myString;\n    \n    address owner;\n    mapping (address => bool) isSecondContract;\n    \n    modifier onlySecondContract {\n        require(isSecondContract[msg.sender]);\n        _;\n    }\n    \n    modifier onlyOwner {\n        require(msg.sender == owner);\n        _;\n    }\n    \n    function setIsSecondContract(address _address, bool _value) public onlyOwner {\n        isSecondContract[_address] = _value;\n    }\n\n    function setMyString(String memory what) public onlySecondContract {\n        myString=what;\n    }\n}\n```\n\n```text\nmsg.sender\n```\n\n```text\nbytes\n```\n\n```text\nbytes\n```\n\n```text\nmsg.sender\n```\n\n```text\nsetIsSecondContract()\n```\n\n```text\nSecondContract\n```\n\n```text\nsetMyString()\n```\n\n```text\nFirstContract\n```\n\n```text\nsetMyString()\n```\n\n```text\ninterface ERC165 {\n   function supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":161,"estimatedTokens":714}}239{"id":"stack-71908632","source":"stackoverflow","questionId":71908632,"title":"CompilerError: Stack too deep, try removing local variables","tags":["stack","solidity","smartcontracts","remix"],"text":"Title: CompilerError: Stack too deep, try removing local variables\nTags: stack, solidity, smartcontracts, remix\nSource: Stack Overflow\n\nQuestion:\nI am trying to do a dapp project.\n\nI have an error about stack too deep, but I don't know how can I solve this problem.\n\nCompilerError: Stack too deep, try removing local variables.\n--> contracts/proje.sol:145:5:\n|\n145 | function addRecord(address _addr, s ... gedOn, string memory ipfs) public {\n| ^ (Relevant source part starts here and spans across multiple lines).\n\nAnd actually, struct will consist of more data than there is. If this gives an error in the number of data, what do we do when we want to enter too much data?\n\n```\ncontract Patient is Clinic {\n uint256 public p_index = 0;\n\n struct Records {\n string cname;\n\n string l_cadence;\n string r_cadence;\n string n_cadence;\n\n string l_dsupport;\n string r_dsupport;\n string n_dsupport;\n\n string l_footoff;\n string r_footoff;\n string n_footoff;\n\n string l_steptime;\n string r_steptime;\n string n_steptime;\n\n string admittedOn;\n string dischargedOn;\n string ipfs;\n }\n\n struct patient {\n uint256 id;\n string name;\n string phone;\n string gender;\n string dob;\n string bloodgroup;\n string allergies;\n Records[] records;\n address addr;\n }\n\n address[] private patientList;\n mapping(address => mapping(address=>bool)) isAuth;\n mapping(address=>patient) patients;\n mapping(address=>bool) isPatient;\n\n function addRecord(address _addr, string memory cname, string memory l_cadence, string memory r_cadence, string memory n_cadence, string memory l_dsupport, string memory r_dsupport, string memory n_dsupport, string memory l_footoff, string memory r_footoff, string memory n_footoff, string memory l_steptime, string memory r_steptime, string memory n_steptime, string memory admittedOn, string memory dischargedOn, string memory ipfs) public {\n \n }\n}\n```\n\n========================================\n\nCode:\n```text\ncontract Patient is Clinic {\n    uint256 public p_index = 0;\n\n    struct Records {\n        string cname;\n\n        string l_cadence;\n        string r_cadence;\n        string n_cadence;\n\n        string l_dsupport;\n        string r_dsupport;\n        string n_dsupport;\n\n        string l_footoff;\n        string r_footoff;\n        string n_footoff;\n\n        string l_steptime;\n        string r_steptime;\n        string n_steptime;\n\n\n        string admittedOn;\n        string dischargedOn;\n        string ipfs;\n    }\n\n    struct patient {\n        uint256 id;\n        string name;\n        string phone;\n        string gender;\n        string dob;\n        string bloodgroup;\n        string allergies;\n        Records[] records;\n        address addr;\n    }\n\n    address[] private patientList;\n    mapping(address => mapping(address=>bool)) isAuth;\n    mapping(address=>patient) patients;\n    mapping(address=>bool) isPatient;\n\n    function addRecord(address _addr, string memory cname, string memory l_cadence, string memory r_cadence, string memory n_cadence, string memory l_dsupport, string memory r_dsupport, string memory n_dsupport, string memory l_footoff, string memory r_footoff, string memory n_footoff, string memory l_steptime, string memory r_steptime, string memory n_steptime, string memory admittedOn, string memory dischargedOn, string memory ipfs) public {\n        \n    }\n}\n```\n\n```text\nfunction addRecord(address _addr, Records memory record) public {\n    // your logic    \n}\n```\n\n```text\nfunction addRecord(address _addr, string memory cname, string memory l_cadence, string memory r_cadence, string memory n_cadence, string memory l_dsupport,\n     string memory r_dsupport, string memory n_dsupport, string memory l_footoff, string memory r_footoff, string memory n_footoff, string memory l_steptime, \n     string memory r_steptime, string memory n_steptime, string memory admittedOn, string memory dischargedOn, string memory ipfs) internal {\n        // your logic\n    }\n```\n\n```text\naddRecord()\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":140,"estimatedTokens":980}}240{"id":"stack-62162134","source":"stackoverflow","questionId":62162134,"title":"Chainlink job not returning value","tags":["nodes","ethereum","solidity"],"text":"Title: Chainlink job not returning value\nTags: nodes, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI have an oracle and JobID I’d like to submit to an oracle to get ETH price data. I have funded the node, and am following the documentation. However, every time I request the price, my BTC value will not update. The contract seems to be funded with LINK and I’m not getting gas errors, but for some reason the number will not change. What is going on?\n\n```\nsolidity\npragma solidity ^0.6.0;\nimport \"github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol\";\ncontract testingData is ChainlinkClient {\n address public owner;\n uint256 public btc;\n address ORACLE = 0xB36d3709e22F7c708348E225b20b13eA546E6D9c;\n bytes32 constant JOB = \"f9528decb5c64044b6b4de54ca7ea63e\";\n uint256 constant private ORACLE_PAYMENT = 1 * LINK;\n constructor() public {\n setPublicChainlinkToken();\n owner = msg.sender;\n }\n function getBTCPrice() \n public\n onlyOwner\n {\n Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);\n req.add(\"get\", \"https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=BTC&to_currency=USD&apikey=xxxx\");\n string[] memory copyPath = new string[](2);\n copyPath[0] = \"Realtime Currency Exchange Rate\";\n copyPath[1] = \"5. Exchange Rate\";\n sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);\n }\n function fulfill(bytes32 _requestId, uint256 _price)\n public\n recordChainlinkFulfillment(_requestId)\n {\n btc = _price;\n }\n modifier onlyOwner() {\n require(msg.sender == owner);\n _;\n }\n}\n```\n\n========================================\n\nCode:\n```text\nsolidity\npragma solidity ^0.6.0;\nimport \"github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol\";\ncontract testingData is ChainlinkClient {\n  address public owner;\n  uint256 public btc;\n  address ORACLE =  0xB36d3709e22F7c708348E225b20b13eA546E6D9c;\n  bytes32 constant JOB = \"f9528decb5c64044b6b4de54ca7ea63e\";\n  uint256 constant private ORACLE_PAYMENT = 1 * LINK;\n  constructor() public {\n    setPublicChainlinkToken();\n    owner = msg.sender;\n  }\n  function getBTCPrice() \n    public\n    onlyOwner\n  {\n    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);\n    req.add(\"get\", \"https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=BTC&to_currency=USD&apikey=xxxx\");\n    string[] memory copyPath = new string[](2);\n    copyPath[0] = \"Realtime Currency Exchange Rate\";\n    copyPath[1] = \"5. Exchange Rate\";\n    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);\n  }\n  function fulfill(bytes32 _requestId, uint256 _price)\n    public\n    recordChainlinkFulfillment(_requestId)\n  {\n    btc = _price;\n  }\n  modifier onlyOwner() {\n    require(msg.sender == owner);\n    _;\n  }\n}\n```\n\n```text\nrun.addInt(\"times\", 100000000);\n```\n\n```text\nsolidity\npragma solidity ^0.6.0;\nimport \"github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol\";\ncontract testingData is ChainlinkClient {\n  address public owner;\n  uint256 public btc;\n  address ORACLE =  0xB36d3709e22F7c708348E225b20b13eA546E6D9c;\n  bytes32 constant JOB = \"f9528decb5c64044b6b4de54ca7ea63e\";\n  uint256 constant private ORACLE_PAYMENT = 1 * LINK;\n  constructor() public {\n    setPublicChainlinkToken();\n    owner = msg.sender;\n  }\n  function getBTCPrice() \n    public\n    onlyOwner\n  {\n    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);\n    req.add(\"get\", \"https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=BTC&to_currency=USD&apikey=xxxx\");\n    string[] memory copyPath = new string[](2);\n    copyPath[0] = \"Realtime Currency Exchange Rate\";\n    copyPath[1] = \"5. Exchange Rate\";\n    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);\n  }\n  function fulfill(bytes32 _requestId, uint256 _price)\n    public\n    recordChainlinkFulfillment(_requestId)\n  {\n    btc = _price;\n  }\n  modifier onlyOwner() {\n    require(msg.sender == owner);\n    _;\n  }\n}\n```\n\n```text\ngetBTCPrice()\n```\n\n========================================\n\nComments:\n- @user13668058 Just wanted to know if this worked after the below suggestion from Patrick? We are currently trying to use the same code but the Job does not seem to hit the API. It is charging the LINK token to the contract and the txn is successful. But it is not hitting the API and no data is fetched. What can be the reason?","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":136,"estimatedTokens":1114}}241{"id":"stack-51681604","source":"stackoverflow","questionId":51681604,"title":"Expected Primary Expression (Solidity)","tags":["mapping","ethereum","solidity","smartcontracts"],"text":"Title: Expected Primary Expression (Solidity)\nTags: mapping, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI am creating a simple smart contract, however, I am getting an error on my last function (\"ViewNotes\") stating that the compiler was \"Expected Primary Expression\"? Can I not check the value at a mapping (of address => string) against the value *0* ?\n\nMy code: \n\n```\npragma solidity ^0.4.4;\n\ncontract Logistics{\n\naddress public owner;\nmapping(address => string) notes;\n\nmodifier onlyOwner() {\n require(msg.sender == owner);\n _;\n}\n\nconstructor(address genesis) public {\n owner = genesis;\n}\n\nfunction sign(string signedNote) public onlyOwner{\n notes[owner] = signedNote; //gaurenteed that msg.sender == owner\n}\n\nfunction transferOwnership(address nuOwner) onlyOwner {\n owner = nuOwner;\n}\n\nfunction viewNotes(address participant) public returns(string){ // signed note on success nothing on fail\n if(notes[participant] !== 0){\n return (notes(participant)); \n }\n}\n```\n\n}\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.4;\n\ncontract Logistics{\n\naddress public owner;\nmapping(address => string) notes;\n\nmodifier onlyOwner() {\n    require(msg.sender == owner);\n    _;\n}\n\nconstructor(address genesis) public {\n   owner = genesis;\n}\n\nfunction sign(string signedNote) public onlyOwner{\n        notes[owner] = signedNote; //gaurenteed that msg.sender == owner\n}\n\nfunction transferOwnership(address nuOwner) onlyOwner {\n    owner = nuOwner;\n}\n\nfunction viewNotes(address participant) public returns(string){ // signed note on success nothing on fail\n    if(notes[participant] !== 0){\n        return (notes(participant));   \n    }\n}\n```\n\n```text\nfunction viewNotes(address participant) public returns (string) {\n    if (bytes(notes[participant]).length != 0) {\n        return notes[participant];\n    }\n}\n```\n\n```text\nfunction viewNotes(address participant) public returns (string) {\n    return notes[participant];\n}\n```\n\n```text\nmapping(address => string) public notes;\n```\n\n```text\npragma solidity ^0.4.24;\n\ncontract Logistics{\n    address public owner = msg.sender;\n    mapping(address => string) public notes;\n\n    function sign(string note) public {\n        require(msg.sender == owner);\n        notes[owner] = note;\n    }\n\n    function transferOwnership(address newOwner) public {\n        require(msg.sender == owner);\n        owner = newOwner;\n    }\n}\n```\n\n```text\n!=\n```\n\n```text\n!==\n```\n\n```text\nstring\n```\n\n```text\n0\n```\n\n```text\nbytes\n```\n\n```text\nnotes\n```\n\n```text\npublic\n```\n\n```text\nnotes(addr)\n```\n\n```text\nviewNotes\n```\n\n========================================\n\nComments:\n- Awesome! Do you know how I could use metamask to let users 'sign into' my UI and then sign and transfer the notes-ledger in my application if they are the current owner? I am a little confused on how that would work, or if its even possible?\n- I guess I am a little confused on how to integrate metmask through web3.js in this case","metadata":{"transformedAt":"2026-08-18T18:33:36.131Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":156,"estimatedTokens":743}}242{"id":"stack-59048312","source":"stackoverflow","questionId":59048312,"title":"Can we use Solidity with NodeJS?","tags":["node.js","blockchain","solidity","smartcontracts"],"text":"Title: Can we use Solidity with NodeJS?\nTags: node.js, blockchain, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI want to develop a blockchain system with smart contract using NodeJs for blockchain and Solidity for smart contract, i Google'd this but i found no answer ?\n\nactually, i developped a blockchain system using javascript and new langage for smart contract, but this langage doesn't contain a lot of instruction so using solidity will be very useful, i wonder if possible to user solidity on blockchain chains which are developped by javascript ?\n\nAnd if there is any post contains a description of how using that.\nThanks you in advance.\n\n========================================\n\nCode:\n```text\ntruffle\n```\n\n```text\ntruffle compile\n```\n\n```text\nconst your_contract = web3.eth.contract(contract.json.abi)\n```\n\n```text\nconst contract = your_contract.at(<your_contract_address)\n```\n\n```text\ncontract.<your_function>\n```\n\n========================================\n\nComments:\n- Here is an npm package for solidity in javascript. I hope this is of some help.\n- This is incorrect. The JSON file produced by truffle only contains the bytecode, ABI, and other related metadata. You cannot actually execute it unless your Javsacript-based blockchain includes an evm within it.\n- @RaghavSood You can `import from '.&#47;'` and then use its method. But you will need to use `web3.eth.contract(.abi)` before you use methods and functions\n- @QuangV&#245; In the 2nd. bullet point of your answer you wrote: `Import the json file to your code`. Well just how exactly do you do that? Is there a way to automate this process, so that after each compilation of your contract - which will create a new `JSON` file - that `JSON` file will automatically get loaded into your `Javascript` code? (And I'm not talking about using `Node.JS`, but rather just plain vanilla `Javascript`)\n- @Sirab33 this automation seems like something you would need to handle on your own, but definitely seems doable","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":43,"estimatedTokens":499}}243{"id":"stack-68552918","source":"stackoverflow","questionId":68552918,"title":"Supply ETH to Aave through solidity","tags":["javascript","ethereum","solidity","web3js"],"text":"Title: Supply ETH to Aave through solidity\nTags: javascript, ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI'm trying deposit into Aave V2 Contract Aave's Code Examples\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity >= 0.4.22 I have code which consumes this like so:\n\n```\nApp = {\n web3Provider: null,\n contracts: {},\n\n init: async function() {\n return await App.initWeb3();\n },\n\n initWeb3: async function() {\n // Modern dapp browsers...\n if (window.ethereum) {\n App.web3Provider = window.ethereum;\n try {\n // Request account access\n await window.ethereum.enable();\n } catch (error) {\n // User denied account access...\n console.error(\"User denied account access\")\n }\n }\n // Legacy dapp browsers...\n else if (window.web3) {\n App.web3Provider = window.web3.currentProvider;\n }\n // If no injected web3 instance is detected, fall back to Ganache\n else {\n App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');\n }\n web3 = new Web3(App.web3Provider);\n\n return App.initContract();\n },\n\n initContract: function() {\n $.getJSON('MyV2CreditDelegation.json', function(data) {\n // Get the necessary contract artifact file and instantiate it with @truffle/contract\n var safeYieldArtifact = data;\n App.contracts.MyV2CreditDelegation = TruffleContract(safeYieldArtifact);\n \n // Set the provider for our contract\n App.contracts.MyV2CreditDelegation.setProvider(App.web3Provider);\n });\n \n\n \n\n return App.bindEvents();\n },\n\n bindEvents: function() {\n $(document).on('click', '.btn-deposit', App.handleDeposit);\n $(document).on('click', '.btn-withdrawl', App.handleWithdrawl);\n },\n\n handleDeposit: function(event) {\n event.preventDefault();\n web3.eth.getAccounts(function(error, accounts) {\n if (error) {\n console.log(error);\n }\n \n var account = accounts[0];\n\n App.contracts.MyV2CreditDelegation.deployed().then(function(instance) {\n creditDelegatorInstance = instance;\n const mockETHAddress = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\"\n // Execute adopt as a transaction by sending account\n return creditDelegatorInstance.depositCollateral(mockETHAddress, 1, true);\n }).then(function(result) {\n //return App.markAdopted();\n }).catch(function(err) {\n console.log(err.message);\n });\n });\n },\n\n handleWithdrawl: function(event) {\n event.preventDefault();\n },\n};\n\n$(function() {\n $(window).load(function() {\n App.init();\n });\n});\n```\n\nWhen attempting to supply, Metamask displays an error:\n\nALERT: Transaction Error. Exception thrown in contract code.\n\nAnd just a simple button to call it in html:\n\n```\n Withdrawl\n\n```\n\nI'm running ganache\n\n`ganache-cli --fork https://mainnet.infura.io/v3/{{MyProjectId}}`\n\nThe only error I see in the console is:\n\nTransaction: 0x9961f8a187c09fd7c9ebf803771fa161c9939268bb01552a1598807bcfdc13ff\nGas usage: 24813\nBlock Number: 12905002\nBlock Time: Mon Jul 26 2021 20:38:30 GMT-0400 (Eastern Daylight Time)\nRuntime Error: revert\n\nMy guess is that I'm not calling the contract from Web3 appropriately\n\nHow can programatically supply Eth (Or any other token) to aave?\n\n========================================\n\nTop Answer:\nIf anyone is looking for how to integrate with Aave V3 in a Solidity contract, here is an example.\n\nThe following is a simple smart contract that allows you to supply Aave with ERC20 token collateral, and take out a variable rate loan.\n\nThis is how you can test the smart contract:\n\n- Obtain test USDC from Aave's faucet (make sure your wallet is on the Goerli network).\n\n- Deploy this smart contract to the Goerli network.\n\n- Send some of the test USDC to the address of the contract you just deployed.\n\n- Call the supply() function.\n\n- Call the borrow() function.\n\n```\n// contracts/AaveExample.sol\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\npragma abicoder v2;\n\nimport \"@aave-protocol/interfaces/IPool.sol\";\nimport \"@openzeppelin-contracts/token/ERC20/IERC20.sol\";\n\ncontract Aave {\n\n // Storage Variables\n address public borrowTokenAddress = 0xDF1742fE5b0bFc12331D8EAec6b478DfDbD31464; // Goerli Aave DAI\n address public supplyTokenAddress = 0xA2025B15a1757311bfD68cb14eaeFCc237AF5b43; // Goerli Aave USDC\n address public aavePoolAddress = 0x368EedF3f56ad10b9bC57eed4Dac65B26Bb667f6; // Goerli Aave Pool Address\n\n constructor() {}\n \n function supply() public returns (bool) {\n // 1. Set amountToDrain to the contract's supplyTokenAddress balance\n uint amountToDrain = IERC20(supplyTokenAddress).balanceOf(address(this));\n\n // 2. Approve Aave pool to access amountToDrain from this contract \n IERC20(supplyTokenAddress).approve(aavePoolAddress, amountToDrain);\n\n // 3. Supply amountToDrain to Aave pool\n IPool(aavePoolAddress).supply(supplyTokenAddress, amountToDrain, address(this), 0);\n\n return true;\n }\n\n function borrow() public returns (bool) {\n // Borrow 0.3 DAI\n IPool(aavePoolAddress).borrow(borrowTokenAddress, 0.3 ether, 2, 0, address(this));\n\n return true;\n }\n}\n```\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: MIT\npragma solidity >= 0.4.22 < 0.8.7;\n\nimport { IERC20, ILendingPool, IProtocolDataProvider, IStableDebtToken } from './Interfaces.sol';\nimport { SafeERC20 } from './Libraries.sol';\n\n/**\n* This is a proof of concept starter contract, showing how uncollaterised loans are possible\n* using Aave v2 credit delegation.\n* This example supports stable interest rate borrows.\n* It is not production ready (!). User permissions and user accounting of loans should be implemented.\n* See @dev comments\n*/\n\ncontract MyV2CreditDelegation {\n    using SafeERC20 for IERC20;\n    \n    ILendingPool constant lendingPool = ILendingPool(address(0x9FE532197ad76c5a68961439604C037EB79681F0)); // Kovan\n    IProtocolDataProvider constant dataProvider = IProtocolDataProvider(address(0x744C1aaA95232EeF8A9994C4E0b3a89659D9AB79)); // Kovan\n    \n    address owner;\n\n    constructor () public {\n        owner = msg.sender;\n    }\n\n    /**\n    * Deposits collateral into the Aave, to enable credit delegation\n    * This would be called by the delegator.\n    * @param asset The asset to be deposited as collateral\n    * @param amount The amount to be deposited as collateral\n    * @param isPull Whether to pull the funds from the caller, or use funds sent to this contract\n    *  User must have approved this contract to pull funds if `isPull` = true\n    * \n    */\n    function depositCollateral(address asset, uint256 amount, bool isPull) public {\n        if (isPull) {\n            IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);\n        }\n        IERC20(asset).safeApprove(address(lendingPool), amount);\n        lendingPool.deposit(asset, amount, address(this), 0);\n    }\n\n    /**\n    * Approves the borrower to take an uncollaterised loan\n    * @param borrower The borrower of the funds (i.e. delgatee)\n    * @param amount The amount the borrower is allowed to borrow (i.e. their line of credit)\n    * @param asset The asset they are allowed to borrow\n    * \n    * Add permissions to this call, e.g. only the owner should be able to approve borrowers!\n    */\n    function approveBorrower(address borrower, uint256 amount, address asset) public {\n        (, address stableDebtTokenAddress,) = dataProvider.getReserveTokensAddresses(asset);\n        IStableDebtToken(stableDebtTokenAddress).approveDelegation(borrower, amount);\n    }\n    \n    /**\n    * Repay an uncollaterised loan\n    * @param amount The amount to repay\n    * @param asset The asset to be repaid\n    * \n    * User calling this function must have approved this contract with an allowance to transfer the tokens\n    * \n    * You should keep internal accounting of borrowers, if your contract will have multiple borrowers\n    */\n    function repayBorrower(uint256 amount, address asset) public {\n        IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);\n        IERC20(asset).safeApprove(address(lendingPool), amount);\n        lendingPool.repay(asset, amount, 1, address(this));\n    }\n    \n    /**\n    * Withdraw all of a collateral as the underlying asset, if no outstanding loans delegated\n    * @param asset The underlying asset to withdraw\n    * \n    * Add permissions to this call, e.g. only the owner should be able to withdraw the collateral!\n    */\n    function withdrawCollateral(address asset) public {\n        (address aTokenAddress,,) = dataProvider.getReserveTokensAddresses(asset);\n        uint256 assetBalance = IERC20(aTokenAddress).balanceOf(address(this));\n        lendingPool.withdraw(asset, assetBalance, owner);\n    }\n}\n```\n\n```text\nApp = {\n  web3Provider: null,\n  contracts: {},\n\n  init: async function() {\n    return await App.initWeb3();\n  },\n\n  initWeb3: async function() {\n    // Modern dapp browsers...\n    if (window.ethereum) {\n      App.web3Provider = window.ethereum;\n      try {\n        // Request account access\n        await window.ethereum.enable();\n      } catch (error) {\n        // User denied account access...\n        console.error(\"User denied account access\")\n      }\n    }\n    // Legacy dapp browsers...\n    else if (window.web3) {\n      App.web3Provider = window.web3.currentProvider;\n    }\n    // If no injected web3 instance is detected, fall back to Ganache\n    else {\n      App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');\n    }\n    web3 = new Web3(App.web3Provider);\n\n    return App.initContract();\n  },\n\n  initContract: function() {\n    $.getJSON('MyV2CreditDelegation.json', function(data) {\n      // Get the necessary contract artifact file and instantiate it with @truffle/contract\n      var safeYieldArtifact = data;\n      App.contracts.MyV2CreditDelegation = TruffleContract(safeYieldArtifact);\n    \n      // Set the provider for our contract\n      App.contracts.MyV2CreditDelegation.setProvider(App.web3Provider);\n    });\n    \n\n    \n\n    return App.bindEvents();\n  },\n\n  bindEvents: function() {\n    $(document).on('click', '.btn-deposit', App.handleDeposit);\n    $(document).on('click', '.btn-withdrawl', App.handleWithdrawl);\n  },\n\n  handleDeposit: function(event) {\n    event.preventDefault();\n    web3.eth.getAccounts(function(error, accounts) {\n      if (error) {\n        console.log(error);\n      }\n    \n      var account = accounts[0];\n\n      App.contracts.MyV2CreditDelegation.deployed().then(function(instance) {\n        creditDelegatorInstance = instance;\n        const mockETHAddress = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\"\n        // Execute adopt as a transaction by sending account\n        return creditDelegatorInstance.depositCollateral(mockETHAddress, 1, true);\n      }).then(function(result) {\n        //return App.markAdopted();\n      }).catch(function(err) {\n        console.log(err.message);\n      });\n    });\n  },\n\n  handleWithdrawl: function(event) {\n    event.preventDefault();\n  },\n};\n\n$(function() {\n  $(window).load(function() {\n    App.init();\n  });\n});\n```\n\n```text\n<button class=\"btn btn-default btn-withdrawl\" \n  type=\"button\"> Withdrawl\n</button>\n```\n\n```text\nganache-cli --fork https://mainnet.infura.io/v3/{{MyProjectId}}\n```\n\n```text\nnpm init --yes\nnpm install --save-dev hardhat \nnpm install @nomiclabs/hardhat-waffle \nnpm install --save-dev \"@nomiclabs/hardhat-ethers@^2.0.0\" \"ethers@^5.0.0\" \"ethereum-waffle@^3.2.0\"\nnpx hardhat \n(follow the prompt)\n```\n\n```text\nimport '@nomiclabs/hardhat-ethers';\nimport * as dotenv from 'dotenv';\nimport { LogDescription } from 'ethers/lib/utils';\nimport hre from 'hardhat';\nimport { IERC20__factory, MyV2CreditDelegation__factory } from '../typechain';\n\ndotenv.config();\n\n// Infura, Alchemy, ... however you can get access to the Kovan test network\n// E.g. https://kovan.infura.io/v3/<project-id>\nconst KOVAN_JSON_RPC = process.env.KOVAN_JSON_RPC || '';\nif (!KOVAN_JSON_RPC) {\n    console.error('Forgot to set KOVAN_JSON_RPC in aave.ts or .env');\n    process.exit(1);\n}\n\n// Test account that has Kovan ETH and an AAVE token balance\nconst AAVE_HOLDER = '';\n\nasync function main() {\n    // Fork Kovan\n    await hre.network.provider.request({\n        method: 'hardhat_reset',\n        params: [{ forking: { jsonRpcUrl: KOVAN_JSON_RPC } }],\n    });\n\n    // Act like AAVE_HOLDER\n    await hre.network.provider.request({\n        method: 'hardhat_impersonateAccount',\n        params: [AAVE_HOLDER],\n    });\n    const signer = await hre.ethers.getSigner(AAVE_HOLDER);\n    console.log('signer:', signer.address);\n\n    // AAVE token on Kovan network\n    const token = IERC20__factory.connect('0xb597cd8d3217ea6477232f9217fa70837ff667af', signer);\n    console.log('token balance:', (await token.balanceOf(signer.address)).toString());\n\n    const MyV2CreditDelegation = new MyV2CreditDelegation__factory(signer);\n    const delegation = await MyV2CreditDelegation.deploy({ gasLimit: 1e7 });\n    console.log('delegation:', delegation.address);\n\n    await token.approve(delegation.address, 1000000000000);\n    console.log('allowance:', (await token.allowance(signer.address, delegation.address, { gasLimit: 1e6 })).toString());\n\n    const depositTrans = await delegation.depositCollateral(token.address, 1000000000000, true, { gasLimit: 1e6 });\n    console.log('depositTrans:', depositTrans.hash);\n    const receipt = await depositTrans.wait();\n    for (const log of receipt.logs) {\n        const [name, desc] = parseLog(log) || [];\n        if (desc) {\n            const args = desc.eventFragment.inputs.map(({ name, type, indexed }, index) =>\n                `\\n    ${type}${indexed ? ' indexed' : ''} ${name}: ${desc.args[name]}`);\n            args.unshift(`\\n    contract ${name} ${log.address}`);\n            console.log('Event', log.logIndex, `${desc.name}(${args ? args.join(',') : ''})`);\n        } else {\n            console.log('Log', log.logIndex, JSON.stringify(log.topics, null, 4), JSON.stringify(log.data));\n        }\n    }\n\n    function parseLog(log: { address: string, topics: Array<string>, data: string }): [string, LogDescription] | undefined {\n        try { return ['', delegation.interface.parseLog(log)]; } catch (e) { }\n        try {\n            const desc = token.interface.parseLog(log);\n            return [log.address.toLowerCase() === token.address.toLowerCase() ? 'AAVE' : 'IERC20', desc];\n        } catch (e) { }\n    }\n}\n\nmain().then(() => process.exit(0), error => {\n    console.error(JSON.stringify(error));\n    console.error(error);\n});\n```\n\n```text\n$ hardhat run --no-compile --network kovan .\\scripts\\Aave.ts\ntoken balance: 999999000000000000\ndelegation: 0x2863E2a95Dc84C227B11CF1997e295E59ab15670\nallowance: 1000000000000\ndepositTrans: 0x0a3d1a8bfbdfc0f403371f9936122d19bdc9f3539c34e3fb1b0a7896a398f923\nDone in 57.11s.\n```\n\n```text\nMyV2CreditDelegation\n```\n\n```text\nApproval\n```\n\n```text\ntoken.allowance\n```\n\n```text\n0.000001\n```\n\n```text\n0.000001\n```\n\n```text\n0.000001\n```\n\n```text\naAAVE\n```\n\n```text\nmockETHAddress\n```\n\n```text\n// contracts/AaveExample.sol\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\npragma abicoder v2;\n\nimport \"@aave-protocol/interfaces/IPool.sol\";\nimport \"@openzeppelin-contracts/token/ERC20/IERC20.sol\";\n\ncontract Aave {\n\n    // Storage Variables\n    address public borrowTokenAddress = 0xDF1742fE5b0bFc12331D8EAec6b478DfDbD31464; // Goerli Aave DAI\n    address public supplyTokenAddress = 0xA2025B15a1757311bfD68cb14eaeFCc237AF5b43; // Goerli Aave USDC\n    address public aavePoolAddress = 0x368EedF3f56ad10b9bC57eed4Dac65B26Bb667f6;    // Goerli Aave Pool Address\n\n\n    constructor() {}\n    \n    function supply() public returns (bool) {\n        // 1. Set amountToDrain to the contract's supplyTokenAddress balance\n        uint amountToDrain = IERC20(supplyTokenAddress).balanceOf(address(this));\n\n        // 2. Approve Aave pool to access amountToDrain from this contract \n        IERC20(supplyTokenAddress).approve(aavePoolAddress, amountToDrain);\n\n        // 3. Supply amountToDrain to Aave pool\n        IPool(aavePoolAddress).supply(supplyTokenAddress, amountToDrain, address(this), 0);\n\n        return true;\n    }\n\n    function borrow() public returns (bool) {\n        // Borrow 0.3 DAI\n        IPool(aavePoolAddress).borrow(borrowTokenAddress, 0.3 ether, 2, 0, address(this));\n\n        return true;\n    }\n}\n```\n\n========================================\n\nComments:\n- Are you sure you're sending it from the right account? After all, I see you defining `account` but never using it.\n- good point, I've been playing around with a bunch of different contracts to try to get this to send so that clearly is a bug. I'll look into it\n- Also I noticed that MyV2CreditDelegation refers to a `ILendingPool` and `IProtocolDataProvider` on Kovan, but those addresses aren't in use on mainnet. Since you start ganache by forking mainnet, those wouldn't work. Your `depositCollateral` would definitely fail.\n- This answer is still lacking a bit. I've tried to update your answer to make it more noob proof. However, when I try to `run hardhat run --no-compile --network kovan .\\scripts\\Aave.ts` I get an error ` Cannot use import statement outside a module` Please update the answer to include how to setup the project appropriately\n- Honestly this answer could use some improvement, but I won't have the bounty go to waste, please update this answer\n- can you provide a git repo?\n- Work aside, took me a bit to extract the script and dependencies, but I added a demo repository which should only require you to do `yarn; yarn build; yarn start;` to see the script work. *Assuming you got Yarn v1.22.0+ installed.* Hopefully that works for you?\n- Not sure if you have time, but I created seperate question for withdrawl, I thought it would be straight forward from here but the transaction gets reverted","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":552,"estimatedTokens":4386}}244{"id":"stack-76659978","source":"stackoverflow","questionId":76659978,"title":"How to get updated remaining HTS fungible token allowance on Hedera?","tags":["javascript","solidity","hedera-hashgraph"],"text":"Title: How to get updated remaining HTS fungible token allowance on Hedera?\nTags: javascript, solidity, hedera-hashgraph\nSource: Stack Overflow\n\nQuestion:\nI have a DApp with a contract that has an *approved allowance* to spend HTS fungible tokens on behalf of a user. However, the contract keeps reverting with `SPENDER_DOES_NOT_HAVE_ALLOWANCE` error.\n\nI have a condition in my code to ask the DApp’s user to approve another allowance transaction if the current allowance is less than the required amount.\n\n```\nif (amountGranted This seems like it should be sufficient. However, when I query the following endpoint of the mirror node:\n\n`/api/v1/account/{accountId}/allowances/tokens`\n\nthe response’ `allowances.amount_granted` value shows the *original token allowance* granted. But it does not show the *updated token allowance*. Is there a different endpoint I can call to get the updated (remaining) token allowance?\n\nSteps to reproduce:\n\n- Create a smart contract with a function that transfers tokens from the caller to the contract (itself).\n\n- Deploy the smart contract on Hedera.\n\n- Create a new Hedera account and create FT’s or use an existing account that already owns FTs. Ref: Hedera Account\n\n- Associate the contract with the Hedera accounts FTs you plan to send to it.\n\n- Use the JS SDK to grant an allowance to the contract of with a token amount of 3.\nQuery the mirror node for allowances info from:\n`https://testnet.mirrornode.hedera.com/api/v1/accounts/${ownerAccountID}/allowances/tokens`\nand add a condition that checks if `amountGranted \n\n- Invoke the smart contract function `transfer` where the Hedera account is the caller and the transfer amount is 2.\n\n- This call succeeds.\n\n- Invoke the smart contract function `transfer` where the Hedera account is the caller and the transfer amount is 2.\n\n- This call does not succeed: Contract Revert with `SPENDER_DOES_NOT_HAVE_ALLOWANCE`.\n\nSmart Contract:\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity >=0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ncontract TransferCallerTokens {\n function transfer(address token, uint256 amount) public {\n IERC20(token).transferFrom(msg.sender, address(this), amount);\n }\n}\n```\n\nSmart contract deployment:\n\n```\nasync function deployContract() {\n const bytecode = fs.readFileSync(\n \"TransferCallerTokens_sol_TransferCallerTokens.bin\");\n\n // Switch operators (for the client) before executing the transaction,\n // as you need to sign using the contract's admin key\n client.setOperator(adminAccountId, adminKey);\n\n // Build the transaction\n const contractCreate = new ContractCreateFlow()\n .setGas(100_000)\n .setBytecode(bytecode)\n .setAdminKey(adminKey)\n const contractCreateTxResponse = await contractCreate.execute(client);\n const contractCreateReceipt = await contractCreateTxResponse.getReceipt(client);\n const transferCallerTokensContractID = contractCreateReceipt.contractId;\n\n console.log(`The transferCallerTokensContractID: ${transferCallerTokensContractID}`);\n}\n```\n\nUsing the SDK to create my fungible token. Note: The FT belongs to the user, and *not* the smart contract above.\n\n```\n// Create a HTS Fungible Token\nasync function createFungibleToken(\n client,\n treasuryAccountId,\n treasuryAccountPrivateKey,\n) {\n // Generate supply key\n const supplyKeyForFT = PrivateKey.generateED25519();\n\n // Confgiure the token\n const createFTokenTxn = await new TokenCreateTransaction()\n .setTokenName('LoeweToken')\n .setTokenSymbol('LO')\n .setTokenType(TokenType.FungibleCommon)\n .setDecimals(1)\n .setInitialSupply(100)\n .setTreasuryAccountId(treasuryAccountId)\n .setSupplyKey(supplyKeyForFT)\n .setMaxTransactionFee(new Hbar(30))\n .freezeWith(client);\n\n // Sign the transaction with the treasury account private key\n const createFTokenTxnSigned = await\n createFTokenTxn.sign(treasuryAccountPrivateKey);\n const createFTokenTxnResponse = await\n createFTokenTxnSigned.execute(client);\n}\n```\n\nGranting an allowance\n\n```\n// Grant allowance to smart contract\nasync function grantAllowance() {\n const tokenAmount = 2;\n const approveAllowanceTx = new AccountAllowanceApproveTransaction()\n .approveTokenAllowance(\n fungibleTokenId, ownerAccountId, spenderAccountId, tokenAmount\n )\n .freezeWith(client);\n\n const approveAllowanceTxSign = await approveAllowanceTx\n .sign(\n PrivateKey.fromString(process.env.MY_PRIVATE_KEY)\n );\n\n const approveAllowanceTxResponse = await approveAllowanceTxSign.execute(client);\n await approveAllowanceTxResponse.getReceipt(client);\n}\n```\n\nExecute the Contract function `transfer`\n\n```\n// execute transfer of HTS fungible token\nasync function executeTransferTransaction() {\n const amount = 2;\n\n const allowanceInfo = await getAllowance();\n const contractAllowanceInfo = allowanceInfo.allowances.find(\n (x) => (x.spender === '0.0.15079297' && x.token_id === '0.0.14073131')\n );\n const contractAmountGranted = contractAllowanceInfo.amount_granted\n console.log(`Amount Granted for Contract is: ${contractAmountGranted}`)\n \n if (contractAmountGranted \n\n- Network Environment: Hedera Testnet\n\n- Hedera JS SDK Version: 2.29.0\n\n========================================\n\nCode:\n```js\nif (amountGranted < tokenAmountToSpend) {\n    // perform allowance tx \n}\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity >=0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ncontract TransferCallerTokens {\n  function transfer(address token, uint256 amount) public {\n    IERC20(token).transferFrom(msg.sender, address(this), amount);\n  }\n}\n```\n\n```text\nasync function deployContract() {\n  const bytecode = fs.readFileSync(\n    \"TransferCallerTokens_sol_TransferCallerTokens.bin\");\n\n    // Switch operators (for the client) before executing the transaction,\n  // as you need to sign using the contract's admin key\n  client.setOperator(adminAccountId, adminKey);\n\n  // Build the transaction\n  const contractCreate = new ContractCreateFlow()\n    .setGas(100_000)\n    .setBytecode(bytecode)\n    .setAdminKey(adminKey)\n  const contractCreateTxResponse = await contractCreate.execute(client);\n  const contractCreateReceipt = await contractCreateTxResponse.getReceipt(client);\n  const transferCallerTokensContractID = contractCreateReceipt.contractId;\n\n  console.log(`The transferCallerTokensContractID: ${transferCallerTokensContractID}`);\n}\n```\n\n```js\n// Create a HTS Fungible Token\nasync function createFungibleToken(\n    client,\n  treasuryAccountId,\n  treasuryAccountPrivateKey,\n) {\n  // Generate supply key\n  const supplyKeyForFT = PrivateKey.generateED25519();\n\n  // Confgiure the token\n  const createFTokenTxn = await new TokenCreateTransaction()\n    .setTokenName('LoeweToken')\n    .setTokenSymbol('LO')\n    .setTokenType(TokenType.FungibleCommon)\n    .setDecimals(1)\n    .setInitialSupply(100)\n    .setTreasuryAccountId(treasuryAccountId)\n    .setSupplyKey(supplyKeyForFT)\n    .setMaxTransactionFee(new Hbar(30))\n    .freezeWith(client);\n\n  // Sign the transaction with the treasury account private key\n  const createFTokenTxnSigned = await\n        createFTokenTxn.sign(treasuryAccountPrivateKey);\n  const createFTokenTxnResponse = await\n        createFTokenTxnSigned.execute(client);\n}\n```\n\n```js\n// Grant allowance to smart contract\nasync function grantAllowance() {\n    const tokenAmount = 2;\n    const approveAllowanceTx = new AccountAllowanceApproveTransaction()\n    .approveTokenAllowance(\n            fungibleTokenId, ownerAccountId, spenderAccountId, tokenAmount\n        )\n    .freezeWith(client);\n\n    const approveAllowanceTxSign = await approveAllowanceTx\n        .sign(\n            PrivateKey.fromString(process.env.MY_PRIVATE_KEY)\n        );\n\n  const approveAllowanceTxResponse = await approveAllowanceTxSign.execute(client);\n  await approveAllowanceTxResponse.getReceipt(client);\n}\n```\n\n```js\n// execute transfer of HTS fungible token\nasync function executeTransferTransaction() {\n  const amount = 2;\n\n    const allowanceInfo = await getAllowance();\n  const contractAllowanceInfo = allowanceInfo.allowances.find(\n        (x) => (x.spender === '0.0.15079297' && x.token_id === '0.0.14073131')\n    );\n  const contractAmountGranted = contractAllowanceInfo.amount_granted\n  console.log(`Amount Granted for Contract is: ${contractAmountGranted}`)\n  \n    if (contractAmountGranted < amount) {\n    await grantAllowance();\n  }\n\n  const transferFromTx = new ContractExecuteTransaction()\n    .setContractId(contractID)\n    .setFunction(\n            'transfer',\n            new ContractFunctionParameters()\n          .addAddress(tokenIDSolidityAddress)\n          .addUint256(amount),\n        )\n    .setGas(3_000_000)\n    .freezeWith(client);\n\n  const transferFromTxResponse = await transferFromTx.execute(client);\n  const receipt = await transferFromTxResponse.getReceipt(client);\n  console.log(`Execute Transfer on TransferCallerTokens status ${receipt.status}`);\n}\n```\n\n```text\nSPENDER_DOES_NOT_HAVE_ALLOWANCE\n```\n\n```text\n/api/v1/account/{accountId}/allowances/tokens\n```\n\n```text\nallowances.amount_granted\n```\n\n```text\nhttps://testnet.mirrornode.hedera.com/api/v1/accounts/${ownerAccountID}/allowances/tokens\n```\n\n```text\namountGranted < tokenAmountToSpend\n```\n\n```text\ngrantAllowance()\n```\n\n```text\ntransfer\n```\n\n```text\ntransfer\n```\n\n```text\nSPENDER_DOES_NOT_HAVE_ALLOWANCE\n```\n\n```text\ntransfer\n```\n\n```js\n//Create the transaction\nconst transaction = new AccountAllowanceApproveTransaction()\n    .approveTokenAllowance(tokenId, ownerAccount, spenderAccountId, tokenAmount);\n```\n\n```js\n/*\n * Use the SDK to execute a contract function directly to system contract \n * to get the remaining number of tokens that spender will be allowed to spend on behalf of owner:\n*/\n  const allowanceTransaction = new ContractExecuteTransaction()\n    .setContractId(fungibleTokenId)\n    .setFunction('allowance', new ContractFunctionParameters()\n      .addAddress(ownerAccountIdSolidityAddress)\n      .addAddress(spenderAccountIdSolidityAddress))\n    .setGas(30_000)\n    .freezeWith(client);\n```\n\n```js\nasync getAllowance(tokenSolidityAddress) {\n    const provider = new ethers.providers.Web3Provider(window.ethereum);\n    const signer = await provider.getSigner();\n    // create contract instance for the contract id (token id)\n    const contract = new ethers.Contract(tokenSolidityAddress, [`function allowance()`], signer);\n    try {\n      const txResult = await contract.allowance(ownerAddress, spenderAddress);\n      return txResult.hash;\n    } catch (error: any) {\n      console.warn(error.message ? error.message : error);\n      return null;\n    }\n  }\n```\n\n```text\n/api/v1/account/{accountId}/allowances/tokens\n```\n\n```text\nallowance.amount_granted\n```\n\n```text\nspender\n```\n\n```text\nowner\n```\n\n```text\nContractExecuteTransaction\n```\n\n```text\nallowance\n```\n\n```text\neth_call\n```\n\n```text\nallowance\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":386,"estimatedTokens":2688}}245{"id":"stack-58711371","source":"stackoverflow","questionId":58711371,"title":"How to get the result and the status of a transaction","tags":["go","ethereum","solidity","go-ethereum"],"text":"Title: How to get the result and the status of a transaction\nTags: go, ethereum, solidity, go-ethereum\nSource: Stack Overflow\n\nQuestion:\nI am trying to work with the Ethereum blockchain, with the Solidity contracts.\nI am currently deploying a contract and performing some actions on it, but I would like to know how to get some 'feedback/callback/returns' of a specific transaction.\n\nIs there a way to set the status of a transaction to 0 (error) and still get events, for example ?\n\n```\nif (id.length This will not work (no event) because I revert everything, but the status will be set to 0\n\n```\nif (id.length I will get some event, but the status will stay 1\n\n```\nif (id.length The status will be 0, but I will not have any event\n\nHere is my go code to perform the action :\n\n```\nfunc testFunction(id []byte) {\n //...\n //...\n tx, err := instance.Action(opt, id)\n if (errors.HasError(err)) {\n return\n }\n callbackValue := subscribeToContract(tx.Hash().Hex())\n logs.Pretty(tx, callbackValue)\n //...\n //...\n}\n\nfunc subscribeToContract(hashToRead string) myStruct {\n query := ethereum.FilterQuery{\n Addresses: []common.Address{address},\n }\n soc := make(chan types.Log)\n\n sub, err := WssClient.SubscribeFilterLogs(context.Background(), query, soc)\n if err != nil {\n logs.Error(err)\n }\n\n for {\n select {\n case err := If `id.length > 0`, all good.\nBut if `id.length Is there a way to directly have the result status, or should loop with `tx, err := client.TransactionReceipt(context.Background(), txHash)` until I get a Status?\n\n========================================\n\nTop Answer:\nAn easier/newer solution:\n\nI think the function waitMined is the function you are looking for.\n\n```\nbind.WaitMined(context.Background(), client, signedTx)\n```\n\nOriginally posted in here.\n\n========================================\n\nCode:\n```text\nif (id.length <= 0) {\n    emit Result(\"KO\", \"1\");\n    revert();\n}\n```\n\n```text\nif (id.length <= 0) {\n    emit Result(\"KO\", \"1\");\n    return;\n}\n```\n\n```text\nif (id.length <= 0) {\n    revert(\"KO_1\");\n}\n```\n\n```golang\nfunc    testFunction(id []byte) {\n    //...\n    //...\n    tx, err := instance.Action(opt, id)\n    if (errors.HasError(err)) {\n        return\n    }\n    callbackValue := subscribeToContract(tx.Hash().Hex())\n    logs.Pretty(tx, callbackValue)\n    //...\n    //...\n}\n\nfunc    subscribeToContract(hashToRead string) myStruct {\n    query := ethereum.FilterQuery{\n        Addresses: []common.Address{address},\n    }\n    soc := make(chan types.Log)\n\n    sub, err := WssClient.SubscribeFilterLogs(context.Background(), query, soc)\n    if err != nil {\n        logs.Error(err)\n    }\n\n    for {\n        select {\n        case err := <-sub.Err():\n            logs.Info(`SOMETHING ERROR`)\n            logs.Error(err)\n        case vLog := <-soc:\n        logs.Info(`SOMETHING`)\n        contractAbi, _ := abi.JSON(strings.NewReader(string(SignABI)))  \n        event := myStruct{}\n    contractAbi.Unpack(&event, \"Result\", vLog.Data)\n    logs.Info(`New Event from [` + vLog.TxHash.Hex() + `] : ` + event.Message)\n        }\n    }\n}\n```\n\n```text\nid.length > 0\n```\n\n```text\nid.length <= 0\n```\n\n```text\nsubscribeToContract\n```\n\n```text\ntx, err := client.TransactionReceipt(context.Background(), txHash)\n```\n\n```golang\nfunc checkTransactionReceipt(_txHash string) int {\n    client, _ := getClient(\"https://ropsten.infura.io/v3/XXXXXX\")\n    txHash := common.HexToHash(_txHash)\n    tx, err := client.TransactionReceipt(context.Background(), txHash)\n    if (Error.HasError(err)) {\n        return (-1)\n    }\n    return (int(tx.Status))\n}\n\nfunc    WaitForBlockCompletation(data EthData, hashToRead string) int {\n    soc := make(chan *types.Header)\n    sub, err := data.WssClient.SubscribeNewHead(context.Background(), soc)\n    if (err != nil) {\n        return -1\n    }\n\n    for {\n        select {\n            case err := <-sub.Err():\n                _ = err\n                return -1\n            case header := <-soc:\n                logs.Info(header.TxHash.Hex())\n                transactionStatus := checkTransactionReceipt(hashToRead)\n                if (transactionStatus == 0) {\n                    //FAILURE\n                    sub.Unsubscribe()\n                    return 0\n                } else if (transactionStatus == 1) {\n                    //SUCCESS\n                    sub.Unsubscribe()\n                    return 1\n                }\n        }\n    }\n}\n```\n\n```text\ngo-ethereum\n```\n\n```text\nSubscribeFilterLogs\n```\n\n```text\nSubscribeNewHead\n```\n\n```text\nTransactionReceipt\n```\n\n```text\nnot found\n```\n\n```golang\nbind.WaitMined(context.Background(), client, signedTx)\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":207,"estimatedTokens":1147}}246{"id":"stack-71041850","source":"stackoverflow","questionId":71041850,"title":"Is there a difference between casting to Interface and to a contract instance?","tags":["interface","blockchain","ethereum","solidity","smartcontracts"],"text":"Title: Is there a difference between casting to Interface and to a contract instance?\nTags: interface, blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nIn solidity, most smart contracts cast external contract calls to interfaces (IERC20 vs. ERC20). Is there any difference casting between the two?\n\nFor example, if I write\n\n`IERC20 Token = IERC20(tokenContractAddress);`\n\nIs there any functional difference to\n\n`ERC20 Token = ERC20(tokenContractAddress);`?\n\nJust curious if there are factors to consider in terms of gas costs, compatibility issues, etc. Thanks!\n\n========================================\n\nCode:\n```text\nIERC20 Token = IERC20(tokenContractAddress);\n```\n\n```text\nERC20 Token = ERC20(tokenContractAddress);\n```\n\n========================================\n\nComments:\n- Great answer! You're right—public state variables have the getter functions that don't exist in interfaces. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":32,"estimatedTokens":233}}247{"id":"stack-70770785","source":"stackoverflow","questionId":70770785,"title":"Internal JSON-RPC error with MetaMask on Polygon Blockchain. `ERC721: transfer caller is not owner nor approved.`","tags":["blockchain","polygon","solidity","metamask","erc721"],"text":"Title: Internal JSON-RPC error with MetaMask on Polygon Blockchain. `ERC721: transfer caller is not owner nor approved.`\nTags: blockchain, polygon, solidity, metamask, erc721\nSource: Stack Overflow\n\nQuestion:\nI am making an NFT marketplace. When I deployed my contract on the Mumbai-testnet. The createToken function might work cause it brings up the Metamask for the Gas Fee but after that, the Error occurs something regarding the **ONWNERSHIP**.\n*(Error image and text is present below.)*\n\n**STEPS which I **\n\n- `npm hardhat node`\n\n- `npm run dev`\n\n- Selecting the Creating Page.\n\n- Enter all the details.\n\n- Click on Create an Asset which calls the **createToken** function.\n\nthen the error occurs.\n\n**Here is my NFT contract**\n\n```\ncontract NFT is ERC721URIStorage {\nusing Counters for Counters.Counter;\nCounters.Counter private _tokenIds;\naddress contractAddress;\n\nconstructor(address marketplaceAddress) ERC721(\"Metaverse Tokens\", \"METT\") {\n contractAddress = marketplaceAddress;\n}\n\nfunction createToken(string memory tokenURI) public returns (uint256) {\n _tokenIds.increment();\n uint256 newItemId = _tokenIds.current();\n\n _mint(msg.sender, newItemId);\n _setTokenURI(newItemId, tokenURI);\n setApprovalForAll(contractAddress, true);\n\n return newItemId;\n}}\n```\n\n**Here is my NFTMarket contract**\n\n```\ncontract NFTMarket is ReentrancyGuard {\nusing Counters for Counters.Counter;\n\nCounters.Counter private _itemIds;\nCounters.Counter private _itemSold;\n\naddress payable owner;\nuint256 listingPrice = 0.025 ether; // Here ether is denoting the MATIC\n\nconstructor() {\n owner = payable(msg.sender);\n}\n\nstruct MarketItem {\n uint256 itemId;\n address nftContract;\n uint256 tokenId;\n address payable seller;\n address payable owner;\n uint256 price;\n bool sold;\n}\n\nmapping(uint256 => MarketItem) private idToMarketItem;\n\nevent MarketItemCreated(\n uint256 indexed itemId,\n address indexed nftContract,\n uint256 indexed tokenId,\n address seller,\n address owner,\n uint256 price,\n bool sold\n);\n\nfunction getListingPrice() public view returns (uint256) {\n return listingPrice;\n}\n\n//Function to create an NFT\nfunction createMarketItem(\n address nftContract,\n uint256 tokenId,\n uint256 price\n) public payable nonReentrant {\n //Conditions for creating the Item.\n require(price > 0, \"Price must be at least 1 wei\");\n require(\n msg.value == listingPrice,\n \"Price must be equal to listing price\"\n );\n\n _itemIds.increment();\n uint256 itemId = _itemIds.current();\n\n idToMarketItem[itemId] = MarketItem(\n itemId,\n nftContract,\n tokenId,\n payable(msg.sender),\n payable(address(0)), // When new NFT is created its ownership add is set to 0.\n price,\n false\n );\n\n IERC721(nftContract).transferFrom(msg.sender, address(this), tokenId);\n\n //Trigger the Event\n emit MarketItemCreated(\n itemId,\n nftContract,\n tokenId,\n msg.sender,\n address(0),\n price,\n false\n );\n}\n\n//Function to Transfer the Ownership\nfunction createMarketSale(address nftContract, uint256 itemId)\n public\n payable\n nonReentrant\n{\n uint256 price = idToMarketItem[itemId].price;\n uint256 tokenId = idToMarketItem[itemId].tokenId;\n\n require(\n msg.value == price,\n \"Please submit the asking value in order to Purchase\"\n );\n\n //Will transfer the MATIC to the seller address.\n idToMarketItem[itemId].seller.transfer(msg.value);\n\n //Will transfer the ownership from the owner of this contract to the Buyer.\n IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId);\n\n //Set the local value of the owner to the Buyer(msg.sender).\n idToMarketItem[itemId].owner = payable(msg.sender);\n\n //Set this NFT as sold.\n idToMarketItem[itemId].sold = true;\n _itemSold.increment();\n\n payable(owner).transfer(listingPrice);\n}\n\n//Returns number of items unsold\nfunction fetchMarketItems() public view returns (MarketItem[] memory) {\n uint256 itemCount = _itemIds.current();\n uint256 unsoldItemCount = _itemIds.current() - _itemSold.current();\n uint256 currentIndex = 0;\n\n MarketItem[] memory items = new MarketItem[](unsoldItemCount);\n\n for (uint256 i = 0; i I tried changing the RPC in the MetaMask and the configuration files and redeployed it many times with different accounts, but still, nothing changes.\n\n**The Error**\n\n```\nMetaMask - RPC Error: Internal JSON-RPC error. \ndata:\ncode: 3\nmessage: \"execution reverted: ERC721: transfer caller is not owner nor approved\"\n```\n\nImage of the console\n\n**If any other info is required please comment**\n\nLink of Blockchain Explorer\n\n========================================\n\nTop Answer:\nI checked your full code and it is working.\n\nYou are inheriting from `ERC721URIStorage` which inherits from `ERC721` If you check the `transferFrom` inside `ERC721`:\n\n```\nfunction transferFrom(address from,address to,uint256 tokenId\n ) public virtual override {\n // ***** THIS REQUIRE IS NOT SATISFIED *****\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: transfer caller is not owner nor approved\");\n _transfer(from, to, tokenId);\n }\n```\n\nyou are getting that error, because `require` statement inside `transferFrom` is not satisfied.\n\nthis is the `_isApprovedOrOwner`\n\n```\nfunction _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n require(_exists(tokenId), \"ERC721: operator query for nonexistent token\");\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));\n }\n```\n\nthis function is not returning `True`. in order to get `True`, this\n\n```\nspender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)\n```\n\nshould return True. in `or` operations in order to get True, 3 of conditions must be `True`.\n\nIn my opinion, you are trying to transfer a token that is not yours.\n\n========================================\n\nCode:\n```text\ncontract NFT is ERC721URIStorage {\nusing Counters for Counters.Counter;\nCounters.Counter private _tokenIds;\naddress contractAddress;\n\nconstructor(address marketplaceAddress) ERC721(\"Metaverse Tokens\", \"METT\") {\n    contractAddress = marketplaceAddress;\n}\n\nfunction createToken(string memory tokenURI) public returns (uint256) {\n    _tokenIds.increment();\n    uint256 newItemId = _tokenIds.current();\n\n    _mint(msg.sender, newItemId);\n    _setTokenURI(newItemId, tokenURI);\n    setApprovalForAll(contractAddress, true);\n\n    return newItemId;\n}}\n```\n\n```text\ncontract NFTMarket is ReentrancyGuard {\nusing Counters for Counters.Counter;\n\nCounters.Counter private _itemIds;\nCounters.Counter private _itemSold;\n\naddress payable owner;\nuint256 listingPrice = 0.025 ether; // Here ether is denoting the MATIC\n\nconstructor() {\n    owner = payable(msg.sender);\n}\n\nstruct MarketItem {\n    uint256 itemId;\n    address nftContract;\n    uint256 tokenId;\n    address payable seller;\n    address payable owner;\n    uint256 price;\n    bool sold;\n}\n\nmapping(uint256 => MarketItem) private idToMarketItem;\n\nevent MarketItemCreated(\n    uint256 indexed itemId,\n    address indexed nftContract,\n    uint256 indexed tokenId,\n    address seller,\n    address owner,\n    uint256 price,\n    bool sold\n);\n\nfunction getListingPrice() public view returns (uint256) {\n    return listingPrice;\n}\n\n//Function to create an NFT\nfunction createMarketItem(\n    address nftContract,\n    uint256 tokenId,\n    uint256 price\n) public payable nonReentrant {\n    //Conditions for creating the Item.\n    require(price > 0, \"Price must be at least 1 wei\");\n    require(\n        msg.value == listingPrice,\n        \"Price must be equal to listing price\"\n    );\n\n    _itemIds.increment();\n    uint256 itemId = _itemIds.current();\n\n    idToMarketItem[itemId] = MarketItem(\n        itemId,\n        nftContract,\n        tokenId,\n        payable(msg.sender),\n        payable(address(0)), // When new NFT is created its ownership add is set to 0.\n        price,\n        false\n    );\n\n    IERC721(nftContract).transferFrom(msg.sender, address(this), tokenId);\n\n    //Trigger the Event\n    emit MarketItemCreated(\n        itemId,\n        nftContract,\n        tokenId,\n        msg.sender,\n        address(0),\n        price,\n        false\n    );\n}\n\n//Function to Transfer the Ownership\nfunction createMarketSale(address nftContract, uint256 itemId)\n    public\n    payable\n    nonReentrant\n{\n    uint256 price = idToMarketItem[itemId].price;\n    uint256 tokenId = idToMarketItem[itemId].tokenId;\n\n    require(\n        msg.value == price,\n        \"Please submit the asking value in order to Purchase\"\n    );\n\n    //Will transfer the MATIC to the seller address.\n    idToMarketItem[itemId].seller.transfer(msg.value);\n\n    //Will transfer the ownership from the owner of this contract to the Buyer.\n    IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId);\n\n    //Set the local value of the owner to the Buyer(msg.sender).\n    idToMarketItem[itemId].owner = payable(msg.sender);\n\n    //Set this NFT as sold.\n    idToMarketItem[itemId].sold = true;\n    _itemSold.increment();\n\n    payable(owner).transfer(listingPrice);\n}\n\n//Returns number of items unsold\nfunction fetchMarketItems() public view returns (MarketItem[] memory) {\n    uint256 itemCount = _itemIds.current();\n    uint256 unsoldItemCount = _itemIds.current() - _itemSold.current();\n    uint256 currentIndex = 0;\n\n    MarketItem[] memory items = new MarketItem[](unsoldItemCount);\n\n    for (uint256 i = 0; i < itemCount; i++) {\n        if (idToMarketItem[i + 1].owner == address(0)) {\n            uint256 currentId = idToMarketItem[i + 1].itemId;\n            MarketItem storage currentItem = idToMarketItem[currentId];\n            items[currentIndex] = currentItem;\n            currentIndex += 1;\n        }\n    }\n    return items;\n}\n\n//Returns number of Own(Created or Bought) NFTs\nfunction fetchMyNFTs() public view returns (MarketItem[] memory) {\n    uint256 totalItemCount = _itemIds.current();\n    uint256 itemCount = 0;\n    uint256 currentIndex = 0;\n\n    for (uint256 i = 0; i < totalItemCount; i++) {\n        if (idToMarketItem[i + 1].owner == msg.sender) {\n            itemCount += 1;\n        }\n    }\n\n    MarketItem[] memory items = new MarketItem[](itemCount);\n    for (uint256 i = 0; i < totalItemCount; i++) {\n        if (idToMarketItem[i + 1].owner == msg.sender) {\n            uint256 currentId = idToMarketItem[i + 1].itemId;\n            MarketItem storage currentItem = idToMarketItem[currentId];\n            items[currentIndex] = currentItem;\n            currentIndex += 1;\n        }\n    }\n    return items;\n}\n\n//Returns the no of NFT created\nfunction fetchItemsCreated() public view returns (MarketItem[] memory) {\n    uint256 totalItemCount = _itemIds.current();\n    uint256 itemCount = 0;\n    uint256 currentIndex = 0;\n\n    for (uint256 i = 0; i < totalItemCount; i++) {\n        if (idToMarketItem[i + 1].seller == msg.sender) {\n            itemCount += 1;\n        }\n    }\n\n    MarketItem[] memory items = new MarketItem[](itemCount);\n    for (uint256 i = 0; i < totalItemCount; i++) {\n        if (idToMarketItem[i + 1].seller == msg.sender) {\n            uint256 currentId = idToMarketItem[i + 1].itemId;\n            MarketItem storage currentItem = idToMarketItem[currentId];\n            items[currentIndex] = currentItem;\n            currentIndex += 1;\n        }\n    }\n    return items;\n}}\n```\n\n```text\nMetaMask - RPC Error: Internal JSON-RPC error. \ndata:\ncode: 3\nmessage: \"execution reverted: ERC721: transfer caller is not owner nor approved\"\n```\n\n```text\nnpm hardhat node\n```\n\n```text\nnpm run dev\n```\n\n```text\nconst hre = require(\"hardhat\");\n\nasync function main() {\n  const [deployer] = await hre.ethers.getSigners();\n\n  console.log(\n    \"Deploying contracts with the account:\",\n    deployer.address\n  );\n\n  let txHash, txReceipt\n  const NFTMarket = await hre.ethers.getContractFactory(\"NFTMarket\");\n  const nftMarket = await NFTMarket.deploy();\n  await nftMarket.deployed();\n\n  txHash = nftMarket.deployTransaction.hash;\n  txReceipt = await ethers.provider.waitForTransaction(txHash);\n  let nftMarketAddress = txReceipt.contractAddress\n\n  console.log(\"nftMarket deployed to:\", nftMarketAddress);\n\n  const NFT = await hre.ethers.getContractFactory(\"NFT\");\n  const nft = await NFT.deploy(nftMarketAddress);\n  await nft.deployed();\n\n\n  txHash = nft.deployTransaction.hash;\n  // console.log(`NFT hash: ${txHash}\\nWaiting for transaction to be mined...`);\n  txReceipt = await ethers.provider.waitForTransaction(txHash);\n  let nftAddress = txReceipt.contractAddress\n\n  console.log(\"nft deployed to:\", nftAddress);\n}\n\nmain()\n  .then(() => process.exit(0))\n  .catch((error) => {\n    console.error(error);\n    process.exit(1);\n  });\n```\n\n```text\n\"execution reverted: ERC721: approve caller is not owner nor approved for all\"\n```\n\n```text\nconfig.js\n```\n\n```text\nfunction transferFrom(address from,address to,uint256 tokenId\n        ) public virtual override {\n        // *****  THIS REQUIRE IS NOT SATISFIED *****\n        require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: transfer caller is not owner nor approved\");\n        _transfer(from, to, tokenId);\n    }\n```\n\n```text\nfunction _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n        require(_exists(tokenId), \"ERC721: operator query for nonexistent token\");\n        address owner = ERC721.ownerOf(tokenId);\n        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));\n    }\n```\n\n```text\nspender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)\n```\n\n```text\nERC721URIStorage\n```\n\n```text\nERC721\n```\n\n```text\ntransferFrom\n```\n\n```text\nERC721\n```\n\n```text\nrequire\n```\n\n```text\ntransferFrom\n```\n\n```text\n_isApprovedOrOwner\n```\n\n```text\nTrue\n```\n\n```text\nTrue\n```\n\n```text\nor\n```\n\n```text\nTrue\n```\n\n```text\nhardhat compile..\n```\n\n========================================\n\nComments:\n- Can you link the failing transaction on a blockchain explorer?\n- Done sir, edited. In my opinion it create the token id but the approval is not working.\n- Thanks for the link. However the linked transaction is not failing. Can you provide steps to reproduce the error message (such as what function, from which address, which token ID, ...)?\n- Sir, I have updated the Query and put the image of the console there. I hope this may provide you the complete info. If anything left please let me know.\n- I did use the second statement to transfer from. I have added my MARKET CONTRACT please have a look. And if any other info require let me know.\n- when do u get the error. while you compile or you are calling from frontend\n- When I call from the frontend.\n- I have step by step checked the code 4 5 times with the Youtube I have practising from. There is no difference in code, still I am getting this unknown issue.\n- the front-end code please. your contract code looks ok\n- Thank You for your efforts, I got the solution and posted it in the answers.","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":572,"estimatedTokens":3705}}248{"id":"stack-70098080","source":"stackoverflow","questionId":70098080,"title":"Trying to run \"brownie run .\\scripts\\deploy.py --network rinkeby\" but getting a ValueError","tags":["python","blockchain","solidity"],"text":"Title: Trying to run \"brownie run .\\scripts\\deploy.py --network rinkeby\" but getting a ValueError\nTags: python, blockchain, solidity\nSource: Stack Overflow\n\nQuestion:\nHey guys I am trying to deploy my project on the rinkeby chain using infura, but I am getting a ValueError\nHere is my trackback:\n\n```\nINFO: Could not find files for the given pattern(s).\nBrownie v1.17.1 - Python development framework for Ethereum\n\n File \"c:\\users\\allow\\appdata\\local\\programs\\python\\python39\\lib\\site-packages\\brownie\\_cli\\__main__.py\", line 64, in main\n importlib.import_module(f\"brownie._cli.{cmd}\").main()\n File \"c:\\users\\allow\\appdata\\local\\programs\\python\\python39\\lib\\site-packages\\brownie\\_cli\\run.py\", line 44, in main\n network.connect(CONFIG.argv[\"network\"])\n File \"c:\\users\\allow\\appdata\\local\\programs\\python\\python39\\lib\\site-packages\\brownie\\network\\main.py\", line 40, in connect\n web3.connect(host, active.get(\"timeout\", 30))\n File \"c:\\users\\allow\\appdata\\local\\programs\\python\\python39\\lib\\site-packages\\brownie\\network\\web3.py\", line 52, in connect\n uri = _expand_environment_vars(uri)\n File \"c:\\users\\allow\\appdata\\local\\programs\\python\\python39\\lib\\site-packages\\brownie\\network\\web3.py\", line 183, in _expand_environment_vars\n raise ValueError(f\"Unable to expand environment variable in host setting: '{uri}'\")\nValueError: Unable to expand environment variable in host setting: 'https://rinkeby.infura.io/v3/$WEB3_INFURA_PROJECT_ID'\n```\n\nHere is my deploy.py code\n\n```\nfrom brownie import accounts, config, SimpleStorage, network\nimport os\n\ndef deploy_simple_storage():\n account = get_account()\n simple_storage = SimpleStorage.deploy({\"from\": account})\n stored_value = simple_storage.retrieve()\n print(stored_value)\n transaction = simple_storage.store(15, {\"from\": account})\n transaction.wait(1)\n updated_stored_value = simple_storage.retrieve()\n print(updated_stored_value)\n\ndef get_account():\n if network.show_active() == \"development\":\n return accounts[0]\n else:\n return accounts.add(config[\"wallets\"][\"from_key\"])\n\ndef main():\n deploy_simple_storage()\n```\n\nI have a really little experience in coding. I think the problem is related to .env, but I don't know what I should now. FYI I am using windows n this course\nhttps://www.youtube.com/watch?v=M576WGiDBdQ\nstuck at 4:48:00\n\n========================================\n\nTop Answer:\nI had the same issue (Mac OS) and I looked at another YouTube around Brownie Deployment and noticed that **\"network\"** needs to be defined at import.\n\nThis line of code above the `from brownie import` did the trick in my `deploy.py`:\n\n```\nimport brownie.network as network\n```\n\n========================================\n\nCode:\n```text\nINFO: Could not find files for the given pattern(s).\nBrownie v1.17.1 - Python development framework for Ethereum\n\n  File \"c:\\users\\allow\\appdata\\local\\programs\\python\\python39\\lib\\site-packages\\brownie\\_cli\\__main__.py\", line 64, in main\n    importlib.import_module(f\"brownie._cli.{cmd}\").main()\n  File \"c:\\users\\allow\\appdata\\local\\programs\\python\\python39\\lib\\site-packages\\brownie\\_cli\\run.py\", line 44, in main\n    network.connect(CONFIG.argv[\"network\"])\n  File \"c:\\users\\allow\\appdata\\local\\programs\\python\\python39\\lib\\site-packages\\brownie\\network\\main.py\", line 40, in connect\n    web3.connect(host, active.get(\"timeout\", 30))\n  File \"c:\\users\\allow\\appdata\\local\\programs\\python\\python39\\lib\\site-packages\\brownie\\network\\web3.py\", line 52, in connect\n    uri = _expand_environment_vars(uri)\n  File \"c:\\users\\allow\\appdata\\local\\programs\\python\\python39\\lib\\site-packages\\brownie\\network\\web3.py\", line 183, in _expand_environment_vars\n    raise ValueError(f\"Unable to expand environment variable in host setting: '{uri}'\")\nValueError: Unable to expand environment variable in host setting: 'https://rinkeby.infura.io/v3/$WEB3_INFURA_PROJECT_ID'\n```\n\n```text\nfrom brownie import accounts, config, SimpleStorage, network\nimport os\n\ndef deploy_simple_storage():\n    account = get_account()\n    simple_storage = SimpleStorage.deploy({\"from\": account})\n    stored_value = simple_storage.retrieve()\n    print(stored_value)\n    transaction = simple_storage.store(15, {\"from\": account})\n    transaction.wait(1)\n    updated_stored_value = simple_storage.retrieve()\n    print(updated_stored_value)\n\n\ndef get_account():\n    if network.show_active() == \"development\":\n        return accounts[0]\n    else:\n        return accounts.add(config[\"wallets\"][\"from_key\"])\n\n\ndef main():\n    deploy_simple_storage()\n```\n\n```py\nimport brownie.network as network\n```\n\n```text\nfrom brownie import\n```\n\n```text\ndeploy.py\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":123,"estimatedTokens":1145}}249{"id":"stack-50948757","source":"stackoverflow","questionId":50948757,"title":"The contract code couldn't be stored, please check your gas limit : Ethereum Smart Contract Deployment Failed:","tags":["ethereum","solidity","web3js","truffle"],"text":"Title: The contract code couldn't be stored, please check your gas limit : Ethereum Smart Contract Deployment Failed:\nTags: ethereum, solidity, web3js, truffle\nSource: Stack Overflow\n\nQuestion:\nI'm learning how Ethereum smartcontracts are developed and deployed using Solidity, Web3.js, and JavaScript.\n\nI've successfully deployed a contract on Ganache. Now when I'm trying to deployed it on Rinkby Test Net using `truffle-hdwallet-provider. It just fails.\n\nIve successfully created a web3 object using truffle-hdwallet-provider and I successfully get the account list but the deployment to the testnet always fails.\n\nYou can check here that my deployment fails: https://rinkeby.etherscan.io/address/0x2f20b8F61813Df4e114D06123Db555325173F178\n\nHere is my deploy script\n\n```\nconst HDWalletProvider = require('truffle-hdwallet-provider');\nconst Web3 = require ('web3');\nconst {interface, bytecode} = require('./compile');\n\nconst provider = new HDWalletProvider(\n 'memonics', // this is correct \n 'https://rinkeby.infura.io/mylink' // this is correct \n );\n\nconst web3 = new Web3(provider);\n\nconst deploy = async() =>{\n const accounts = await web3.eth.getAccounts();\n console.log('Attempting to deploy from account:', accounts[0]); //This excute fine\n try {\n const result = await new web3.eth.Contract(JSON.parse(interface)).deploy({ data: bytecode, arguments: ['Hi There!']}).send({ from: accounts[0], gas: '1000000'});\n console.log('Contract deployed to ', result.options.address);\n }\n catch(err) {\n console.log('ERROR'); // Here I get error \n }\n \n\n \n};\ndeploy();\n```\n\nand here is my Contract\n\n```\npragma solidity ^0.4.17;\n\ncontract Inbox{\n string public message;\n \n constructor (string initialMessage) public {\n message = initialMessage;\n }\n function setMessage(string newMessage) public {\n message = newMessage;\n }\n}\n```\n\nI tried using Remix and it deployed successfully but when trying with truffle-hdwallet-provider it gives this error:\n\nThe contract code couldn't be stored, please check your gas limit.\n\nI tied with different gas values (up-to max possible) but still no result.\n\n========================================\n\nTop Answer:\nUse this `'0x0' +` inside `deploy` just before bytecode.\n\n```\n.deploy({ data:'0x0' + bytecode })\n.send({ gas: \"1000000\", gasPrice: \"5000000000\", from: accounts[0] });\n```\n\n========================================\n\nCode:\n```text\nconst HDWalletProvider = require('truffle-hdwallet-provider');\nconst Web3 = require ('web3');\nconst {interface, bytecode} = require('./compile');\n\nconst provider = new HDWalletProvider(\n    'memonics',                         // this is correct \n    'https://rinkeby.infura.io/mylink'  // this is correct \n    );\n\nconst web3 = new Web3(provider);\n\nconst deploy = async() =>{\n    const accounts = await web3.eth.getAccounts();\n    console.log('Attempting to deploy from account:', accounts[0]); //This excute fine\n    try {\n    const result = await new web3.eth.Contract(JSON.parse(interface)).deploy({ data: bytecode, arguments: ['Hi There!']}).send({ from: accounts[0], gas: '1000000'});\n    console.log('Contract deployed to ', result.options.address);\n    }\n    catch(err) {\n        console.log('ERROR'); // Here I get error \n    }\n    \n\n    \n};\ndeploy();\n```\n\n```text\npragma solidity ^0.4.17;\n\ncontract Inbox{\n    string public message;\n    \n    constructor (string initialMessage) public {\n        message = initialMessage;\n    }\n    function setMessage(string newMessage) public {\n        message = newMessage;\n    }\n}\n```\n\n```text\n0x\n```\n\n```text\n0x\n```\n\n```text\n.deploy({ data:'0x0' + bytecode })\n.send({ gas: \"1000000\", gasPrice: \"5000000000\", from: accounts[0] });\n```\n\n```text\n'0x0' +\n```\n\n```text\ndeploy\n```\n\n```text\nconst result = await new web3.eth.Contract(interface)\n.deploy({data: '0x' + bytecode, arguments: ['Hello there']})\n.send({from: accounts[0], gas: '1000000'})\n```\n\n========================================\n\nComments:\n- it should be '0x' + bytecode, not '0x0'\n- thanks, it worked. In old versions of web3js+soldity, there was only \"0x\"+bytecode. but now its \"0x0\"+bytecode\n- Worked on 2025, but still don't know what it's mean","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":157,"estimatedTokens":1030}}250{"id":"stack-49440605","source":"stackoverflow","questionId":49440605,"title":"Does calling an 'external view' function in solidity broadcast a 'transaction' to the network?","tags":["ethereum","solidity"],"text":"Title: Does calling an 'external view' function in solidity broadcast a 'transaction' to the network?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\n\"In Ethereum, when you call a function on a contract, you broadcast it to a node or nodes on the network as a transaction.\" - CryptoZombies (Solidity Tutorial)\n\nAre there circumstances where function calls do not broadcast a transaction to the network?\n\nHow might one broadcast a transaction to a specific node?\n\nThank you.\n\n========================================\n\nCode:\n```text\nconstant\n```\n\n========================================\n\nComments:\n- Thank you. \"However, once the transaction is submitted, it becomes a pending transaction across all nodes in the network and any miner on the blockchain can pick it up and process it.\" Do you happen to know whether it is possible for one miner to extend their mining algorithm to prioritize tx submissions from a specific node or tx submissions with certain metadata? i.e. App -> specific remote node -> pending tx. Pending tx -> identified as priority by specific miner -> mines block immediately [though never makes it to the canonical chain].","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":24,"estimatedTokens":289}}251{"id":"stack-71532782","source":"stackoverflow","questionId":71532782,"title":"What are the rules (syntax) for importing from Github repo to Solidity Contract","tags":["github","solidity"],"text":"Title: What are the rules (syntax) for importing from Github repo to Solidity Contract\nTags: github, solidity\nSource: Stack Overflow\n\nQuestion:\nI have the following import statement in a Solidity contract ( this works).\n\n```\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"\n```\n\nThe interface I'm importing is at the following repo: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol\n\nMy question is, what is the syntax or rules I should when importing from a github repo to Solidity? what does the @ sign in the import statement mean ?\n\n========================================\n\nCode:\n```text\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\"\n```\n\n```text\nimport \"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol\";\n```\n\n```text\nnode_modules\n```\n\n```text\n@\n```\n\n```text\n@openzeppelin/<package_name>\n```\n\n========================================\n\nComments:\n- It should be noted that without input remappings this github url import won't work locally\n- @ihorbond Correct, thanks for the clarification. Same goes for NPM import. And both GitHub and NPM remappings are usually already set up in the compiler default config, so in most cases devs don't need to care about configuring the remappings. But in some cases such as Etherscan verification, that might not be configured and throw an error.","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":43,"estimatedTokens":352}}252{"id":"stack-43063421","source":"stackoverflow","questionId":43063421,"title":"How to create ether wallet?","tags":["python","blockchain","ethereum","solidity"],"text":"Title: How to create ether wallet?\nTags: python, blockchain, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI want to create users ether wallet through code. is there any api or something to create ether wallet which they can use to transfer & receive ether ?\n\n========================================\n\nTop Answer:\nYou can use pyethapp (python based client) for creating ethereum wallet, transferring funds.\n\nLink: https://github.com/ethereum/pyethapp\n\nIt has very simple command to create account\n\n```\n$ pyethapp account new\n```\n\nExplore examples also: https://github.com/ethereum/pyethapp/tree/develop/examples\n\n========================================\n\nCode:\n```text\nfunction createWallet(password) {\n  const params = {keyBytes: 32, ivBytes: 16};\n  const dk = keythereum.create(params);\n\n  const options = {\n    kdf: 'pbkdf2',\n    cipher: 'aes-128-ctr',\n    kdfparams: { c: 262144, dklen: 32, prf: 'hmac-sha256' }\n  };\n  const keyObject = keythereum.dump(password, dk.privateKey, dk.salt, dk.iv, options);\n  return keyObject;\n}\n /* for getting private key from keyObject */\nfunction getPrivateKey(password, keyObject) {\n  return keythereum.recover(password, keyObject);\n}\n\nconst keyObject = createWallet(\"My Super secret password\");\nconst walletAddress = '0x' + keyObject.address;\n\nconst privateKey = getPrivateKey(\"My Super secret password\", keyObject);\n```\n\n```text\n0x\n```\n\n```text\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n```\n\n```text\n0x8fd379246834eac74B8419FfdA202CF8051F7A03\n```\n\n```text\n$ pyethapp account new\n```\n\n```text\n$ pip install web3\n```\n\n```text\n>>> from web3 import Web3, KeepAliveRPCProvider, IPCProvider\n```\n\n```text\n>>> web3 = Web3(KeepAliveRPCProvider(host='localhost', port='8545'))\n```\n\n```text\n>>> web3 = Web3(IPCProvider())\n```\n\n```text\n>>> web3.personal.newAccount('the-passphrase')\n['0xd3cda913deb6f67967b99d67acdfa1712c293601']\n```\n\n========================================\n\nComments:\n- So 0xd3cda913deb6f67967b99d67acdfa1712c293601 is the address. How can I know the private key?","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":90,"estimatedTokens":511}}253{"id":"stack-69984326","source":"stackoverflow","questionId":69984326,"title":"Solidity Time-Travel Test Failing","tags":["ethereum","solidity","smartcontracts","web3js","truffle"],"text":"Title: Solidity Time-Travel Test Failing\nTags: ethereum, solidity, smartcontracts, web3js, truffle\nSource: Stack Overflow\n\nQuestion:\nI am following the CryptoZombies tutorial and having trouble getting one of the tests to pass. The test is as follows:\n\n```\nit(\"zombies should be able to attack another zombie\", async () => {\n let result;\n result = await contractInstance.createRandomZombie(zombieNames[0], {from: alice});\n const firstZombieId = result.logs[0].args.zombieId.toNumber();\n result = await contractInstance.createRandomZombie(zombieNames[1], {from: bob});\n const secondZombieId = result.logs[0].args.zombieId.toNumber();\n await time.increase(time.duration.days(1));\n await contractInstance.attack(firstZombieId, secondZombieId, {from: alice});\n expect(result.receipt.status).to.equal(true);\n })\n```\n\nessentially, create zombie1, create zombie2, fast forward one day, let zombie1 attack zombie2 (since there is a cooldown period between zombie creation and when it is allowed to attach) and finally assert that the smart contract was able to be executed.\n\nThe test fails with this blob of an unhelpful error message:\n\n```\n1) Contract: CryptoZombies\n zombies should be able to attack another zombie:\n Uncaught TypeError: callback is not a function\n at /home/deepsports/.nvm/versions/node/v14.18.0/lib/node_modules/truffle/build/webpack:/packages/provider/wrapper.js:107:1\n at XMLHttpRequest.request.onreadystatechange (/home/deepsports/.nvm/versions/node/v14.18.0/lib/node_modules/truffle/build/webpack:/node_modules/web3/node_modules/web3-providers-http/lib/index.js:98:1)\n at XMLHttpRequestEventTarget.dispatchEvent (/home/deepsports/.nvm/versions/node/v14.18.0/lib/node_modules/truffle/build/webpack:/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:1)\n at XMLHttpRequest.exports.modules.996763.XMLHttpRequest._setReadyState (/home/deepsports/.nvm/versions/node/v14.18.0/lib/node_modules/truffle/build/webpack:/node_modules/xhr2-cookies/dist/xml-http-request.js:208:1)\n at XMLHttpRequest.exports.modules.996763.XMLHttpRequest._onHttpResponseEnd (/home/deepsports/.nvm/versions/node/v14.18.0/lib/node_modules/truffle/build/webpack:/node_modules/xhr2-cookies/dist/xml-http-request.js:318:1)\n at IncomingMessage. (/home/deepsports/.nvm/versions/node/v14.18.0/lib/node_modules/truffle/build/webpack:/node_modules/xhr2-cookies/dist/xml-http-request.js:289:47)\n at endReadableNT (internal/streams/readable.js:1334:12)\n at processTicksAndRejections (internal/process/task_queues.js:82:21)\n```\n\nFor background, I'm using:\n\n- Truffle v5.4.17\n\n- Solidity 0.4.25\n\n- Node v14.18.0 (if that's helpful?)\n\nThe stacktrace is a bit hard to parse, since there's no lines in my actual code referenced. Through process of elimination, was able to confirm that it is this line of code that causes the failure:\n`await time.increase(time.duration.days(1));`\n\nwhich calls into this code (created as part of the tutorial):\n\n```\nasync function increase(duration) {\n\n //first, let's increase time\n await web3.currentProvider.send({\n jsonrpc: \"2.0\",\n method: \"evm_increaseTime\",\n params: [duration], // there are 86400 seconds in a day\n id: new Date().getTime()\n });\n\n //next, let's mine a new block\n web3.currentProvider.send({\n jsonrpc: '2.0',\n method: 'evm_mine',\n params: [],\n id: new Date().getTime()\n })\n\n}\n```\n\n========================================\n\nCode:\n```text\nit(\"zombies should be able to attack another zombie\", async () => {\n        let result;\n        result = await contractInstance.createRandomZombie(zombieNames[0], {from: alice});\n        const firstZombieId = result.logs[0].args.zombieId.toNumber();\n        result = await contractInstance.createRandomZombie(zombieNames[1], {from: bob});\n        const secondZombieId = result.logs[0].args.zombieId.toNumber();\n        await time.increase(time.duration.days(1));\n        await contractInstance.attack(firstZombieId, secondZombieId, {from: alice});\n        expect(result.receipt.status).to.equal(true);\n    })\n```\n\n```text\n1) Contract: CryptoZombies\n       zombies should be able to attack another zombie:\n     Uncaught TypeError: callback is not a function\n      at /home/deepsports/.nvm/versions/node/v14.18.0/lib/node_modules/truffle/build/webpack:/packages/provider/wrapper.js:107:1\n      at XMLHttpRequest.request.onreadystatechange (/home/deepsports/.nvm/versions/node/v14.18.0/lib/node_modules/truffle/build/webpack:/node_modules/web3/node_modules/web3-providers-http/lib/index.js:98:1)\n      at XMLHttpRequestEventTarget.dispatchEvent (/home/deepsports/.nvm/versions/node/v14.18.0/lib/node_modules/truffle/build/webpack:/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:1)\n      at XMLHttpRequest.exports.modules.996763.XMLHttpRequest._setReadyState (/home/deepsports/.nvm/versions/node/v14.18.0/lib/node_modules/truffle/build/webpack:/node_modules/xhr2-cookies/dist/xml-http-request.js:208:1)\n      at XMLHttpRequest.exports.modules.996763.XMLHttpRequest._onHttpResponseEnd (/home/deepsports/.nvm/versions/node/v14.18.0/lib/node_modules/truffle/build/webpack:/node_modules/xhr2-cookies/dist/xml-http-request.js:318:1)\n      at IncomingMessage.<anonymous> (/home/deepsports/.nvm/versions/node/v14.18.0/lib/node_modules/truffle/build/webpack:/node_modules/xhr2-cookies/dist/xml-http-request.js:289:47)\n      at endReadableNT (internal/streams/readable.js:1334:12)\n      at processTicksAndRejections (internal/process/task_queues.js:82:21)\n```\n\n```text\nasync function increase(duration) {\n\n    //first, let's increase time\n    await web3.currentProvider.send({\n        jsonrpc: \"2.0\",\n        method: \"evm_increaseTime\",\n        params: [duration], // there are 86400 seconds in a day\n        id: new Date().getTime()\n    });\n\n    //next, let's mine a new block\n    web3.currentProvider.send({\n        jsonrpc: '2.0',\n        method: 'evm_mine',\n        params: [],\n        id: new Date().getTime()\n    })\n\n}\n```\n\n```text\nawait time.increase(time.duration.days(1));\n```\n\n```text\n// no callback, fails\nawait web3.currentProvider.send({\n    jsonrpc: \"2.0\",\n    method: \"evm_increaseTime\",\n    params: [duration],\n    id: new Date().getTime()\n});\n```\n\n```text\nasync function increase(duration) {\n    return new Promise((resolve, reject) => {\n        web3.currentProvider.send({\n            jsonrpc: \"2.0\",\n            method: \"evm_increaseTime\",\n            params: [duration],\n            id: new Date().getTime()\n        }, (err, result) => {\n            // second call within the callback\n            web3.currentProvider.send({\n                jsonrpc: '2.0',\n                method: 'evm_mine',\n                params: [],\n                id: new Date().getTime()\n            }, (err, result) => {\n                // need to resolve the Promise in the second callback\n                resolve();\n            });\n        });\n    });\n}\n```\n\n```text\nweb3\n```\n\n```text\nsendAsync\n```\n\n```text\nweb3.currentProvider.send()\n```\n\n```text\nawait\n```\n\n```text\nsend()\n```\n\n```text\ncontract.methods.foo().send()\n```\n\n```text\nawait\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":190,"estimatedTokens":1756}}254{"id":"stack-70643149","source":"stackoverflow","questionId":70643149,"title":"Call a function in another contract - Solidity","tags":["blockchain","ethereum","solidity","smartcontracts","truffle"],"text":"Title: Call a function in another contract - Solidity\nTags: blockchain, ethereum, solidity, smartcontracts, truffle\nSource: Stack Overflow\n\nQuestion:\nI need to call a function in another contract using Truffle. This is my sample contract:\n\n**Category.sol:**\n\n```\ncontract Category {\n /// ...\n /// @notice Check if category exists\n function isCategoryExists(uint256 index) external view returns (bool) {\n if (categories[index].isExist) {\n return true;\n }\n return false;\n }\n}\n```\n\n**Post.sol:**\n\n```\ncontract Post {\n /// ...\n /// @notice Create a post\n function createPost(PostInputStruct memory _input)\n external\n onlyValidInput(_input)\n returns (bool)\n {\n /// NEED TO CHECK IF CATEGORY EXISTS\n /// isCategoryExists() >>\n }\n}\n```\n\n**Deploy.js**\n\n```\nconst Category = artifacts.require(\"Category\");\nconst Post = artifacts.require(\"Post\");\n\nmodule.exports = function (deployer) {\n deployer.deploy(Category);\n deployer.deploy(Post);\n};\n```\n\nWhat can I do?\n\n========================================\n\nCode:\n```text\ncontract Category {\n  /// ...\n  /// @notice Check if category exists\n  function isCategoryExists(uint256 index) external view returns (bool) {\n    if (categories[index].isExist) {\n      return true;\n    }\n    return false;\n  }\n}\n```\n\n```text\ncontract Post {\n  /// ...\n  /// @notice Create a post\n  function createPost(PostInputStruct memory _input)\n    external\n    onlyValidInput(_input)\n    returns (bool)\n  {\n    /// NEED TO CHECK IF CATEGORY EXISTS\n    /// isCategoryExists() <<<from Category.sol>>>\n  }\n}\n```\n\n```text\nconst Category = artifacts.require(\"Category\");\nconst Post = artifacts.require(\"Post\");\n\nmodule.exports = function (deployer) {\n  deployer.deploy(Category);\n  deployer.deploy(Post);\n};\n```\n\n```text\ncontract Category is Post {\n  /// ...\n  /// @notice Check if category exists\n  function isCategoryExists(uint256 index) external view returns (bool) {\n    if (categories[index].isExist) {\n      return true;\n    }\n    return false;\n  }\n  // you can call createPost\n  createPost(){}\n}\n```\n\n========================================\n\nComments:\n- Hi Jafari, this tutorial might help others, pasting the link below tutorialspoint.com/solidity/solidity_inheritance.htm\n- `contract Category is Post` or `contract Post is Category` ?\n- Category is Post => Category inherits from Post so u can use functions of Post in Category","metadata":{"transformedAt":"2026-08-18T18:33:36.132Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":115,"estimatedTokens":587}}255{"id":"stack-70128297","source":"stackoverflow","questionId":70128297,"title":"Is there a way to pass fixed array as parameter to utility function is Solidity?","tags":["arrays","ethereum","solidity"],"text":"Title: Is there a way to pass fixed array as parameter to utility function is Solidity?\nTags: arrays, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI have two arrays with fixed lengths which I want to send to a utility function, but it gives the following error since arrays length are different.\n\n```\nTypeError: Invalid type for argument in function call. Invalid implicit conversion from string storage ref[2] storage ref to string storage ref[] storage pointer requested.\n```\n\nIs there a way to make a utility function that will take fixed arrays with arbitrary lengths?\n\nFull code snippet\n\n```\ncontract test {\n string[2] internal list1 = [\"str1\", \"str2\"];\n string[3] internal list2 = [\"str3\", \"str4\", \"str5\"];\n\n function entryPoint() public view returns (uint256) {\n return utilityFunction(list1, list2);\n }\n \n function utilityFunction(string[] storage _list1, string[] storage _list2) internal pure returns (uint256 result) {\n // some logic here\n }\n}\n```\n\n========================================\n\nCode:\n```text\nTypeError: Invalid type for argument in function call. Invalid implicit conversion from string storage ref[2] storage ref to string storage ref[] storage pointer requested.\n```\n\n```text\ncontract test {\n    string[2] internal list1 = [\"str1\", \"str2\"];\n    string[3] internal list2 = [\"str3\", \"str4\", \"str5\"];\n\n    function entryPoint() public view returns (uint256) {\n        return utilityFunction(list1, list2);\n    }\n    \n    function utilityFunction(string[] storage _list1, string[] storage _list2) internal pure returns (uint256 result) {\n        // some logic here\n    }\n}\n```\n\n```text\n// changed `string[]` to `string[2]` and the other `string[]` to `string[3]`\nfunction utilityFunction(string[2] storage _list1, string[3] storage _list2) internal pure returns (uint256 result) {\n```\n\n```text\nfunction entryPoint() public view returns (uint256) {\n    // declare a dynamic-size array in memory with 2 empty items\n    string[] memory _list1 = new string[](2);\n    // assign values to the dynamic-size array\n    _list1[0] = list1[0];\n    _list1[1] = list1[1];\n\n    string[] memory _list2 = new string[](3);\n    _list2[0] = list2[0];\n    _list2[1] = list2[1];\n    _list2[2] = list2[2];\n\n    // pass the dynamic-size in-memory arrays\n    return utilityFunction(_list1, _list2);\n}\n\n// changed location to memory, now you can accept dynamic-size arrays with arbitrary length\nfunction utilityFunction(string[] memory _list1, string[] memory _list2) internal pure returns (uint256 result) {\n}\n```\n\n```text\nentryPoint()\n```\n\n```text\nlist1\n```\n\n```text\nlist2\n```\n\n```text\n_list1\n```\n\n```text\n_list2\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":98,"estimatedTokens":656}}256{"id":"stack-50569984","source":"stackoverflow","questionId":50569984,"title":"How to query a struct by multiple attributes in Solidity?","tags":["ethereum","solidity","truffle"],"text":"Title: How to query a struct by multiple attributes in Solidity?\nTags: ethereum, solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nSuppose I have the following contract:\n\n```\ncontract UserContract {\n struct User {\n address walletAddress;\n string organisation;\n string fName;\n string lName;\n string email;\n uint index;\n }\n mapping(address => User) private users;\n address[] private userIndex;\n}\n```\n\nI know how to write a function that returns user information corresponding to a given `address`, but I'd also like to write a function that can grab user info by the `User`'s email address.\n\nHow does this work? Is my only option to create a separate mapping for this use-case that maps the `User` struct to a string? If so, does this mean the struct gets stored two times? Or does it only store references to that struct?\n\nThanks!\n\n========================================\n\nCode:\n```text\ncontract UserContract {\n    struct User {\n        address walletAddress;\n        string organisation;\n        string fName;\n        string lName;\n        string email;\n        uint index;\n    }\n    mapping(address => User) private users;\n    address[] private userIndex;\n}\n```\n\n```text\naddress\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\ncontract UserContract {\n    struct User {\n        address walletAddress;\n        string organisation;\n        string fName;\n        string lName;\n        string email;\n        uint index;\n    }\n    User[] users;\n    mapping(address => uint256) private addressMap;\n    mapping(string => uint256) private emailMap; // Note this must be private if you’re going to use `string` as the key. Otherwise, use bytes32\n    address[] private userIndex;\n}\n```\n\n```text\nmappings\n```\n\n```text\nstruct\n```\n\n```text\nstructs\n```\n\n```text\nmapping\n```\n\n========================================\n\nComments:\n- you can use for loop but it will take more processing , but for loop can be a solution\n- Works like a charm! Thank you\n- Could you clarify what userIndex is for, Adam Kipnis? My understanding is that addressMap already provides mapping from user's walletAddress to index in array users.\n- Also why don't you make users - private? We would likely not want it to be modified directly from outside of this contract.","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":98,"estimatedTokens":558}}257{"id":"stack-46299286","source":"stackoverflow","questionId":46299286,"title":"How connect library to smart contract from external resources?","tags":["ethereum","solidity","openzeppelin"],"text":"Title: How connect library to smart contract from external resources?\nTags: ethereum, solidity, openzeppelin\nSource: Stack Overflow\n\nQuestion:\n```\npragma solidity ^0.4.15;\n\nimport './ERC20.sol';\nimport './SafeMath.sol';\n```\n\nHow connect **SafeMath.sol** from external(*non-local*) resourses?\n\n========================================\n\nTop Answer:\nWhile James' answer is valid, I would not recommend linking your contract's dependencies from an online repository, this is highly insecure since your code depends on some online source that can be dynamically updated and because you might get unstable versions.\n\nI would strongly recommend you Zeppelin's recommended way to use OpenZeppelin contracts, allowing you to use only stable releases and easily update the dependencies to get the latest features and bug-fixes:\n\n```\nnpm init -y\nnpm install -E zeppelin-solidity\n```\n\nThen in your contract:\n\n```\nimport 'zeppelin-solidity/contracts/math/SafeMath.sol';\n\ncontract MyContract {\n using SafeMath for uint;\n ...\n}\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.15;\n\nimport './ERC20.sol';\nimport './SafeMath.sol';\n```\n\n```text\npragma solidity ^0.4.0;\n\nimport \"github.com/OpenZeppelin/zeppelin-solidity/contracts/math/SafeMath.sol\";\n\ncontract MathExtended {\n    using SafeMath for uint;\n    function exec(uint a, uint b) returns (uint){\n        return a.add(b);\n    }\n}\n```\n\n```text\nnpm init -y\nnpm install -E zeppelin-solidity\n```\n\n```text\nimport 'zeppelin-solidity/contracts/math/SafeMath.sol';\n\ncontract MyContract {\n  using SafeMath for uint;\n  ...\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":73,"estimatedTokens":398}}258{"id":"stack-43028611","source":"stackoverflow","questionId":43028611,"title":"Access multiple return values (a, b, c) from solidity function in web3js","tags":["blockchain","ethereum","solidity"],"text":"Title: Access multiple return values (a, b, c) from solidity function in web3js\nTags: blockchain, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI have a function that returns multiple values. I wish to access these from Web3js.\n\n```\nfunction testReturnBet(uint index) constant returns (address player, \n uint tokensPlaced, \n uint8[4] numbers,\n uint ratioIndex,\n uint timestamp,\n uint rollIndex,\n uint winAmount) {\n bet outBet = bets[index];\n return (outBet.player,\n outBet.tokensPlaced, \n outBet.numbers, \n outBet.ratioIndex, \n outBet.timestamp, \n outBet.rollIndex, \n outBet.winAmount);\n }\n```\n\n========================================\n\nTop Answer:\nThis question is the same as this one on Ethereum.SE.\n\nAs suggested there as well, this blog for full details: https://blockheroes.dev/js-read-multiple-returned-values-solidity/\n\nThe solution for you should be the following:\n\n```\nconst result = await contractInstance.yourFunction(param);\nconst {0: variable_1, 1: variable_2} = result;\n```\n\n========================================\n\nCode:\n```text\nfunction testReturnBet(uint index) constant returns (address player, \n                                                     uint tokensPlaced, \n                                                     uint8[4] numbers,\n                                                     uint ratioIndex,\n                                                     uint timestamp,\n                                                     uint rollIndex,\n                                                     uint winAmount) {\n        bet outBet = bets[index];\n        return (outBet.player,\n                outBet.tokensPlaced, \n                outBet.numbers, \n                outBet.ratioIndex, \n                outBet.timestamp, \n                outBet.rollIndex, \n                outBet.winAmount);\n    }\n```\n\n```text\ncontract.testReturnBet(index).then(function(response) {\n  console.log(response); // should be an array\n});\n```\n\n```text\nconst result = await contractInstance.yourFunction(param);\nconst {0: variable_1, 1: variable_2} = result;\n```\n\n========================================\n\nComments:\n- So the return value is simply an array of all the return values in order. Cool.\n- Ioana Roceanu, a link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it is there, then quote the most relevant part of the page you are linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":78,"estimatedTokens":643}}259{"id":"stack-73395638","source":"stackoverflow","questionId":73395638,"title":"Transaction reverted: function returned an unexpected amount of data while testing with ether.js (uniswapv2router.swapExactTokensForTokens function)","tags":["javascript","solidity","hardhat","ether"],"text":"Title: Transaction reverted: function returned an unexpected amount of data while testing with ether.js (uniswapv2router.swapExactTokensForTokens function)\nTags: javascript, solidity, hardhat, ether\nSource: Stack Overflow\n\nQuestion:\nim testing UNISWAP_V2_ROUTER.swapExactTokensForTokens using ether.js and this line: `await swapInstances.connect(accounts[0]).swap(tokenIn, tokenOut, amountIn, amountOutMin, to);` cause this error : `Transaction reverted: function returned an unexpected amount of data`.\n\nwhy?\n\nunit test :\n\n```\nit(\"should be able to swap tokens\", async function () {\n accounts = await ethers.getSigners()\n to = await accounts[1].getAddress();\n const Swap = await ethers.getContractFactory(\"Swap\", accounts[0]);\n const swapInstances = await Swap.deploy();\n const LocandaToken = await ethers.getContractFactory(\"LocandaToken\", accounts[0]); //ERC20\n const locandaToken = await LocandaToken.deploy();\n const RubiconPoolToken = await ethers.getContractFactory(\"RubiconPoolToken\", accounts[1]); //ERC20\n const rubiconPoolToken = await RubiconPoolToken.deploy();\n tokenIn = locandaToken.address;\n tokenOut = rubiconPoolToken.address;\n\n await locandaToken.connect(accounts[0]).transfer(swapInstances.address, amountIn);\n await rubiconPoolToken.connect(accounts[1]).transfer(swapInstances.address, amountIn);\n\n \n const ethBalance = await ethers.provider.getBalance(accounts[0].address);\n console.log(\"eth balance\" + ethBalance);\n\n await locandaToken.connect(accounts[0]).approve(swapInstances.address, amountIn)\n const test = await swapInstances.connect(accounts[0]).swap(tokenIn, tokenOut, amountIn, amountOutMin, to);\n })\n```\n\nswap function :\n\n```\nfunction swap(\n address _tokenIn,\n address _tokenOut,\n uint256 _amountIn,\n uint256 _amountOutMin,\n address _to // address where sending the tokenout\n ) external {\n IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn); // transfer from user wallet to this contract\n IERC20(_tokenIn).approve(UNISWAP_V2_ROUTER, _amountIn); // aprove the router to spend _tokenin\n address[] memory path; //represents the path/flow of the swap\n\n if (_tokenIn == WETH || _tokenOut == WETH) {\n path = new address[](2);\n path[0] = _tokenIn;\n path[1] = _tokenOut;\n } else {\n path = new address[](3);\n path[0] = _tokenIn;\n path[1] = WETH;\n path[2] = _tokenOut;\n }\n\n IUniswapV2Router(UNISWAP_V2_ROUTER).swapExactTokensForTokens(\n _amountIn,\n _amountOutMin,\n path,\n _to,\n block.timestamp\n );\n\n \n }\n```\n\n========================================\n\nTop Answer:\nI also got this error when I used Router1 Address instead of Router2 address.\n\nAfter use correct router address, it's solved.\n\n========================================\n\nCode:\n```text\nit(\"should be able to swap tokens\", async function () {\n            accounts = await ethers.getSigners()\n            to = await accounts[1].getAddress();\n            const Swap = await ethers.getContractFactory(\"Swap\", accounts[0]);\n            const swapInstances = await Swap.deploy();\n            const LocandaToken = await ethers.getContractFactory(\"LocandaToken\", accounts[0]); //ERC20\n            const locandaToken = await LocandaToken.deploy();\n            const RubiconPoolToken = await ethers.getContractFactory(\"RubiconPoolToken\", accounts[1]); //ERC20\n            const rubiconPoolToken = await RubiconPoolToken.deploy();\n            tokenIn = locandaToken.address;\n            tokenOut = rubiconPoolToken.address;\n\n            await locandaToken.connect(accounts[0]).transfer(swapInstances.address, amountIn);\n            await rubiconPoolToken.connect(accounts[1]).transfer(swapInstances.address, amountIn);\n\n            \n            const ethBalance = await ethers.provider.getBalance(accounts[0].address);\n            console.log(\"eth balance\" + ethBalance);\n\n            await locandaToken.connect(accounts[0]).approve(swapInstances.address, amountIn)\n            const test = await swapInstances.connect(accounts[0]).swap(tokenIn, tokenOut, amountIn, amountOutMin, to);\n        })\n```\n\n```text\nfunction swap(\n        address _tokenIn,\n        address _tokenOut,\n        uint256 _amountIn,\n        uint256 _amountOutMin,\n        address _to // address where sending the tokenout\n    ) external {\n        IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn); // transfer from user wallet to this contract\n        IERC20(_tokenIn).approve(UNISWAP_V2_ROUTER, _amountIn); // aprove the router to spend _tokenin\n        address[] memory path; //represents the path/flow of the swap\n\n        if (_tokenIn == WETH || _tokenOut == WETH) {\n            path = new address[](2);\n            path[0] = _tokenIn;\n            path[1] = _tokenOut;\n        } else {\n            path = new address[](3);\n            path[0] = _tokenIn;\n            path[1] = WETH;\n            path[2] = _tokenOut;\n        }\n\n        IUniswapV2Router(UNISWAP_V2_ROUTER).swapExactTokensForTokens(\n            _amountIn,\n            _amountOutMin,\n            path,\n            _to,\n            block.timestamp\n        );\n\n     \n    }\n```\n\n```text\nawait swapInstances.connect(accounts[0]).swap(tokenIn, tokenOut, amountIn, amountOutMin, to);\n```\n\n```text\nTransaction reverted: function returned an unexpected amount of data\n```\n\n```js\nawait locandaToken.connect(accounts[0]).transfer(swapInstances.address, amountIn);\n\nawait rubiconPoolToken.connect(accounts[1]).transfer(swapInstances.address, amountIn);\n```\n\n```text\nfunction transfer(address to, uint256 amount) external returns (bool);\nfunction transferFrom(address from, address to, uint256 amount) external returns (bool);\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":161,"estimatedTokens":1391}}260{"id":"stack-71311019","source":"stackoverflow","questionId":71311019,"title":"Error in plugin @nomiclabs/hardhat-etherscan: Error! Missing Or invalid Module name","tags":["ethereum","solidity","smartcontracts","hardhat"],"text":"Title: Error in plugin @nomiclabs/hardhat-etherscan: Error! Missing Or invalid Module name\nTags: ethereum, solidity, smartcontracts, hardhat\nSource: Stack Overflow\n\nQuestion:\nI tried to verify my contract with constructor arguments but hardhat throwing that error everytime\n\n```\nnpx hardhat verify --network rinkeby 0x50a45120252c2FeeD06915F46D8Fbabec1a008df \"TestSmartContract\" \"TSC\" \"my_ipfs_link1\" \"my_ipfs_link2\"\n```\n\nthese arguments is same as my contract's arguments\nhttps://i.sstatic.net/OWJoL.png\n\n========================================\n\nTop Answer:\nThe issue seems to occur with the 3.0.2 version of @nomiclabs/hardhat-etherscan, it is fixed in the latest version 3.0.3. Please upgrade to the latest version (3.0.3) to fix it or use 3.0.1.\n\n========================================\n\nCode:\n```text\nnpx hardhat verify --network rinkeby 0x50a45120252c2FeeD06915F46D8Fbabec1a008df \"TestSmartContract\" \"TSC\" \"my_ipfs_link1\" \"my_ipfs_link2\"\n```\n\n```text\nnpm i -s @nomiclabs/hardhat-etherscan@3.0.1\n```\n\n========================================\n\nComments:\n- verifying solidity code with anything other than remix has been a pain\n- this fixed the issue OP describes but then in the end it failed anyway with Reason: Fail - Unable to verify. Any idea?\n- ah then this is because the arguments u inputed for verification is not correct, it's not a hardhat issue:)\n- But my constructor doesn't take any arguments ..","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":37,"estimatedTokens":354}}261{"id":"stack-71928224","source":"stackoverflow","questionId":71928224,"title":"Create a transaction with data using etherjs","tags":["solidity","ethers.js","hardhat"],"text":"Title: Create a transaction with data using etherjs\nTags: solidity, ethers.js, hardhat\nSource: Stack Overflow\n\nQuestion:\nI'm studying the Solidity, and I want to understand how to interact with a smartcotnract and etherjs.\n\nI have a simple function like this:\n\n```\nfunction buyNumber(uint256 _number) public payable {\n \n \n if(msg.value And I have the test\n\n```\nconst tx = {\n from: owner.address,\n to: myContract.address,\n value: ethers.utils.parseEther('0.1'),\n data: '0x4b729aff0000000000000000000000000000000000000000000000000000000000000001'\n }\n\n let sendTx = await owner.sendTransaction(tx);\n\n console.log(sendTx)\n```\n\nNow, the transaction works because I get `0x4b729aff0000000000000000000000000000000000000000000000000000000000000001` the function signature and parameters with\n\n```\nlet iface = new ethers.utils.Interface(ABI)\n iface.encodeFunctionData(\"buyNumber\", [ 1 ])\n0x4b729aff0000000000000000000000000000000000000000000000000000000000000001\n```\n\nCan I get the same result in easy way? How can I call a function in my contract with params? I could put the msg.value as parameter, but I prefer to use less parameters\n\n========================================\n\nCode:\n```text\nfunction buyNumber(uint256 _number) public payable {\n      \n      \n      if(msg.value < 0.1 ether){\n        revert(\"more eth!\");\n      }\n\n      ...todoStuff\n\n    }\n```\n\n```js\nconst tx = {\n        from: owner.address,\n        to: myContract.address,\n        value: ethers.utils.parseEther('0.1'),\n        data: '0x4b729aff0000000000000000000000000000000000000000000000000000000000000001'\n      }\n\n      let sendTx = await owner.sendTransaction(tx);\n\n      console.log(sendTx)\n```\n\n```text\nlet iface = new ethers.utils.Interface(ABI)\n iface.encodeFunctionData(\"buyNumber\", [ 1 ])\n0x4b729aff0000000000000000000000000000000000000000000000000000000000000001\n```\n\n```text\n0x4b729aff0000000000000000000000000000000000000000000000000000000000000001\n```\n\n```text\nconst contract = new ethers.Contract(contractAddress, abiJson, signerInstance);\n\n// the Solidity function accepts 1 param - a number\n// the last param is the `overrides` object - see docs below\nawait contract.buyNumber(1, {\n    value: ethers.utils.parseEther('0.1')\n});\n```\n\n```text\ndata\n```\n\n```text\nvalue\n```\n\n========================================\n\nComments:\n- Do I need to supply a full abi json? In some code samples I noticed it is enough to pass a signature of the function you are going to call, e.g. `function buyNumber(uint256 _number) public payable`\n- @Gleichmut You can pass just the parts of the ABI that are relevant to your JS code.","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":100,"estimatedTokens":648}}262{"id":"stack-71708142","source":"stackoverflow","questionId":71708142,"title":"Gas efficiency of totalSupply() vs. a tokenID counter | ERC-721","tags":["ethereum","solidity","erc721"],"text":"Title: Gas efficiency of totalSupply() vs. a tokenID counter | ERC-721\nTags: ethereum, solidity, erc721\nSource: Stack Overflow\n\nQuestion:\nI'm creating a solidity contract for an NFT and in my `mint` function I'm not sure if a call to `totalSupply()` vs using a token counter and incrementing it is better practice. Does either variation cost more gas? Is one the more standard practice? I've seen examples of both being used.\n\nVariation 1:\n\n```\ncontract MyNFT is ERC721Enumerable, PaymentSplitter, Ownable {\n using Counters for Counters.Counter;\n Counters.Counter private currentTokenId;\n...\n\nfunction mint(uint256 _count)\n public payable\n{\n uint256 tokenId = currentTokenId.current();\n require(tokenId Variation 2:\n\n```\nfunction mint(uint256 _count)\n public payable\n{\n uint supply = totalSupply();\n require( supply + _count Both versions seem to work. I just want to be sure I'm using the most efficient / secure. Thanks for any advice!\n\n========================================\n\nCode:\n```text\ncontract MyNFT is ERC721Enumerable, PaymentSplitter, Ownable {\n    using Counters for Counters.Counter;\n    Counters.Counter private currentTokenId;\n...\n\nfunction mint(uint256 _count)\n        public payable\n{\n    uint256 tokenId = currentTokenId.current();\n    require(tokenId < MAX_SUPPLY, \"Max supply reached\");\n    for(uint i = 0; i < _count; ++i){\n        currentTokenId.increment();\n        uint256 newItemId = currentTokenId.current();\n        _safeMint(msg.sender, newItemId);\n    }\n}\n}\n```\n\n```text\nfunction mint(uint256 _count)\n        public payable\n{\n    uint supply = totalSupply();\n    require( supply + _count <= MAX_SUPPLY, \"Exceeds max supply.\" );\n    for(uint i = 0; i < _count; ++i){\n        _safeMint(msg.sender, supply + i);\n    }\n}\n```\n\n```text\nmint\n```\n\n```text\ntotalSupply()\n```\n\n```text\nCounter\n```\n\n```text\ntotalSupply\n```\n\n```text\nCounter\n```\n\n```text\nsstore\n```\n\n```text\nsload\n```\n\n```text\nsstore\n```\n\n```text\nsload\n```\n\n========================================\n\nComments:\n- Remix show the gas used when a function is called, just compare the gas usage. Similarly there plugins to measure gas consumption for Truffle and others tools.\n- Looping is not so efficient solution. Without whole contract code base is hard to predict efficiency. You can try to analyze assembly of this contract\n- Thanks for the advice. I just started using remix and it's really helpful\n- appreciate the answer, yes I'm using the generic openzeppelin implementations. This makes sense\n- This means totalSupply() is more efficient right","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":107,"estimatedTokens":634}}263{"id":"stack-69312285","source":"stackoverflow","questionId":69312285,"title":"How to convert bytes3 to HEX string in Solidity","tags":["bit-manipulation","solidity","rsk"],"text":"Title: How to convert bytes3 to HEX string in Solidity\nTags: bit-manipulation, solidity, rsk\nSource: Stack Overflow\n\nQuestion:\nI previously asked about converting uint to hex string. Now I want to store a HEX value `0x00ff08` in a `bytes3` variable and to be able to convert it to a `string` in Solidity smart contract. Subsequently I intend to deploy it on RSK with Solidity compiler version at least 0.8.0 .\n\nI tried this `string(abi.encodePacked(bytes3(`**`0x00ff08`**`)))` but it throws a runtime error\n\n*Failed to decode output: null: invalid codepoint at offset 1; bad codepoint prefix (argument=\"bytes\", value={\"0\":0,\"1\":255,\"2\":8}, code=INVALID_ARGUMENT, version=strings/5.4.0)*\n\nA different argument `string(abi.encodePacked(bytes3(`**`0x443322`**`)))` doesn't cause an error, but returns a very strange `D3\"` result. What could be the problem here? How do I convert `bytes3` to a `string` with the same characters?\n\n========================================\n\nCode:\n```text\n0x00ff08\n```\n\n```text\nbytes3\n```\n\n```text\nstring\n```\n\n```text\nstring(abi.encodePacked(bytes3(\n```\n\n```text\n0x00ff08\n```\n\n```text\n)))\n```\n\n```text\nstring(abi.encodePacked(bytes3(\n```\n\n```text\n0x443322\n```\n\n```text\n)))\n```\n\n```text\nD3\"\n```\n\n```text\nbytes3\n```\n\n```text\nstring\n```\n\n```text\nfunction uint8tohexchar(uint8 i) public pure returns (uint8) {\n        return (i > 9) ?\n            (i + 87) : // ascii a-f\n            (i + 48); // ascii 0-9\n    }\n```\n\n```text\nfunction uint24tohexstr(uint24 i) public pure returns (string memory) {\n        bytes memory o = new bytes(6);\n        uint24 mask = 0x00000f;\n        o[5] = bytes1(uint8tohexchar(uint8(i & mask)));\n        i = i >> 4;\n        o[4] = bytes1(uint8tohexchar(uint8(i & mask)));\n        i = i >> 4;\n        o[3] = bytes1(uint8tohexchar(uint8(i & mask)));\n        i = i >> 4;\n        o[2] = bytes1(uint8tohexchar(uint8(i & mask)));\n        i = i >> 4;\n        o[1] = bytes1(uint8tohexchar(uint8(i & mask)));\n        i = i >> 4;\n        o[0] = bytes1(uint8tohexchar(uint8(i & mask)));\n        return string(o);\n    }\n```\n\n```text\nfunction bytes3tohexstr(bytes3 i) public pure returns (string memory) {\n        uint24 n = uint24(i);\n        return uint24tohexstr(n);\n    }\n```\n\n```text\nabi.encodePacked(myBytes3)\n```\n\n```text\nstring(..)\n```\n\n```text\nabi.encodePacked(..)\n```\n\n```text\nbytes3\n```\n\n```text\nstring\n```\n\n```text\nuint8\n```\n\n```text\nuint24\n```\n\n```text\nstring\n```\n\n```text\nbytes3\n```\n\n```text\nbytes3\n```\n\n```text\nbytes3\n```\n\n```text\nuint24\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":27,"totalLines":145,"estimatedTokens":624}}264{"id":"stack-69976064","source":"stackoverflow","questionId":69976064,"title":"Change the state of a variable of a contract B from a Keeper","tags":["solidity","chainlink","chainlink-keepers"],"text":"Title: Change the state of a variable of a contract B from a Keeper\nTags: solidity, chainlink, chainlink-keepers\nSource: Stack Overflow\n\nQuestion:\nThe purpose is to use this variable from the B contract\nIm trying with delegate call but doesnt work,only works with event\n\nContractB.sol\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity >0.8.0;\n\ncontract ContractB {\n \n uint256 public tokenName = uint256(2);\n event SetToken(uint256 _tokenName); \n\n function setTokenName(uint256 _newName) external returns (uint256) { \n setInternal(_newName); \n }\n \n function setInternal (uint256 _newName) public returns (uint256)\n {\n tokenName = _newName;\n emit SetToken(tokenName);\n return tokenName;\n }\n \n function getTokenName() public view returns (uint256)\n {\n return tokenName;\n } \n}\n```\n\nCounter.sol\n\n```\n//Begin\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.6;\n\ninterface KeeperCompatibleInterface {\n function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData);\n function performUpkeep(bytes calldata performData) external;\n}\n\ncontract Counter is KeeperCompatibleInterface {\n \n uint256 public counter; // Public counter variable\n\n // Use an interval in seconds and a timestamp to slow execution of Upkeep\n //60 seconds\n uint public immutable interval;\n uint public lastTimeStamp; //My counter was updated \n \n //**\n address contractBAddress;\n uint256 public tokenName = uint256(2);\n //**\n \n constructor(uint updateInterval,address _contractBAddress) {\n interval = updateInterval;\n lastTimeStamp = block.timestamp;\n counter = 0;\n contractBAddress=_contractBAddress;\n }\n\n function checkUpkeep(bytes calldata checkData) external view override returns (bool upkeepNeeded, bytes memory performData) {\n upkeepNeeded = (block.timestamp - lastTimeStamp) > interval;\n performData = checkData;\n }\n\n \n //When checkUpKeep its already to launch, this task is executed\n function performUpkeep(bytes calldata) external override {\n lastTimeStamp = block.timestamp;\n counter=0;\n counter = counter + 1;\n (bool success, bytes memory returndata) = contractBAddress.delegatecall(\n abi.encodeWithSignature(\"setTokenName(uint256)\", counter)\n );\n\n // if the function call reverted\n if (success == false) {\n // if there is a return reason string\n if (returndata.length > 0) {\n // bubble up any reason for revert\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(\"Function call reverted\");\n }\n }\n }\n function getTokenName() public view returns (uint256)\n {\n return tokenName;\n }\n \n}\n```\n\nThe event works perfect, but i cant change the state in ContractB.sol ...\nhttps://kovan.etherscan.io/tx/0x7fbacd6fa79d73b3b3233e955c9b95ae83efe2149002d1561c696061f6b1695e#eventlog\n\n========================================\n\nTop Answer:\nYou should use this:\n\n```\nContractB contractB = ContractB(contractBAddress);\n contractB.setTokenName(counter);\n```\n\nDocumentation:\nhttps://solidity-by-example.org/calling-contract/\n\nCounter.sol\n\n```\n//Begin\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.6;\n\ninterface KeeperCompatibleInterface {\n function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData);\n function performUpkeep(bytes calldata performData) external;\n}\n\ncontract Counter is KeeperCompatibleInterface {\n \n uint256 public counter; // Public counter variable\n\n // Use an interval in seconds and a timestamp to slow execution of Upkeep\n //60 seconds\n uint public immutable interval;\n uint public lastTimeStamp; //My counter was updated \n \n //**\n address public contractBAddress;\n //**\n \n constructor(uint updateInterval,address _contractBAddress) {\n interval = updateInterval;\n lastTimeStamp = block.timestamp;\n counter = 0;\n contractBAddress=_contractBAddress;\n }\n\n function checkUpkeep(bytes calldata checkData) external view override returns (bool upkeepNeeded, bytes memory performData) {\n upkeepNeeded = (block.timestamp - lastTimeStamp) > interval;\n performData = checkData;\n }\n\n \n //When checkUpKeep its already to launch, this task is executed\n function performUpkeep(bytes calldata) external override {\n lastTimeStamp = block.timestamp;\n counter = counter + 1;\n ContractB contractB = ContractB(contractBAddress);\n contractB.setTokenName(counter);\n }\n \n}\n```\n\nContractB.sol\n\n```\ncontract ContractB {\n \n uint256 public tokenName = uint256(2);\n\n function setTokenName(uint256 _newName) external { \n tokenName=_newName;\n }\n \n \n function getTokenName() public view returns (uint256)\n {\n return tokenName;\n }\n \n}\n```\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: MIT\npragma solidity >0.8.0;\n\ncontract ContractB {\n    \n    uint256 public tokenName = uint256(2);\n    event SetToken(uint256 _tokenName); \n\n    function setTokenName(uint256 _newName) external returns (uint256) {                \n        setInternal(_newName);  \n    }\n    \n    function setInternal (uint256 _newName) public returns (uint256)\n    {\n        tokenName = _newName;\n        emit SetToken(tokenName);\n        return tokenName;\n    }\n            \n    function getTokenName() public view returns (uint256)\n    {\n        return tokenName;\n    }        \n}\n```\n\n```text\n//Begin\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.6;\n\ninterface KeeperCompatibleInterface {\n    function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData);\n    function performUpkeep(bytes calldata performData) external;\n}\n\ncontract Counter is KeeperCompatibleInterface {\n    \n    uint256 public counter;    // Public counter variable\n\n    // Use an interval in seconds and a timestamp to slow execution of Upkeep\n    //60 seconds\n    uint public immutable interval;\n    uint public lastTimeStamp;  //My counter was updated  \n    \n    //**\n    address contractBAddress;\n    uint256 public tokenName = uint256(2);\n    //**\n    \n    constructor(uint updateInterval,address _contractBAddress) {\n      interval = updateInterval;\n      lastTimeStamp = block.timestamp;\n      counter = 0;\n      contractBAddress=_contractBAddress;\n    }\n\n    function checkUpkeep(bytes calldata checkData) external view override returns (bool upkeepNeeded, bytes memory performData) {\n        upkeepNeeded = (block.timestamp - lastTimeStamp) > interval;\n        performData = checkData;\n    }\n\n    \n    //When checkUpKeep its already to launch, this task is executed\n    function performUpkeep(bytes calldata) external override {\n        lastTimeStamp = block.timestamp;\n        counter=0;\n        counter = counter + 1;\n        (bool success, bytes memory returndata) = contractBAddress.delegatecall(\n              abi.encodeWithSignature(\"setTokenName(uint256)\", counter)\n        );\n\n        // if the function call reverted\n        if (success == false) {\n            // if there is a return reason string\n            if (returndata.length > 0) {\n                // bubble up any reason for revert\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(\"Function call reverted\");\n            }\n        }\n    }\n    function getTokenName() public view returns (uint256)\n    {\n        return tokenName;\n    }\n    \n}\n```\n\n```text\npragma solidity ^0.8.0;\n\nimport \"./ContractB.sol\";\n\ncontract Counter is KeeperCompatibleInterface {\n    ContractB public contractB;\n    uint256 public counter;\n\n    constructor(ContractB _contractBAddress) {\n        contractB = _contractBAddress;\n    }\n\n    function performUpkeep(bytes calldata) external override {\n        counter = counter + 1;\n        contractB.setTokenName(counter);\n    }\n}\n```\n\n```text\ndelegatecall\n```\n\n```text\nA\n```\n\n```text\ndelegatecall\n```\n\n```text\nB\n```\n\n```text\nB\n```\n\n```text\nA\n```\n\n```text\nmsg.sender\n```\n\n```text\nmsg.value\n```\n\n```text\nA\n```\n\n```text\nB\n```\n\n```text\nsetTokenName\n```\n\n```text\nContractB\n```\n\n```text\ntokenName\n```\n\n```text\nContractB\n```\n\n```text\nCounter\n```\n\n```text\nuint256 public counter\n```\n\n```text\ndelegatecall\n```\n\n```text\nCounter\n```\n\n```text\ncounter\n```\n\n```text\nContractB\n```\n\n```text\nsetTokenName\n```\n\n```text\nContractB\n```\n\n```text\nContractB contractB = ContractB(contractBAddress);\n    contractB.setTokenName(counter);\n```\n\n```text\n//Begin\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.6;\n\ninterface KeeperCompatibleInterface {\n    function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData);\n    function performUpkeep(bytes calldata performData) external;\n}\n\ncontract Counter is KeeperCompatibleInterface {\n    \n    uint256 public counter;    // Public counter variable\n\n    // Use an interval in seconds and a timestamp to slow execution of Upkeep\n    //60 seconds\n    uint public immutable interval;\n    uint public lastTimeStamp;  //My counter was updated  \n    \n    //**\n    address public contractBAddress;\n    //**\n    \n    constructor(uint updateInterval,address _contractBAddress) {\n      interval = updateInterval;\n      lastTimeStamp = block.timestamp;\n      counter = 0;\n      contractBAddress=_contractBAddress;\n    }\n\n    function checkUpkeep(bytes calldata checkData) external view override returns (bool upkeepNeeded, bytes memory performData) {\n        upkeepNeeded = (block.timestamp - lastTimeStamp) > interval;\n        performData = checkData;\n    }\n\n    \n    //When checkUpKeep its already to launch, this task is executed\n    function performUpkeep(bytes calldata) external override {\n        lastTimeStamp = block.timestamp;\n        counter = counter + 1;\n        ContractB contractB = ContractB(contractBAddress);\n        contractB.setTokenName(counter);\n    }\n    \n}\n```\n\n```text\ncontract ContractB {\n    \n    uint256 public tokenName = uint256(2);\n\n    function setTokenName(uint256 _newName) external {                \n      tokenName=_newName;\n    }\n    \n    \n    function getTokenName() public view returns (uint256)\n    {\n        return tokenName;\n    }\n    \n}\n```\n\n========================================\n\nComments:\n- Please edit your question and paste the code as text, so that it's easier for answerers to copy-paste and debug.","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":472,"estimatedTokens":2557}}265{"id":"stack-69647532","source":"stackoverflow","questionId":69647532,"title":"Checking and granting role in Solidity","tags":["ethereum","solidity","smartcontracts"],"text":"Title: Checking and granting role in Solidity\nTags: ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a factory contract which is used to mint ERC721 tokens, at two different prices depending on whether it's during presale.\n\nI'm using the Access library from OpenZeppelin, and have my contract set up with two roles (plus the default administrator role). Some lines are excluded for brevity:\n\n```\nimport \"@openzeppelin/contracts/access/AccessControl.sol\";\nimport \"./Example.sol\";\n\ncontract ExampleFactory is AccessControl {\n // ...\n\n bool public ONLY_WHITELISTED = true;\n uint256 public PRESALE_COST = 6700000 gwei;\n uint256 public SALE_COST = 13400000 gwei;\n uint256 MAX_PRESALE_MINT = 2;\n uint256 MAX_LIVE_MINT = 10;\n uint256 TOTAL_SUPPLY = 100;\n\n // ...\n\n bytes32 public constant ROLE_MINTER = keccak256(\"ROLE_MINTER\");\n bytes32 public constant ROLE_PRESALE = keccak256(\"ROLE_PRESALE\");\n \n // ...\n\n constructor(address _nftAddress) {\n nftAddress = _nftAddress;\n\n // Grant the contract deployer the default admin role: it will be able\n // to grant and revoke any roles\n _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);\n _setupRole(ROLE_MINTER, msg.sender);\n _setupRole(ROLE_PRESALE, msg.sender);\n }\n\n function mint(uint256 _mintAmount, address _toAddress) public payable {\n // If the user doesn't have the minter role then require payment\n if (hasRole(ROLE_MINTER, msg.sender) == false) {\n if (ONLY_WHITELISTED == true) {\n // If still in whitelist mode then require presale role & enough value\n require(hasRole(ROLE_PRESALE, msg.sender), \"address is not whitelisted\");\n require(msg.value >= PRESALE_COST * _mintAmount, \"tx value too low for quantity\");\n } else {\n require(msg.value >= SALE_COST * _mintAmount, \"tx value too low for quantity\");\n }\n }\n\n // Check there are enough tokens left to mint\n require(canMint(_mintAmount), \"remaining supply too low\");\n\n Example token = Example(nftAddress);\n for (uint256 i = 0; i There are a couple of different paths to mint:\n\n- If the user has `ROLE_MINTER`, they can mint without payment or limits\n\n- If `ONLY_WHITELISTED` is `true`, the transaction must have enough value for presale price, and they must have `ROLE_PRESALE`\n\n- If `ONLY_WHITELISTED` is `false`, anyone can mint\n\nI've written a script to test minting:\n\n```\nconst factoryContract = new web3Instance.eth.Contract(\n FACTORY_ABI,\n FACTORY_CONTRACT_ADDRESS,\n { gasLimit: '1000000' }\n);\n\nconsole.log('Testing mint x3 from minter role')\ntry {\n const result = await factoryContract.methods\n .mint(3, OWNER_ADDRESS)\n .send({ from: OWNER_ADDRESS });\n console.log(' ✅ Minted 3x. Transaction: ' + result.transactionHash);\n} catch (err) {\n console.log(' 🚨 Mint failed')\n console.log(err)\n}\n```\n\nRunning this successfully mints 3 tokens to the factory owner. No value is attached to this call, and it's minting more than the maximum, so in order for it to be successful it has to the `ROLE_MINTER` path.\n\nHowever, if I call `hasRole` from the same address, the result is `false` which doesn't make sense.\n\n```\nconst minterHex = web3.utils.fromAscii('ROLE_MINTER')\nconst result = await factoryContract.methods.hasRole(minterHex, OWNER_ADDRESS).call({ from: OWNER_ADDRESS });\n// result = false\n```\n\nIf I try to run the test mint script from another address (with no roles) it failed as expected, which suggests roles are working but I'm using `hasRole` wrong?\n\n========================================\n\nCode:\n```text\nimport \"@openzeppelin/contracts/access/AccessControl.sol\";\nimport \"./Example.sol\";\n\ncontract ExampleFactory is AccessControl {\n  // ...\n\n  bool public ONLY_WHITELISTED = true;\n  uint256 public PRESALE_COST = 6700000 gwei;\n  uint256 public SALE_COST = 13400000 gwei;\n  uint256 MAX_PRESALE_MINT = 2;\n  uint256 MAX_LIVE_MINT = 10;\n  uint256 TOTAL_SUPPLY = 100;\n\n  // ...\n\n  bytes32 public constant ROLE_MINTER = keccak256(\"ROLE_MINTER\");\n  bytes32 public constant ROLE_PRESALE = keccak256(\"ROLE_PRESALE\");\n  \n  // ...\n\n  constructor(address _nftAddress) {\n    nftAddress = _nftAddress;\n\n    // Grant the contract deployer the default admin role: it will be able\n    // to grant and revoke any roles\n    _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);\n    _setupRole(ROLE_MINTER, msg.sender);\n    _setupRole(ROLE_PRESALE, msg.sender);\n  }\n\n  function mint(uint256 _mintAmount, address _toAddress) public payable {\n    // If the user doesn't have the minter role then require payment\n    if (hasRole(ROLE_MINTER, msg.sender) == false) {\n        if (ONLY_WHITELISTED == true) {\n            // If still in whitelist mode then require presale role & enough value\n            require(hasRole(ROLE_PRESALE, msg.sender), \"address is not whitelisted\");\n            require(msg.value >= PRESALE_COST * _mintAmount, \"tx value too low for quantity\");\n        } else {\n            require(msg.value >= SALE_COST * _mintAmount, \"tx value too low for quantity\");\n        }\n    }\n\n    // Check there are enough tokens left to mint\n    require(canMint(_mintAmount), \"remaining supply too low\");\n\n    Example token = Example(nftAddress);\n    for (uint256 i = 0; i < _mintAmount; i++) {\n        token.mintTo(_toAddress);\n    }\n  }\n\n  function canMint(uint256 _mintAmount) public view returns (bool) {\n    if (hasRole(ROLE_MINTER, msg.sender) == false) {\n        if (ONLY_WHITELISTED == true) {\n            require((_mintAmount <= MAX_PRESALE_MINT), \"max 2 tokens can be minted during presale\");\n        } else {\n            require((_mintAmount <= MAX_LIVE_MINT), \"max 10 tokens can be minted during sale\");\n        }\n    }\n\n    Example token = Example(nftAddress);\n    uint256 issuedSupply = token.totalSupply();\n    return issuedSupply < (TOTAL_SUPPLY - _mintAmount);\n  }\n}\n```\n\n```text\nconst factoryContract = new web3Instance.eth.Contract(\n  FACTORY_ABI,\n  FACTORY_CONTRACT_ADDRESS,\n  { gasLimit: '1000000' }\n);\n\nconsole.log('Testing mint x3 from minter role')\ntry {\n  const result = await factoryContract.methods\n    .mint(3, OWNER_ADDRESS)\n    .send({ from: OWNER_ADDRESS });\n  console.log('  ✅  Minted 3x. Transaction: ' + result.transactionHash);\n} catch (err) {\n  console.log('  🚨  Mint failed')\n  console.log(err)\n}\n```\n\n```text\nconst minterHex = web3.utils.fromAscii('ROLE_MINTER')\nconst result = await factoryContract.methods.hasRole(minterHex, OWNER_ADDRESS).call({ from: OWNER_ADDRESS });\n// result = false\n```\n\n```text\nROLE_MINTER\n```\n\n```text\nONLY_WHITELISTED\n```\n\n```text\ntrue\n```\n\n```text\nROLE_PRESALE\n```\n\n```text\nONLY_WHITELISTED\n```\n\n```text\nfalse\n```\n\n```text\nROLE_MINTER\n```\n\n```text\nhasRole\n```\n\n```text\nfalse\n```\n\n```text\nhasRole\n```\n\n```text\nconst minterHex = web3.utils.fromAscii('ROLE_MINTER')\n```\n\n```text\nbytes32 public constant ROLE_MINTER = keccak256(\"ROLE_MINTER\");\n```\n\n```text\nconst minterHash = web3.utils.soliditySha3('ROLE_MINTER');\nconst result = await factoryContract.methods.hasRole(minterHash, OWNER_ADDRESS).call();\n```\n\n```text\nROLE_MINTER\n```\n\n```text\n0x524f4c455f4d494e544552\n```\n\n```text\nkeccak256\n```\n\n```text\nROLE_MINTER\n```\n\n```text\n0xaeaef46186eb59f884e36929b6d682a6ae35e1e43d8f05f058dcefb92b601461\n```\n\n```text\nOWNER_ADDRESS\n```\n\n```text\n0x524f4c455f4d494e544552\n```\n\n```text\nfalse\n```\n\n```text\nweb3.utils.soliditySha3()\n```\n\n```text\nmsg.sender\n```\n\n```text\ncall()\n```\n\n```text\nhasRole()\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":28,"totalLines":293,"estimatedTokens":1817}}266{"id":"stack-60593821","source":"stackoverflow","questionId":60593821,"title":"ModuleNotFoundError: No module named 'knox'","tags":["solidity","metamask"],"text":"Title: ModuleNotFoundError: No module named 'knox'\nTags: solidity, metamask\nSource: Stack Overflow\n\nQuestion:\nI added the *Django-rest-Knox* into the requirement.txt then ran the *\"docker-compose up\"* command in my terminal. But, I got this error message \"ModuleNotFoundError: No module named 'Knox'\". Any idea, why is that?\n\n========================================\n\nTop Answer:\nI ran into the same problem and realized that I installed Django-rest-knox under virtual environment.\n\n========================================\n\nCode:\n```text\npip install -U django-rest-knox\n```\n\n========================================\n\nComments:\n- after pip install django-rest-knox you need to migrate : python manage.py migrate","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":23,"estimatedTokens":178}}267{"id":"stack-68930328","source":"stackoverflow","questionId":68930328,"title":"Can NFT be used for authentication on web apps","tags":["ethereum","solidity","smartcontracts"],"text":"Title: Can NFT be used for authentication on web apps\nTags: ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nCan NFT's be used as a mean of authentication? The scenario is a user buys an NFT (ERC721) now he visits the site that uses this Token for authentication, so am guessing the web3.js on the site checks the users wallet if he has the token in wallet then can access the site....but what about server side calls...the server can check the ledger to see who owns the token, but how can it know if the person making the call is the owner..address can be spoofed so sending it with call is out of question. Also the case if users sells his token now a new user owns it\n\nAm thinking something like digital signature but how to get the owners public key and is requiring users to sign messages a hassle...am noob to solidity what do I know but **SO** requires me to try to answer my question before asking for an answer also some code a requirement for every posts\n\n```\npragma solidity ^0.4.22;contract helloWorld {\n function renderHelloWorld () public pure returns (string) {\n return 'helloWorld';\n }\n}\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.22;contract helloWorld {\n function renderHelloWorld () public pure returns (string) {\n   return 'helloWorld';\n }\n}\n```\n\n========================================\n\nComments:\n- Thanks man this is a good article to get me started, yes I have seen Metakey also the bored-ape-yacht-club uses some method to verify membership with their NFT tokens and that's what am trying to recreate.need to allow Only users who have a token...did not think of the transfer events good point thought I keep a cron job back-end do a daily checkup..testing a function like that will be fun :(\n- I went to tutorial article. I think it's outdated (and as typical, this author fails to date stamp it. UGH!) According to below, web3.js has been removed from MetaMask. docs.metamask.io/guide/&hellip;\n- @codechimp Looks like you're right, built is still possible to build a login flow with some additional setup. Metamask links to this tutorial from their documentation: medium.com/hackernoon/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":34,"estimatedTokens":545}}268{"id":"stack-53775288","source":"stackoverflow","questionId":53775288,"title":"How to handle decimal numbers in solidity?","tags":["solidity"],"text":"Title: How to handle decimal numbers in solidity?\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nHow to handle decimal numbers in solidity?\nIf you want to find the percentage of some amount and do some calculation on that number, how to do that?\n\nSuppose I perform : 15 % of 45 and need to divide that value with 7 how to get the answer.\n\nPlease help. I have done research, but getting answer like it is not possible to do that calculation. Please help.\n\n========================================\n\nCode:\n```text\n45 * 15 / 100 = 6\n```\n\n```text\n4500 * 15 / 100 = 675\n```\n\n========================================\n\nComments:\n- So how to get the final answer. 675 will be stored there.\n- I'm not sure what you mean. Just store 675. If you're asking how to display something like \"6.75\" in UI, just divide by 100 (e.g. in JavaScript on a web page or wherever you're building such UI).","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":28,"estimatedTokens":220}}269{"id":"stack-64711324","source":"stackoverflow","questionId":64711324,"title":"Solidity : Getting error as Member “balance” not found or not visible after argument-dependent lookup","tags":["blockchain","ethereum","solidity","decentralized-applications"],"text":"Title: Solidity : Getting error as Member “balance” not found or not visible after argument-dependent lookup\nTags: blockchain, ethereum, solidity, decentralized-applications\nSource: Stack Overflow\n\nQuestion:\nI am trying to write a Decentralization App to buy a concert ticket. For some reason, the part owner.transfer(this.balance) keeps giving me error. Also since solidity has too many version, I can't find a the best for mine. please help me in this. Thank you\n\nErro Message\n\n```\nGetting error as Member “balance” not found or not visible after argument-dependent lookup. Use address(this).balance to access address owner.transfer(this.balance)\n```\n\nSolidity Code\n\n```\npragma solidity 0.6.6;\n\ncontract Event {\n \n address owner;\n uint public tickets;\n string public description;\n string public website;\n uint constant price = 0.01 ether;\n mapping (address => uint) public purchasers;\n \n constructor(uint t, string memory _description, string memory _webstite) public {\n owner = msg.sender;\n description = _description;\n website = _webstite;\n tickets = t;\n }\n \n // function () payable {\n // buyTickets(1);\n // }\n \n function buyTickets(uint amount) public payable {\n if (msg.value != (amount * price) || amount > tickets) {\n revert();\n }\n purchasers[msg.sender] += amount;\n tickets -= amount;\n if (tickets == 0) {\n owner.transfer(this.balance);\n }\n }\n \n function refund(uint numTickets) public {\n if (purchasers[msg.sender] After I change it to `owner.transfer(address(this).balance);`, it gave me another error.\n\n```\n[vm] from: 0x5b3...eddc4to: Event.buyTickets(uint256) 0xd91...39138value: 0 weidata: 0x2f3...00001logs: 0hash: 0x030...bbdf1\nstatus 0x0 Transaction mined but execution failed\n transaction hash 0x03045aab3f5d40ebeef4eacedf50ce506edfc2b75c279652839fd74f8e9bbdf1 \n from 0x5b38da6a701c568545dcfcb03fcb875f56beddc4 \n to Event.buyTickets(uint256) 0xd9145cce52d386f254917e481eb44e9943f39138 \n gas 3000000 gas \n transaction cost 21760 gas \n execution cost 296 gas \n hash 0x03045aab3f5d40ebeef4eacedf50ce506edfc2b75c279652839fd74f8e9bbdf1 \n input 0x2f3...00001 \n decoded input { \"uint256 amount\": { \"_hex\": \"0x01\" } } \n decoded output {} \n logs [] \n value 0 wei \ntransact to Event.buyTickets errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.\n```\n\n========================================\n\nCode:\n```text\nGetting error as Member “balance” not found or not visible after argument-dependent lookup. Use address(this).balance to access address owner.transfer(this.balance)\n```\n\n```text\npragma solidity 0.6.6;\n\ncontract Event {\n    \n    address owner;\n    uint public tickets;\n    string public description;\n    string public website;\n    uint constant price = 0.01 ether;\n    mapping (address => uint) public purchasers;\n    \n    constructor(uint t,  string memory _description, string memory _webstite) public {\n        owner = msg.sender;\n        description = _description;\n        website = _webstite;\n        tickets = t;\n    }\n    \n    // function () payable {\n    //     buyTickets(1);\n    // }\n    \n    function buyTickets(uint amount) public payable {\n        if (msg.value != (amount * price) || amount > tickets) {\n            revert();\n        }\n        purchasers[msg.sender] += amount;\n        tickets -= amount;\n        if (tickets == 0) {\n            owner.transfer(this.balance);\n        }\n    }\n    \n    function refund(uint numTickets)  public {\n        if (purchasers[msg.sender] < numTickets) {\n            revert();\n        }\n        \n        msg.sender.transfer(numTickets * price);\n        purchasers[msg.sender] -= numTickets;\n        tickets += numTickets;\n    }\n    \n}\n```\n\n```text\n[vm] from: 0x5b3...eddc4to: Event.buyTickets(uint256) 0xd91...39138value: 0 weidata: 0x2f3...00001logs: 0hash: 0x030...bbdf1\nstatus  0x0 Transaction mined but execution failed\n transaction hash   0x03045aab3f5d40ebeef4eacedf50ce506edfc2b75c279652839fd74f8e9bbdf1 \n from   0x5b38da6a701c568545dcfcb03fcb875f56beddc4 \n to Event.buyTickets(uint256) 0xd9145cce52d386f254917e481eb44e9943f39138 \n gas    3000000 gas \n transaction cost   21760 gas \n execution cost 296 gas \n hash   0x03045aab3f5d40ebeef4eacedf50ce506edfc2b75c279652839fd74f8e9bbdf1 \n input  0x2f3...00001 \n decoded input  { \"uint256 amount\": { \"_hex\": \"0x01\" } } \n decoded output {} \n logs   []  \n value  0 wei \ntransact to Event.buyTickets errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.\n```\n\n```text\nowner.transfer(address(this).balance);\n```\n\n```text\naddress payable owner;\n...\nowner.transfer(address(this).balance);\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":151,"estimatedTokens":1232}}270{"id":"stack-58211030","source":"stackoverflow","questionId":58211030,"title":"In solidity, do function signatures take data location into account?","tags":["solidity","evm"],"text":"Title: In solidity, do function signatures take data location into account?\nTags: solidity, evm\nSource: Stack Overflow\n\nQuestion:\nex: if my function in solidity is: \n\n```\nfunction someFunction(uint256 a, bytes calldata _data) external { \n//some stuff \n}\n```\n\nwould the function signature be the first four bytes of the hash of: `someFunction(uint256,bytes)` or would it be the first four bytes of the hash of: `someFunction(uint256,bytes calldata)`? or even `someFunction(uint256,bytescalldata)` (with no space between bytes and calldata)\n\n========================================\n\nCode:\n```text\nfunction someFunction(uint256 a, bytes calldata _data) external { \n//some stuff \n}\n```\n\n```text\nsomeFunction(uint256,bytes)\n```\n\n```text\nsomeFunction(uint256,bytes calldata)\n```\n\n```text\nsomeFunction(uint256,bytescalldata)\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":35,"estimatedTokens":206}}271{"id":"stack-58684328","source":"stackoverflow","questionId":58684328,"title":"How to deploy two smart contracts that inherit from each other to test network together?","tags":["deployment","ethereum","solidity","smartcontracts"],"text":"Title: How to deploy two smart contracts that inherit from each other to test network together?\nTags: deployment, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI have two smarts contracts\n\nI working in remix IDE and when I click \"Deploy\", I can deploy only one smart contract. And when I copy ABI, I can copy only one ABI from one contract.\n\nIs there a way to deploy this two contracts together, or should I deploy them seperatly?\nAnd if I will deploy them seperatly how numberTwo contract will find where is numberOne contract?\n\nThank you.\n\n```\npragma solidity ^0.4.25;\ncontract numberOne{\n}\ncontract numberTwo is numberOne{\n}\n```\n\n========================================\n\nTop Answer:\nThe way you wrote it is that your numberTwo contract inherit numberOne so you don't need to deploy the first one separately.\n\nBut if you actually wanna deploy them separately you can do it like this. Just deploy them one by one and then connect the first one to the second one using the address of the first one.\n\n```\ncontract NumberOne {\n uint256 public someData = 256;\n}\n\ncontract NumberTwo {\n\n NumberOne numberOneContract;\n\n function initNumberOne(address _address) public {\n numberOneContract = NumberOne(_address); \n }\n\n function getSomeData() view public returns (uint256) {\n return numberOneContract.someData();\n }\n\n}\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.25;\ncontract numberOne{\n}\ncontract numberTwo is numberOne{\n}\n```\n\n```text\ncontract NumberOne {\n uint256 public someData = 256;\n}\n\ncontract NumberTwo {\n\n  NumberOne numberOneContract;\n\n  function initNumberOne(address _address) public {\n    numberOneContract = NumberOne(_address);            \n  }\n\n  function getSomeData() view public returns (uint256) {\n    return numberOneContract.someData();\n  }\n\n}\n```\n\n========================================\n\nComments:\n- Thank you, I think it should work too. Did you mean return numberOneContract.someData(); ?\n- It won't automatically deploy two contracts though. Your second contract just inheriting all the methods from the first one.\n- That what I thought. But now I can access functions from both contracts from numberTwo contract address.\n- it's just because this is how the inheritance works, NumberOne is not deployed, so when you call it's methods on NumberTwo you just use the inherited methods but store all the data on NumberTwo","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":87,"estimatedTokens":600}}272{"id":"stack-57747986","source":"stackoverflow","questionId":57747986,"title":"SafeMath error on sending tokens via contract","tags":["token","ethereum","solidity"],"text":"Title: SafeMath error on sending tokens via contract\nTags: token, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nWhile attempting to send tokens via a contract I run in to the error message: \"SafeMath: subtraction overflow.\"\n\nInitially I only used the transfer functionality. However, as I thought the msg.sender only has to send its tokens to the other user (via truffle console this is no issue). However, reading [this] I got the impression it is actually the contract address that becomes the msg.sender in the TokenContract. Therefore, (as only the accounts but not the contract itself) I thought that I have to send tokens to the contract first, subsequently approve that the contract is allowed to send tokens on behalf of the msg.sender and subsequently transfer the money. However, I keep having the SafeMath error.\n\nThe TokenContract (not the interface below) implements the The most simple version of my code is as follows:\n\n```\ncontract ContractA {\n\n function pay () public returns (bool) {\n\n TokenContract tk = TokenContract(\"tokenContractAddress\");\n tk.transferFrom(msg.sender, address(this), 5);\n tk.approve(address(this), 5);\n tk.transfer(\"someAccount\", 5);\n\n return true;\n }\n}\n\ninterface TokenContract {\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n function approve(address spender, uint256 amount) external returns (bool);\n function transfer(address recipient, uint256 amount) external returns (bool); \n}\n\ncontract TokenContract is ERC20, ERC20Detailed {\n constructor() ERC20Detailed(\"Token\", \"TKN\", 18) public {\n _mint(msg.sender, 1000);\n }\n}\n```\n\nObviously I expect not the safeMath error to appear. As I transfer money and approve. I just expect the same behaviour as when using truffle console.\n\n========================================\n\nCode:\n```text\ncontract ContractA {\n\n    function pay () public returns (bool) {\n\n        TokenContract tk = TokenContract(\"tokenContractAddress\");\n        tk.transferFrom(msg.sender, address(this), 5);\n        tk.approve(address(this), 5);\n        tk.transfer(\"someAccount\", 5);\n\n        return true;\n    }\n}\n\ninterface TokenContract {\n    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n    function approve(address spender, uint256 amount) external returns (bool);\n    function transfer(address recipient, uint256 amount) external returns (bool);   \n}\n\ncontract TokenContract is ERC20, ERC20Detailed {\n    constructor() ERC20Detailed(\"Token\", \"TKN\", 18) public {\n        _mint(msg.sender, 1000);\n    }\n}\n```\n\n```text\n/**\n     * @dev See `IERC20.transferFrom`.\n     *\n     * Emits an `Approval` event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of `ERC20`;\n     *\n     * Requirements:\n     * - `sender` and `recipient` cannot be the zero address.\n     * - `sender` must have a balance of at least `value`.\n     * - the caller must have allowance for `sender`'s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {\n        _transfer(sender, recipient, amount);\n        _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));\n        return true;\n    }\n```\n\n```text\nContractA\n```\n\n```text\nsender\n```\n\n```text\namount\n```\n\n```text\napprove\n```\n\n```text\npay\n```\n\n```text\ntransferFrom\n```\n\n========================================\n\nComments:\n- You don't need `tk.approve(address(this), 5)`. You do need to make sure *you* approve `ContractA` before calling `pay()`.\n- Thank you so much @smarx. I did not have the time to play around earlier, but you clarified it. Got it working!","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":119,"estimatedTokens":929}}273{"id":"stack-39988104","source":"stackoverflow","questionId":39988104,"title":"Interact with the OS hosting an Ethereum node","tags":["bash","call","ethereum","solidity"],"text":"Title: Interact with the OS hosting an Ethereum node\nTags: bash, call, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nIs there a way to make calls to the system (like calling traceroute) using Solidity or maybe Web3? If that's not a clear question, I'm imagining executing a contract and having that contract perform system commands based on the contract.\n\nI can't think of a way to to this with Embark, which I've been learning, so I'm thinking that I'll just need to send http requests to a python backend where I'll make system calls. Can anyone think of a better way?","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":8,"estimatedTokens":145}}274{"id":"stack-52182503","source":"stackoverflow","questionId":52182503,"title":"Ethereum/Solidity: Do we need to implement an own \"balance\"-variable in Contracts?","tags":["ethereum","solidity","smartcontracts"],"text":"Title: Ethereum/Solidity: Do we need to implement an own \"balance\"-variable in Contracts?\nTags: ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nIn order to manage balances of a smart contract with Solidity, do we still need to implement the `balance`-keeper by ourselves?\n\nIn the following blogpost, the author is doing so:\n\nhttps://medium.com/daox/three-methods-to-transfer-funds-in-ethereum-by-means-of-solidity-5719944ed6e9\n\n```\ncontract Sender {\n function send(address _receiver) payable {\n _receiver.call.value(msg.value).gas(20317)();\n }\n}\n\ncontract Receiver {\n uint public balance = 0;\n\n function () payable {\n balance += msg.value;\n }\n }\n```\n\nAccording to the docs, it seems to already built in: https://solidity.readthedocs.io/en/develop/units-and-global-variables.html#address-related (although it was implemented in the `address`-property which can be cast from `this`, don't know if I understand it correctly)\n\nCan someone Experienced please clarify a bit?\n\nPS: sorry for bad formatting of my question. Safari doesn't show the formatting-toolbar of stackoveflow anymore properly.\n\n========================================\n\nCode:\n```text\ncontract Sender {\n  function send(address _receiver) payable {\n    _receiver.call.value(msg.value).gas(20317)();\n  }\n}\n\ncontract Receiver {\n   uint public balance = 0;\n\n   function () payable {\n      balance += msg.value;\n   }\n }\n```\n\n```text\nbalance\n```\n\n```text\naddress\n```\n\n```text\nthis\n```\n\n```text\n<address>.balance\n```\n\n```text\neth_getBalance\n```\n\n```text\nbalance\n```\n\n```text\nselfdestruct(<address>)\n```\n\n```text\nbalance\n```\n\n```text\n<address>.balance\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":87,"estimatedTokens":408}}275{"id":"stack-49785667","source":"stackoverflow","questionId":49785667,"title":"Truffle migrate success but contract address is not displayed","tags":["ethereum","solidity","truffle"],"text":"Title: Truffle migrate success but contract address is not displayed\nTags: ethereum, solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nI am using testrpc to deploy my contracts. Contract deployment is successful and it also displays the contract address in console when it is deployed.\nhttps://i.sstatic.net/UvDYj.png\nBut when I try to query from truffle console it throws this error: `Contract has no network configuration for its current network id (5777)`. \n\nhttps://i.sstatic.net/NCb2k.png\n\nI am clueless. Any help would be much appreciated. I am using Truffle v4.1.0-beta.0 (core: 4.1.0).\nSolidity v0.4.19 (solc-js)\n\n========================================\n\nCode:\n```text\nContract has no network configuration for its current network id (5777)\n```\n\n```text\nvar Caller = artifacts.require(\"Caller\");\nvar Callee = artifacts.require(\"Callee\");\n\nmodule.exports = function(deployer) {\n  deployer.deploy(Callee).then(function() {\n    return deployer.deploy(Caller, Callee.address);\n  });\n};\n```\n\n========================================\n\nComments:\n- Odd...are you able to get the transaction hash for the V2 deployment in the console? What happens if you do `ContractV2.at(ADDR)`?\n- Yes. When I tried ContractV2.at(ADDR). It displays abi, bytecode and everything","metadata":{"transformedAt":"2026-08-18T18:33:36.133Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":37,"estimatedTokens":316}}276{"id":"stack-75229509","source":"stackoverflow","questionId":75229509,"title":"Is it possible in solidity to check if a contract has specific function before calling it and not revert or avoid revert 0x0dfe1681","tags":["ethereum","solidity","smartcontracts","uniswap"],"text":"Title: Is it possible in solidity to check if a contract has specific function before calling it and not revert or avoid revert 0x0dfe1681\nTags: ethereum, solidity, smartcontracts, uniswap\nSource: Stack Overflow\n\nQuestion:\nI am implementing a token that takes fees on buy/sell but not on transfer. I rely on checking the 'from' and 'to' for being uniswap pairs (V2 or V3) to detect it as a buy/sell transaction.\nFor V2, it's fairly simply as I can use factory function to get the pair address. But for V3 pools, there are more combinations and more fees may be added in the future. So I want to programmatically check if the 'from' or 'to' address has a 'token0' funtion using address.staticcall().\n\nThe problem is staticcall() just fails with revert if the 'token0' function does not exists, any suggestions would be greatly appreciated. Anyway to help detect that address is a pair/pool without reverting would work.\n\nHere is the code I am using (from github) - this code is calling symbol() function\n\nThis call may revert if the function called is not existing in the contract\nHere I am calling symbol(), but potentially can call token0() or any other function\n\n```\nfunction _isUniswapV2Pair(address target) internal view returns (bool) {\n address token0;\n address token1;\n\n string memory targetSymbol = _callAndParseStringReturn(\n target,\n hex\"95d89b41\" // symbol()\n );\n\n if (bytes(targetSymbol).length == 0) {\n return false;\n }\n\n if (_compare(targetSymbol, \"UNI-V2\")) {\n IUniswapV2Pair pairContract = IUniswapV2Pair(target);\n\n try pairContract.token0() returns (address _token0) {\n token0 = _token0;\n } catch Error(string memory) {\n return false;\n } catch (bytes memory) {\n return false;\n }\n\n try pairContract.token1() returns (address _token1) {\n token1 = _token1;\n } catch Error(string memory) {\n return false;\n } catch (bytes memory) {\n return false;\n }\n } else {\n return false;\n }\n\n return target == _dexFactoryV2.getPair(token0, token1); }\n\n function _callAndParseStringReturn(address token, bytes4 selector)\n internal\n view\n returns (string memory)\n {\n (bool success, bytes memory data) = token.staticcall(\n abi.encodeWithSelector(selector)\n );\n\n // if not implemented, or returns empty data, return empty string\n if (!success || data.length == 0) {\n return \"\";\n }\n\n // bytes32 data always has length 32\n if (data.length == 32) {\n bytes32 decoded = abi.decode(data, (bytes32));\n return _bytes32ToString(decoded);\n } else if (data.length > 64) {\n return abi.decode(data, (string));\n }\n return \"\"; }\n \n function _bytes32ToString(bytes32 x) internal pure returns (string memory) {\n bytes memory bytesString = new bytes(32);\n uint256 charCount = 0;\n for (uint256 j = 0; j I have studied the solidity documentation and explored using assembly functions to detect contract name, but looks like that's not possible.\n\nAlso tried several approaches to avoid revert from staticcall if the called function is not existing. There are several contracts that get passed to transfer in case of uniswap swaps - it could be SwapRouter, or NFPosManager or custom tokens or any other contract.\n\nFYI I do check if the address is a contract and not a wallet address before making this above call.\n\n========================================\n\nCode:\n```text\nfunction _isUniswapV2Pair(address target) internal view returns (bool) {\n       address token0;\n       address token1;\n\n       string memory targetSymbol = _callAndParseStringReturn(\n           target,\n           hex\"95d89b41\" // symbol()\n       );\n\n       if (bytes(targetSymbol).length == 0) {\n           return false;\n       }\n\n       if (_compare(targetSymbol, \"UNI-V2\")) {\n           IUniswapV2Pair pairContract = IUniswapV2Pair(target);\n\n           try pairContract.token0() returns (address _token0) {\n               token0 = _token0;\n           } catch Error(string memory) {\n               return false;\n           } catch (bytes memory) {\n               return false;\n           }\n\n           try pairContract.token1() returns (address _token1) {\n               token1 = _token1;\n           } catch Error(string memory) {\n               return false;\n           } catch (bytes memory) {\n               return false;\n           }\n       } else {\n           return false;\n       }\n\n       return target == _dexFactoryV2.getPair(token0, token1);    }\n\n    function _callAndParseStringReturn(address token, bytes4 selector)\n       internal\n       view\n       returns (string memory)\n      {\n       (bool success, bytes memory data) = token.staticcall(\n           abi.encodeWithSelector(selector)\n       );\n\n       // if not implemented, or returns empty data, return empty string\n       if (!success || data.length == 0) {\n           return \"\";\n       }\n\n       // bytes32 data always has length 32\n       if (data.length == 32) {\n           bytes32 decoded = abi.decode(data, (bytes32));\n           return _bytes32ToString(decoded);\n       } else if (data.length > 64) {\n           return abi.decode(data, (string));\n       }\n       return \"\";    }\n   \n    function _bytes32ToString(bytes32 x) internal pure returns (string memory) {\n       bytes memory bytesString = new bytes(32);\n       uint256 charCount = 0;\n       for (uint256 j = 0; j < 32; j++) {\n           bytes1 char = x[j];\n           if (char != 0) {\n               bytesString[charCount] = char;\n               charCount++;\n           }\n       }\n       bytes memory bytesStringTrimmed = new bytes(charCount);\n       for (uint256 j = 0; j < charCount; j++) {\n           bytesStringTrimmed[j] = bytesString[j];\n       }\n       return string(bytesStringTrimmed);    }\n```\n\n```text\nfallback()\n```\n\n```text\ntoken0()\n```\n\n```text\ntoken1()\n```\n\n```text\ntry\n```\n\n```text\ncatch\n```\n\n========================================\n\nComments:\n- Thanks, Petr - I did look into the answer you referenced. The limitation of that solution is - it works well for UniswapV2 and I use a similar approach. With UniswapV3 though, there are multiple fees and a pool can be created for each combination. Also UniswapV3 allows access to pool and not pair, so I presume there could be multiple pools for the same pair. I need to be able to check dynamically and need some code that does not revert if it's not a pool or pair but still a contract\n- Update the question with complete code for pair check for V2 - I have similar for V3","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":191,"estimatedTokens":1580}}277{"id":"stack-47911527","source":"stackoverflow","questionId":47911527,"title":"msg.sender is different in internal call","tags":["solidity","truffle"],"text":"Title: msg.sender is different in internal call\nTags: solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nI'm new to `solidity` & `ethereum` development. \n\nLet's say I have the following structure ( mine is a more complicated, but I think this will work for now ) :\n\n```\ncontract A {\n address public owner;\n function A() public {\n owner = msg.sender;\n }\n\n isOwner(address _addr) {\n return _addr == owner;\n }\n}\n\ncontract Base is A { \n ....\n someMethod(address _addr) {\n require(isOwner(msg.sender))\n\n // do something with _addr\n }\n}\n\ncontract SomeContract{\n Base public baseContract;\n function SomeContract(Base _base) { \n baseContract = _base\n }\n callingMethod() {\n ....\n require(baseContract.someMethod(msg.sender))\n ....\n }\n}\n```\n\nBy calling `callingMethod` from `truffle`, it fails because of `require(isOwner(msg.sender))`. I was able to see that `msg.sender` is different from owner using an `Event` and printing its result to console, but I don't understand why.\n\nAnyone knows why is this happening? Thanks !\n\n========================================\n\nTop Answer:\n`msg.sender` might represent either user address or another contract address.\n\nUsually it is an user address, however when inside your contract this contract calls another contract `msg.sender` would be an address of the contract caller – not an address which was defined during the initial call, e.g. `contract.connect()`.\n\nIt might be important during `ERC721` token approve call: we could approve one address, but eventually authorized `ERC721` token function would be called by deployed contract which would end up with revered tx as this address has not been approved.\n\n========================================\n\nCode:\n```text\ncontract A {\n  address public owner;\n  function A() public {\n      owner = msg.sender;\n  }\n\n  isOwner(address _addr) {\n      return _addr == owner;\n  }\n}\n\ncontract Base is A { \n     ....\n     someMethod(address _addr) {\n        require(isOwner(msg.sender))\n\n        // do something with _addr\n     }\n}\n\ncontract SomeContract{\n     Base public baseContract;\n     function SomeContract(Base _base) { \n        baseContract = _base\n     }\n     callingMethod() {\n        ....\n        require(baseContract.someMethod(msg.sender))\n        ....\n     }\n}\n```\n\n```text\nsolidity\n```\n\n```text\nethereum\n```\n\n```text\ncallingMethod\n```\n\n```text\ntruffle\n```\n\n```text\nrequire(isOwner(msg.sender))\n```\n\n```text\nmsg.sender\n```\n\n```text\nEvent\n```\n\n```text\nmsg.sender\n```\n\n```text\nmsg.sender\n```\n\n```text\ncontract.connect(<signer>)\n```\n\n```text\nERC721\n```\n\n```text\nERC721\n```\n\n========================================\n\nComments:\n- Possible duplicate of Questions about contract calling another contract","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":145,"estimatedTokens":671}}278{"id":"stack-72603836","source":"stackoverflow","questionId":72603836,"title":"erc20 claim token transfer function doesn't work","tags":["javascript","ethereum","solidity","erc20","openzeppelin"],"text":"Title: erc20 claim token transfer function doesn't work\nTags: javascript, ethereum, solidity, erc20, openzeppelin\nSource: Stack Overflow\n\nQuestion:\nI have this contract and trying to call the claimFreeToken function. Contract already doesn't have enough tokens but the function doesn't return an error and also token doesn't receive. Where did I overlook it?\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\ncontract TestToken is ERC20 {\n constructor(uint256 initialSupply) ERC20(\"Test Token\", \"TET\") {\n _mint(msg.sender, initialSupply * (10**decimals()));\n }\n\n function claimFreeToken() public payable {\n transfer(msg.sender, 1000 * (10**decimals()));\n }\n}\n```\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\ncontract TestToken is ERC20 {\n    constructor(uint256 initialSupply) ERC20(\"Test Token\", \"TET\") {\n        _mint(msg.sender, initialSupply * (10**decimals()));\n    }\n\n    function claimFreeToken() public payable {\n        transfer(msg.sender, 1000 * (10**decimals()));\n    }\n}\n```\n\n```text\nfunction claimFreeToken() public payable {\n    _transfer(address(this), msg.sender, 1000 * (10**decimals()));\n}\n```\n\n```text\ntransfer\n```\n\n```text\nmsg.sender\n```\n\n```text\nmsg.sender\n```\n\n```text\nmsg.sender\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":65,"estimatedTokens":351}}279{"id":"stack-73296233","source":"stackoverflow","questionId":73296233,"title":"Switch Error, Expected Primary Expression","tags":["switch-statement","solidity"],"text":"Title: Switch Error, Expected Primary Expression\nTags: switch-statement, solidity\nSource: Stack Overflow\n\nQuestion:\nTrying to use a switch-case statement in Solidity and getting an 'expected primary expression' error.\n\n```\nfunction foo(uint8 version) public {\n switch version\n case 1 {\n \n }\n default {\n revert();\n }\n}\n```\n\nMy exact error is\n\n```\nError: Expected primary expression.\n --> project/contracts/MyContract.sol:149:9:\n |\n 149 | switch version\n | ^^^^^^\n```\n\nCompiler version 8.11\n\n========================================\n\nCode:\n```text\nfunction foo(uint8 version) public {\n    switch version\n    case 1 {\n        <do something>\n    }\n    default {\n        revert();\n    }\n}\n```\n\n```text\nError: Expected primary expression.\n      --> project/contracts/MyContract.sol:149:9:\n       |\n   149 |         switch version\n       |         ^^^^^^\n```\n\n```text\nfunction foo(uint8 version) public {\n    if (version == 1) {\n        // do something\n    } else if (version == 2) {\n        // do something else\n    } else {\n        revert();\n    }\n}\n```\n\n```text\nfunction fooYul(uint8 version) public {\n    assembly {\n        switch version\n        case 1 {\n            // do something\n        }\n        case 2 {\n            // do something else\n        }\n        default {\n            revert(0, 0)\n        }\n    }\n}\n```\n\n```text\nswitch\n```\n\n```text\nif\n```\n\n```text\nelse if\n```\n\n```text\nassembly\n```\n\n```text\nswitch\n```\n\n========================================\n\nComments:\n- Thanks! Was looking at docs for switch syntax used in assembly blocks not realizing Solidity didn't have switch syntax.","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":107,"estimatedTokens":398}}280{"id":"stack-71725588","source":"stackoverflow","questionId":71725588,"title":"How to clear and reset Mapping of Array in solidity","tags":["ethereum","solidity"],"text":"Title: How to clear and reset Mapping of Array in solidity\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nBelow is how I do the record into the mapping array. How can I create a clear|removeall function that clears or reset all the records back to default which is empty?\n\n```\naddress payable[] public players;\n mapping(address => uint256[]) playerTicket;\n \n \n function playersRecord() public view returns(uint256[] memory){\n return playerTicket[msg.sender];\n }\n```\n\nI managed with the below function to clear one by one but not sure how to clear all\n\n```\nfunction remove(address _addr) public {\n // Reset the value to the default value.\n delete playerTicket[_addr];\n}\n```\n\n========================================\n\nTop Answer:\nuse delete keyword in latest version.\nworking example - refer this repo\n\n```\ndelete players;\n```\n\n========================================\n\nCode:\n```text\naddress payable[] public players;\n    mapping(address => uint256[])  playerTicket;\n        \n        \n    function playersRecord() public view returns(uint256[] memory){\n                return playerTicket[msg.sender];\n    }\n```\n\n```text\nfunction remove(address _addr) public {\n    // Reset the value to the default value.\n    delete playerTicket[_addr];\n}\n```\n\n```text\nremove()\n```\n\n```js\ndelete players;\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":63,"estimatedTokens":326}}281{"id":"stack-70005355","source":"stackoverflow","questionId":70005355,"title":"MekaVerse NFT smart contract is using ECDSA, but I don't understand how it works","tags":["solidity","signature","smartcontracts","ecdsa","nft"],"text":"Title: MekaVerse NFT smart contract is using ECDSA, but I don't understand how it works\nTags: solidity, signature, smartcontracts, ecdsa, nft\nSource: Stack Overflow\n\nQuestion:\nIn the smart contract of MekaVerse I can see these lines to enable a whitelisting, but I don't understand the theory behind it and how I can use it.\n\n```\nfunction mint(uint256[] memory _tokensId, uint256 _timestamp, bytes memory _signature) public payable saleIsOpen {\n\n uint256 total = totalToken();\n require(_tokensId.length = price(_tokensId.length), \"Value below price\");\n\n address wallet = _msgSender();\n\n address signerOwner = signatureWallet(wallet,_tokensId,_timestamp,_signature);\n require(signerOwner == owner(), \"Not authorized to mint\");\n\n require(block.timestamp >= _timestamp - 30, \"Out of time\");\n\n for(uint8 i = 0; i 0 && _tokensId[i] The interesting part that I don't understand is here :\n\n```\naddress signerOwner = signatureWallet(wallet,_tokensId,_timestamp,_signature);\nrequire(signerOwner == owner(), \"Not authorized to mint\")\n```\n\nAnd here :\n\n```\nfunction signatureWallet(address wallet, uint256[] memory _tokensId, uint256 _timestamp, bytes memory _signature) public view returns (address){\n\nreturn ECDSA.recover(keccak256(abi.encode(wallet, _tokensId, _timestamp)), _signature);\n```\n\n}\n\nThank you for your help,\nBen\n\n========================================\n\nCode:\n```text\nfunction mint(uint256[] memory _tokensId, uint256 _timestamp, bytes memory _signature) public payable saleIsOpen {\n\n    uint256 total = totalToken();\n    require(_tokensId.length <= 2, \"Max limit\");\n    require(total + _tokensId.length <= MAX_ELEMENTS, \"Max limit\");\n    require(msg.value >= price(_tokensId.length), \"Value below price\");\n\n    address wallet = _msgSender();\n\n    address signerOwner = signatureWallet(wallet,_tokensId,_timestamp,_signature);\n    require(signerOwner == owner(), \"Not authorized to mint\");\n\n    require(block.timestamp >= _timestamp - 30, \"Out of time\");\n\n    for(uint8 i = 0; i < _tokensId.length; i++){\n        require(rawOwnerOf(_tokensId[i]) == address(0) && _tokensId[i] > 0 && _tokensId[i] <= MAX_ELEMENTS, \"Token already minted\");\n        _mintAnElement(wallet, _tokensId[i]);\n    }\n\n}\n\nfunction signatureWallet(address wallet, uint256[] memory _tokensId, uint256 _timestamp, bytes memory _signature) public view returns (address){\n\n    return ECDSA.recover(keccak256(abi.encode(wallet, _tokensId, _timestamp)), _signature);\n\n}\n```\n\n```text\naddress signerOwner = signatureWallet(wallet,_tokensId,_timestamp,_signature);\nrequire(signerOwner == owner(), \"Not authorized to mint\")\n```\n\n```text\nfunction signatureWallet(address wallet, uint256[] memory _tokensId, uint256 _timestamp, bytes memory _signature) public view returns (address){\n\nreturn ECDSA.recover(keccak256(abi.encode(wallet, _tokensId, _timestamp)), _signature);\n```\n\n```text\nrecover()\n```\n\n```text\nrecover()\n```\n\n```text\nbytes32\n```\n\n```text\nhash\n```\n\n```text\nbytes\n```\n\n```text\nsignature\n```\n\n```text\nhash\n```\n\n```text\nsignature\n```\n\n```text\n0x0\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":118,"estimatedTokens":757}}282{"id":"stack-71450252","source":"stackoverflow","questionId":71450252,"title":"How do I check empty string in solidity?","tags":["string","blockchain","ethereum","solidity","smartcontracts"],"text":"Title: How do I check empty string in solidity?\nTags: string, blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI'm learning solidity. I want to check if a memory string variable is a null, empty, or whitespaces.\nI understand I have to check it like this:\n\n```\nbytes(_content).length > 0\n```\n\nHowever, this does now cover empty whitespace. What would be the best way to check for empty whitespace?\nOr do you suggest that this check does not belong in s\n\n========================================\n\nCode:\n```text\nbytes(_content).length > 0\n```\n\n```text\nbytes test = '0xabcd'\n\ntest[2:5];  # 'abc'\n```\n\n```text\nbytes whitespaces='0x20202020202020'\n```\n\n```text\n0x\n```\n\n```text\n0x20\n```\n\n```text\n0x2020\n```\n\n========================================\n\nComments:\n- This is definitely a solution. Sounds like a good one. I will do this. But I do wonder if it's the most optimal solution in terms of performance and if its the cleanest solution in tems of code. But it sounds like its the only solution. Thanks @Yilmaz.\n- working with strings pains the neck in solidity.","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":49,"estimatedTokens":273}}283{"id":"stack-70225007","source":"stackoverflow","questionId":70225007,"title":"Contract \"Coin\" should be marked as abstract","tags":["solidity","smartcontracts"],"text":"Title: Contract \"Coin\" should be marked as abstract\nTags: solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\ni want to create a token on ERC-20 network.\n\ni want to inheritance from interface in my contract .\n\nwhen i inheritance form interface it show me this error :\n\nContract \"CpayCoin\" should be marked as abstract.\n\n`solc` version in truffle :\n\n```\ncompilers: {\nsolc: {\n version: \"0.8.10\", // Fetch exact version from solc-bin (default: truffle's version)\n docker: false, // Use \"0.5.1\" you've installed locally with docker (default: false)\n settings: { // See the solidity docs for advice about optimization and evmVersion\n optimizer: {\n enabled: false,\n runs: 200\n },\n evmVersion: \"byzantium\"\n }\n}\n```\n\n},\n\n**whats the problem ? how can i solve this problem ???**\n\nthis is my interface :\n\n```\n// SPDX-License-Identifier: MIT\npragma solidity >=0.4.22 contract :\n\n```\n// SPDX-License-Identifier: MIT\n```\n\npragma solidity >=0.4.22 uint256) private _balances;\n mapping(address => mapping(address => uint256)) private _allowances;\n\n //Unit256\n uint256 private _totalSupply;\n uint256 private _tokenPrice;\n\n // String\n string private _name;\n string private _symbol;\n\n //Address\n address _minter;\n\n constructor(\n string memory name_,\n string memory symbol_,\n uint256 totalSupply_\n ) {\n _minter = msg.sender;\n _balances[_minter] = _totalSupply;\n _tokenPrice = 10**15 wei;\n _name = name_;\n _symbol = symbol_;\n _totalSupply = totalSupply_;\n }\n\n // Modifier\n modifier onlyMinter() {\n require(msg.sender == _minter, \"Only Minter can Mint!\");\n _;\n }\n\n modifier enoughBalance(address adr, uint256 amount) {\n require(_balances[adr] >= amount, \"Not enough Balance!\");\n _;\n }\n\n modifier enoughValue(uint256 amount) {\n require(msg.value == amount * _tokenPrice, \"Not enough Value!\");\n _;\n }\n\n modifier checkZeroAddress(address adr) {\n require(adr != address(0), \"ERC20: mint to the zero address\");\n _;\n }\n\n // Functions\n function name() public view virtual returns (string memory) {\n return _name;\n }\n\n function symbol() public view virtual returns (string memory) {\n return _symbol;\n }\n\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n function balanceOf(address adr)\n public\n view\n virtual\n override\n returns (uint256)\n {\n return _balances[adr];\n }\n\n function _mint(address account, uint256 amount)\n internal\n virtual\n onlyMinter\n checkZeroAddress(account)\n {\n _totalSupply += amount;\n _balances[account] += amount;\n\n emit Transfer(address(0), account, amount);\n }\n\n function _burn(address account, uint256 amount)\n internal\n virtual\n onlyMinter\n checkZeroAddress(account)\n {\n uint256 accountBalance = _balances[account];\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n\n _totalSupply += amount;\n emit Transfer(account, address(0), amount);\n }\n\n function _transfer(\n address sender,\n address recipient,\n uint256 amount\n ) internal virtual {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n uint256 senderBalance = _balances[sender];\n require(\n senderBalance >= amount,\n \"ERC20: transfer amount exceeds balance\"\n );\n\n unchecked {\n _balances[sender] = senderBalance - amount;\n }\n\n _balances[recipient] += amount;\n\n emit Transfer(sender, recipient, amount);\n }\n\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n}\n```\n\n========================================\n\nTop Answer:\nAs Petr Hejda stated in the previous answer: you need to implement all declared functions to have a normal contract and not an abstract one.\n\nFor the people coming to this question when getting `Contract should be mark as abstract` in a local environment such as truffle or hardhat, you can use the online compiler Remix to find out which functions are missing implementation. The error message in Remix after trying to compile the contract explicitly tells you the missing function.\n\n========================================\n\nCode:\n```text\ncompilers: {\nsolc: {\n  version: \"0.8.10\",    // Fetch exact version from solc-bin (default: truffle's version)\n  docker: false,        // Use \"0.5.1\" you've installed locally with docker (default: false)\n  settings: {          // See the solidity docs for advice about optimization and evmVersion\n    optimizer: {\n      enabled: false,\n      runs: 200\n    },\n    evmVersion: \"byzantium\"\n  }\n}\n```\n\n```text\n// SPDX-License-Identifier: MIT\npragma solidity >=0.4.22 <0.9.0;\n\ninterface IERC20 {\n    function decimals() external view returns (uint8);\n\n    function totalSupply() external view returns (uint256);\n\n    function balanceOf(address account) external view returns (uint256);\n\n    function transfer(address recipient, uint256 amount)\n        external\n        returns (bool);\n\n    function allowance(address owner, address spender)\n        external\n        view\n        returns (uint256);\n\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    function transferFrom(\n        address sender,\n        address recipient,\n        uint256 amount\n    ) external returns (bool);\n\n    event Transfer(address indexed from, address indexed to, uint256 value);\n    event Approval(\n        address indexed owner,\n        address indexed spender,\n        uint256 value\n    );\n}\n```\n\n```text\n// SPDX-License-Identifier: MIT\n```\n\n```text\nimport \"./IERC-20.sol\";\n\ncontract CpayCoin is IERC20 {\n    //mapping\n    mapping(address => uint256) private _balances;\n    mapping(address => mapping(address => uint256)) private _allowances;\n\n    //Unit256\n    uint256 private _totalSupply;\n    uint256 private _tokenPrice;\n\n    // String\n    string private _name;\n    string private _symbol;\n\n    //Address\n    address _minter;\n\n    constructor(\n        string memory name_,\n        string memory symbol_,\n        uint256 totalSupply_\n    ) {\n        _minter = msg.sender;\n        _balances[_minter] = _totalSupply;\n        _tokenPrice = 10**15 wei;\n        _name = name_;\n        _symbol = symbol_;\n        _totalSupply = totalSupply_;\n    }\n\n    // Modifier\n    modifier onlyMinter() {\n        require(msg.sender == _minter, \"Only Minter can Mint!\");\n        _;\n    }\n\n    modifier enoughBalance(address adr, uint256 amount) {\n        require(_balances[adr] >= amount, \"Not enough Balance!\");\n        _;\n    }\n\n    modifier enoughValue(uint256 amount) {\n        require(msg.value == amount * _tokenPrice, \"Not enough Value!\");\n        _;\n    }\n\n    modifier checkZeroAddress(address adr) {\n        require(adr != address(0), \"ERC20: mint to the zero address\");\n        _;\n    }\n\n    // Functions\n    function name() public view virtual returns (string memory) {\n        return _name;\n    }\n\n    function symbol() public view virtual returns (string memory) {\n        return _symbol;\n    }\n\n    function totalSupply() public view virtual override returns (uint256) {\n        return _totalSupply;\n    }\n\n    function balanceOf(address adr)\n        public\n        view\n        virtual\n        override\n        returns (uint256)\n    {\n        return _balances[adr];\n    }\n\n    function _mint(address account, uint256 amount)\n        internal\n        virtual\n        onlyMinter\n        checkZeroAddress(account)\n    {\n        _totalSupply += amount;\n        _balances[account] += amount;\n\n        emit Transfer(address(0), account, amount);\n    }\n\n    function _burn(address account, uint256 amount)\n        internal\n        virtual\n        onlyMinter\n        checkZeroAddress(account)\n    {\n        uint256 accountBalance = _balances[account];\n        unchecked {\n            _balances[account] = accountBalance - amount;\n        }\n\n        _totalSupply += amount;\n        emit Transfer(account, address(0), amount);\n    }\n\n    function _transfer(\n        address sender,\n        address recipient,\n        uint256 amount\n    ) internal virtual {\n        require(sender != address(0), \"ERC20: transfer from the zero address\");\n        require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n        uint256 senderBalance = _balances[sender];\n        require(\n            senderBalance >= amount,\n            \"ERC20: transfer amount exceeds balance\"\n        );\n\n        unchecked {\n            _balances[sender] = senderBalance - amount;\n        }\n\n        _balances[recipient] += amount;\n\n        emit Transfer(sender, recipient, amount);\n    }\n\n    function _approve(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n}\n```\n\n```text\nsolc\n```\n\n```text\nis\n```\n\n```text\nCpayCoin is IERC20\n```\n\n```text\nCpayCoin\n```\n\n```text\nIERC20\n```\n\n```text\nIERC20\n```\n\n```text\ndecimals()\n```\n\n```text\ntransfer()\n```\n\n```text\nCpayCoin\n```\n\n```text\nCpayCoin\n```\n\n```text\nCpayCoin\n```\n\n```text\nIERC20\n```\n\n```text\n_transfer()\n```\n\n```text\ntransfer()\n```\n\n```text\n_transfer()\n```\n\n```text\nContract <ContractName> should be mark as abstract\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":448,"estimatedTokens":2348}}284{"id":"stack-68173194","source":"stackoverflow","questionId":68173194,"title":"Storage compatibility: Solidity upgradable smart contract using \"proxy\" design pattern and changing the mapping type","tags":["ethereum","solidity"],"text":"Title: Storage compatibility: Solidity upgradable smart contract using \"proxy\" design pattern and changing the mapping type\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nAnyone used the \"proxy\" pattern to write upgradable smart contracts?\nI am planning to upgrade/extend my old smart contract, originally, my code looks like this:\n\n```\nmapping(address => uint256) balance;\n```\n\nI am planning to write it like this:\n\n```\nstruct PackedBalance {\n uint256 balance;\n uint256 locked_balance; // to support a new feature.\n}\nmapping(address => PackedBalance) balance;\n```\n\nMy concern is if the \"storage\" is compatible to the \"old version smart contract\".\n\nI just read the \"Layout of State Variables in Storage\". As I understand it, it is compatible. But I am a newbie, so I would like to seek help from some experts.\n\n\"compatible\" means: I can still read correct \"balance\" of the existing storage slots. And I can write \"locked_balance\" without breaking anything(like overwritten).\n\n========================================\n\nCode:\n```text\nmapping(address => uint256)  balance;\n```\n\n```text\nstruct PackedBalance {\n    uint256 balance;\n    uint256 locked_balance;    // to support a new feature.\n}\nmapping(address => PackedBalance) balance;\n```\n\n```text\npragma solidity ^0.8;\n\ncontract MyContract {\n    mapping(address => uint256) balance;\n    \n    function setBalanceForAddress(address _address, uint256 _balance) external {\n        balance[_address] = _balance;\n    }\n}\n```\n\n```text\npragma solidity ^0.8;\n\ncontract MyContract {\n    struct PackedBalance {\n        uint256 balance;\n        uint256 locked_balance;\n    }\n\n    mapping(address => PackedBalance) balance;\n    \n    function setBalanceForAddress(address _address, uint256 _balance, uint256 _lockedBalance) external {\n        balance[_address] = PackedBalance(_balance, _lockedBalance);\n    }\n}\n```\n\n```text\n0x4fa1007300000000000000000000000012312312312312312312312312312312312312310000000000000000000000000000000000000000000000000000000000000064\n```\n\n```text\n0x6f7223d9000000000000000000000000123123123123123123123123123123123123123100000000000000000000000000000000000000000000000000000000000000640000000000000000000000000000000000000000000000000000000000000064\n```\n\n```text\nuint256\n```\n\n```text\nstruct\n```\n\n```text\naddress\n```\n\n```text\n0x1231231231231231231231231231231231231231\n```\n\n```text\nuint256\n```\n\n```text\n0xf100689cc6bb188feb3c0ef4658bee6e8042e58e79daebcd84870d7f336a8422\n```\n\n```text\nstruct\n```\n\n```text\n0xf100689cc6bb188feb3c0ef4658bee6e8042e58e79daebcd84870d7f336a8422\n```\n\n```text\n0xf100689cc6bb188feb3c0ef4658bee6e8042e58e79daebcd84870d7f336a8423\n```\n\n========================================\n\nComments:\n- However, `hardhat` would give an error: \"Error: New storage layout is incompatible\".\n- @AndyJiang It's a check used by the openzeppelin-upgrades package. I's not related to Hardhat or EVM in general. Here's an open issue on their GitHub related to the error message - github.com/OpenZeppelin/openzeppelin-upgrades/issues/73 ... Possible solutions: 1) Comment out the check in your local copy of the `openzeppelin-upgrades` package. 2) Perform the proxy upgrade without this package. 3) Wait for OpenZeppelin to allow the change in the package. 4) Submit a pull request that allows suppressing the error, ...","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":121,"estimatedTokens":823}}285{"id":"stack-69408191","source":"stackoverflow","questionId":69408191,"title":"ERC-721 Smart contract is minting 2 NFTs at a time","tags":["ethereum","solidity","nft"],"text":"Title: ERC-721 Smart contract is minting 2 NFTs at a time\nTags: ethereum, solidity, nft\nSource: Stack Overflow\n\nQuestion:\nI have this smart contract from Hash Lip's github that, from what I can tell should be minting 1 at a time, but is instead minting 2 every time. Code as follows:\n\nSetup code:\n\n```\n// SPDX-License-Identifier: GPL-3.0\n\n// Created by HashLips\n// The Nerdy Coder Clones\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\ncontract TestBoxes is ERC721Enumerable, Ownable {\n using Strings for uint256;\n\n string public baseURI;\n string public baseExtension = \".json\";\n uint256 public cost = 0.01 ether;\n uint256 public maxSupply = 3; //there should only be 3 minted (I have 3 image files to test)\n uint256 public maxMintAmount = 3;\n bool public paused = false;\n mapping(address => bool) public whitelisted;\n```\n\nAnd then the part where the contract is minting is as follows. as you can see above, I have set the max as 3, and in the next part, after the constructor executes, it mints 1 NFT for the owner.\n\n```\nconstructor(\n string memory _name,\n string memory _symbol,\n string memory _initBaseURI\n ) ERC721(_name, _symbol) {\n setBaseURI(_initBaseURI);\n mint(msg.sender, 1); //should mint 1 at deployment but mints 2...\n }\n\n // internal\n function _baseURI() internal view virtual override returns (string memory) {\n return baseURI;\n }\n\n // public\n function mint(address _to, uint256 _mintAmount) public payable {\n uint256 supply = totalSupply();\n require(!paused);\n require(_mintAmount > 0);\n require(_mintAmount = cost * _mintAmount);\n }\n }\n\n for (uint256 i = 0; i <= _mintAmount; i++) { //start the index at 0\n _safeMint(_to, supply + i);\n }\n }\n```\n\n========================================\n\nTop Answer:\n```\nfor (uint256 i = 1; i The way above works the same way.\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: GPL-3.0\n\n// Created by HashLips\n// The Nerdy Coder Clones\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\ncontract TestBoxes is ERC721Enumerable, Ownable {\n  using Strings for uint256;\n\n  string public baseURI;\n  string public baseExtension = \".json\";\n  uint256 public cost = 0.01 ether;\n  uint256 public maxSupply = 3;  //there should only be 3 minted (I have 3 image files to test)\n  uint256 public maxMintAmount = 3;\n  bool public paused = false;\n  mapping(address => bool) public whitelisted;\n```\n\n```text\nconstructor(\n    string memory _name,\n    string memory _symbol,\n    string memory _initBaseURI\n  ) ERC721(_name, _symbol) {\n    setBaseURI(_initBaseURI);\n    mint(msg.sender, 1); //should mint 1 at deployment but mints 2...\n  }\n\n  // internal\n  function _baseURI() internal view virtual override returns (string memory) {\n    return baseURI;\n  }\n\n  // public\n  function mint(address _to, uint256 _mintAmount) public payable {\n    uint256 supply = totalSupply();\n    require(!paused);\n    require(_mintAmount > 0);\n    require(_mintAmount <= maxMintAmount);\n    require(supply + _mintAmount <= maxSupply);\n\n    if (msg.sender != owner()) {\n        if(whitelisted[msg.sender] != true) {\n          require(msg.value >= cost * _mintAmount);\n        }\n    }\n\n    for (uint256 i = 0; i <= _mintAmount; i++) { //start the index at 0\n      _safeMint(_to, supply + i);\n    }\n  }\n```\n\n```text\nfor (uint256 i = 0; i <= _mintAmount; i++)\n```\n\n```text\nfor\n```\n\n```text\nmint()\n```\n\n```text\n_mintAmount\n```\n\n```text\n1\n```\n\n```text\ni\n```\n\n```text\n0\n```\n\n```text\n_safeMint()\n```\n\n```text\ni\n```\n\n```text\n1\n```\n\n```text\n_safeMint()\n```\n\n```text\ni < _mintAmoun\n```\n\n```text\nmintAmount\n```\n\n```text\nfor (uint256 i = 1; i <= _mintAmount; i++)\n```\n\n========================================\n\nComments:\n- I don't want to say anything bad about hashlips but you should probably find a different source for your smart contract code.","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":191,"estimatedTokens":1000}}286{"id":"stack-66741987","source":"stackoverflow","questionId":66741987,"title":"transaction could not be decoded: could not recover secp256k1 key: calculated Rx is larger than curve P","tags":["solidity","truffle"],"text":"Title: transaction could not be decoded: could not recover secp256k1 key: calculated Rx is larger than curve P\nTags: solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nI am getting following error while trying to compile solidity contract:\n\n```\ntransaction could not be decoded: could not recover secp256k1 key: calculated Rx is larger than curve P\n```\n\n========================================\n\nTop Answer:\nSame issue here, I was able to solve it following this answer here\n\nYou need to downgrade `@truffle/hdwallet-provider` to version `1.0.40`\n\n========================================\n\nCode:\n```text\ntransaction could not be decoded: could not recover secp256k1 key: calculated Rx is larger than curve P\n```\n\n```text\n\"@truffle/hdwallet-provider\": \"1.2.3\",\n```\n\n```text\n@truffle/hdwallet-provider\n```\n\n```text\n1.0.40\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":36,"estimatedTokens":206}}287{"id":"stack-59379024","source":"stackoverflow","questionId":59379024,"title":"Error: Returned values aren't valid when trying to call function","tags":["javascript","solidity","web3js","truffle","ganache"],"text":"Title: Error: Returned values aren't valid when trying to call function\nTags: javascript, solidity, web3js, truffle, ganache\nSource: Stack Overflow\n\nQuestion:\nI created a NameContracts as described here: https://bitsofco.de/calling-smart-contract-functions-using-web3-js-call-vs-send/\n\nI compiled & migrated it with truffle and started the ganache-cli. Then I tried to call the function getName with web3, but always get the error:\n\nError: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.\n\nI'm not sure what that means or what I did wrong. I already searched the web, but none of the suggested solutions worked for me. Here's my code:\n\n```\nconst Web3 = require('web3');\nconst fs = require('fs');\n\nconst rpcURL = \"http://localhost:8545\";\nconst web3 = new Web3(rpcURL);\n\nconst rawData = fs.readFileSync('NameContract.json');\nconst jsonData = JSON.parse(rawData);\nconst abi = jsonData[\"abi\"];\n\nlet accounts;\nlet contract;\nweb3.eth.getAccounts().then(result =>{\n accounts = result;\n web3.eth.getBalance(accounts[0], (err, wei) => {\n balance = web3.utils.fromWei(wei, 'ether')\n console.log(\"Balance of accounts[0]: \" + balance); // works as expected\n })\n contract = new web3.eth.Contract(abi, accounts[0]);\n console.log(contract.methods); // works as expected\n console.log(contract.address); // prints undefined\n contract.methods.getName().call((result) => {console.log(result)}); // throws error\n})\n```\n\n========================================\n\nCode:\n```text\nconst Web3 = require('web3');\nconst fs = require('fs');\n\nconst rpcURL = \"http://localhost:8545\";\nconst web3 = new Web3(rpcURL);\n\nconst rawData = fs.readFileSync('NameContract.json');\nconst jsonData = JSON.parse(rawData);\nconst abi = jsonData[\"abi\"];\n\nlet accounts;\nlet contract;\nweb3.eth.getAccounts().then(result =>{\n  accounts = result;\n  web3.eth.getBalance(accounts[0], (err, wei) => {\n    balance = web3.utils.fromWei(wei, 'ether')\n    console.log(\"Balance of accounts[0]: \" + balance); // works as expected\n  })\n  contract = new web3.eth.Contract(abi, accounts[0]);\n  console.log(contract.methods); // works as expected\n  console.log(contract.address); // prints undefined\n  contract.methods.getName().call((result) => {console.log(result)}); // throws error\n})\n```\n\n```js\nlet contract_address = \"0x12f1a3...\"; // the address of your deployed contract (see the result of $truffle migrate)\ncontract = new web3.eth.Contract(abi, contract_address);\n```\n\n```text\ncontract.methods.getName().call()\n```\n\n```text\n<your_account_name>.getName()\n```\n\n```text\n$ truffle migrate\n```\n\n========================================\n\nComments:\n- Thanks. I don't get the error any more. But still if I try to console log contract.address I get undefined.\n- You can not access it directly. Try `console.log(contract.options.address);` You can find more information in the official documentation.","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":90,"estimatedTokens":764}}288{"id":"stack-58437634","source":"stackoverflow","questionId":58437634,"title":"Solidity - Error: Identifier not found or not unique. Compilation error","tags":["compilation","solidity"],"text":"Title: Solidity - Error: Identifier not found or not unique. Compilation error\nTags: compilation, solidity\nSource: Stack Overflow\n\nQuestion:\nI had tried to compile this code by Compiler version 0.5.12, but I had an exception:\n\nbrowser/Untitled.sol:21:24: DeclarationError: Identifier not found or not unique.\n\nfunction getRoleOf(adress ad) public returns(string txt){\n\n^----^\n\nMy code:\n\n```\npragma solidity >=0.4.22 uint256) private balaces;\n mapping(address => role) private roles;\n enum role{\n Admin,\n Manager,\n User\n }\n \n constructor() public{\n balaces[msg.sender] = 1000;\n roles[msg.sender] = role.Admin;\n }\n \n function getRoleOf(adress ad) public returns(string txt){\n if(roles[ad] == role.User){\n txt = \"User\";\n return;\n }\n if(roles[ad] == role.Manager){\n txt = \"Manager\";\n return;\n }\n if(roles[ad] == role.Admin){\n txt = \"Admin\";\n return;\n }\n return \"Нет такого пользователя\";\n }\n}\n```\n\nWhat is wrong in my code?\n\n========================================\n\nTop Answer:\nThere is a typo in :`function getRoleOf(adress ad)`\n`adress` should be `address`\n\nThe following compiles in Remix using Solidity Compiler 0.4.26\n\n```\npragma solidity >=0.4.22 uint256) private balaces;\n mapping(address => role) private roles;\n enum role{\n Admin,\n Manager,\n User\n }\n\n constructor() public{\n balaces[msg.sender] = 1000;\n roles[msg.sender] = role.Admin;\n }\n\n function getRoleOf(address ad) public returns(string txt){\n if(roles[ad] == role.User){\n txt = \"User\";\n return;\n }\n if(roles[ad] == role.Manager){\n txt = \"Manager\";\n return;\n }\n if(roles[ad] == role.Admin){\n txt = \"Admin\";\n return;\n }\n return \"Нет такого пользователя\";\n }\n}\n```\n\n========================================\n\nCode:\n```text\npragma solidity >=0.4.22 <0.5.13;\ncontract Max{\n    mapping(address => uint256) private balaces;\n    mapping(address => role) private roles;\n    enum role{\n        Admin,\n        Manager,\n        User\n    }\n    \n    constructor() public{\n        balaces[msg.sender] = 1000;\n        roles[msg.sender] = role.Admin;\n    }\n    \n    function getRoleOf(adress ad) public returns(string txt){\n        if(roles[ad] == role.User){\n            txt = \"User\";\n            return;\n        }\n        if(roles[ad] == role.Manager){\n            txt = \"Manager\";\n            return;\n        }\n        if(roles[ad] == role.Admin){\n            txt = \"Admin\";\n            return;\n        }\n        return \"Нет такого пользователя\";\n    }\n}\n```\n\n```text\npragma solidity >=0.4.22 <0.5.13;\ncontract Max{\n    mapping(address => uint256) private balaces;\n    mapping(address => role) private roles;\n    enum role{\n        Admin,\n        Manager,\n        User\n    }\n\n    constructor() public{\n        balaces[msg.sender] = 1000;\n        roles[msg.sender] = role.Admin;\n    }\n\n    function getRoleOf(address ad) public returns(string memory txt){\n        txt = \"Нет такого пользователя\";\n        if(roles[ad] == role.User){\n            txt = \"User\";\n        } else if(roles[ad] == role.Manager){\n            txt = \"Manager\";\n        } else if(roles[ad] == role.Admin){\n            txt = \"Admin\";\n        }\n        return txt;\n    }\n}\n```\n\n```text\npragma solidity >=0.4.22 <0.5.13;\ncontract Max{\n    mapping(address => uint256) private balaces;\n    mapping(address => role) private roles;\n    enum role{\n        Admin,\n        Manager,\n        User\n    }\n\n    constructor() public{\n        balaces[msg.sender] = 1000;\n        roles[msg.sender] = role.Admin;\n    }\n\n    function getRoleOf(address ad) public returns(string txt){\n        if(roles[ad] == role.User){\n            txt = \"User\";\n            return;\n        }\n        if(roles[ad] == role.Manager){\n            txt = \"Manager\";\n            return;\n        }\n        if(roles[ad] == role.Admin){\n            txt = \"Admin\";\n            return;\n        }\n        return \"Нет такого пользователя\";\n    }\n}\n```\n\n```text\nfunction getRoleOf(adress ad)\n```\n\n```text\nadress\n```\n\n```text\naddress\n```\n\n```text\ngetRoleOf(adress ad)\n```\n\n```text\ngetRoleOf(address ad)\n```\n\n```text\naddress\n```\n\n========================================\n\nComments:\n- you should add your code inside a code snippet and add a description","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":218,"estimatedTokens":1030}}289{"id":"stack-57540884","source":"stackoverflow","questionId":57540884,"title":"Warning Regarding extcodehash in Remix for openzeppelin-contracts","tags":["solidity","remix"],"text":"Title: Warning Regarding extcodehash in Remix for openzeppelin-contracts\nTags: solidity, remix\nSource: Stack Overflow\n\nQuestion:\nI have compiled the openzeppelin-contracts code in Remix IDE. Meanwhile, I have obtained the following warning.\n\nWarning: The \"extcodehash\" instruction is not supported by the VM version \"byzantium\" you are currently compiling for. It will be interpreted as an invalid instruction on this VM. assembly { codehash := extcodehash(account) }\n\nI am obtaining this warning for all recent versions of the EVM, and not just the byzantium one. I have tried to search for a solution regarding this warning, but without success. Would anyone know how to \"fix\" this issue?\n\n========================================\n\nCode:\n```text\nimport \"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.3.0/contracts/token/ERC721/ERC721Full.sol\";\nimport \"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.3.0/contracts/math/SafeMath.sol\";\n```\n\n```text\nbyzantium\n```\n\n```text\npetersburg\n```\n\n========================================\n\nComments:\n- Thank you abcoathup. I am compiling the smart contrat found at the link hereafter (using the 0.5.3 Compiler Version): medium.com/openberry/&hellip;\n- Updated my answer now that I can see the contract.\n- Thank you for your answer and time abcoathup!\n- I create a Pull Request to get the code for the tutorial you used updated: github.com/openberry-ac/cryptovipers/pull/3 I created an Issue to update the pragma Solidity version on `Address.sol` in OpenZeppelin Contracts github.com/OpenZeppelin/openzeppelin-contracts/issues/1897\n- Wonderful! Thank you again abcoathup.","metadata":{"transformedAt":"2026-08-18T18:33:36.134Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":35,"estimatedTokens":411}}290{"id":"stack-56005578","source":"stackoverflow","questionId":56005578,"title":"The constructor should be payable if you send value","tags":["ethereum","blockchain","solidity","smartcontracts"],"text":"Title: The constructor should be payable if you send value\nTags: ethereum, blockchain, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI'm running this code on remix IDE. Everything is working fine except the `function transfertocontracts(uint amount) public`. I'm trying to transfer some ethers for e.g. 10 to my contract and then later using this function `function Transfer_Contract_Amount() public` I will transfer all the amount of contract to specific address.\n\nThe problem is that when I run `function transfertocontracts(uint amount) public` I'm getting this Error:\n\nNote: The constructor should be payable if you send value. debug the transaction to get more information.\n\n```\ncontract SLA {\n \n address seller;\n \n \n event DepositFunds(address from, uint amount);\n \n constructor() payable public {\n seller = msg.sender;\n }\n \n\n function transfertocontracts(uint amount) public {\n address(this).transfer(amount);\n }\n \n function seePerson_Amount() public view returns(uint) {\n return seller.balance;\n }\n\n function seeContract_Amount() public view returns(uint) {\n return address(this).balance;\n }\n \n function Transfer_Contract_Amount() public {\n seller.transfer(address(this).balance);\n }\n}\n```\n\n========================================\n\nCode:\n```text\ncontract SLA {\n    \n    address seller;\n    \n    \n    event DepositFunds(address from, uint amount);\n    \n    constructor() payable public {\n        seller = msg.sender;\n    }\n    \n\n    function transfertocontracts(uint amount) public {\n       address(this).transfer(amount);\n    }\n    \n    function seePerson_Amount() public view returns(uint) {\n       return seller.balance;\n    }\n\n    function seeContract_Amount() public view returns(uint) {\n       return address(this).balance;\n    }\n    \n    function Transfer_Contract_Amount() public {\n       seller.transfer(address(this).balance);\n    }\n}\n```\n\n```text\nfunction transfertocontracts(uint amount) public\n```\n\n```text\nfunction Transfer_Contract_Amount() public\n```\n\n```text\nfunction transfertocontracts(uint amount) public\n```\n\n```text\npragma solidity >=0.4.22 <0.6.0;\ncontract SLA{\n\n address payable seller;\n\n\nevent DepositFunds(address from, uint amount);\n\nconstructor() payable public {\n    seller = msg.sender;\n}\n\n\nfunction transfertocontracts(uint amount) payable public{\n\n}\n\nfunction seePerson_Amount() public view returns(uint){\n   return seller.balance;\n}\n\nfunction seeContract_Amount() public view returns(uint){\n   return address(this).balance;\n}\n\nfunction Transfer_Contract_Amount() payable public{\n    seller.transfer(address(this).balance);\n}\n}\n```\n\n========================================\n\nComments:\n- great can you please mark it correct and upvote so other can know it too. Thanks:)\n- one more question.. How I will tackle this thing when I will use this smart contract with web3.js.. will this thing will be done using metamask?\n- in web3 you have to send the value parameter with the amount of ether which goes through the metamask to approve the transaction and then it will be sent to SmartContract","metadata":{"transformedAt":"2026-08-18T18:33:36.137Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":126,"estimatedTokens":761}}291{"id":"stack-57213842","source":"stackoverflow","questionId":57213842,"title":"How to access Solidity mapping which has value of array type?","tags":["solidity"],"text":"Title: How to access Solidity mapping which has value of array type?\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI define a state variable of mapping type, e.g. mapping(uint256 => uint256[]). I thought to make it public so that I can access it from outside of the contract. However, the compiler reports error `TypeError: Wrong argument count for function call: 1 arguments given but expected 2.`. It looks like the automatic getter of the mapping doesn't return an array. \n\nFor example, ContractB is the contract to be built, \n\n```\npragma solidity >=0.5.0 uint256[]) public data;\n\n function getData(uint256 index) public view returns(uint256[] memory) {\n return data[index];\n }\n\n function add(uint256 index, uint256 value) public {\n data[index].push(value);\n }\n}\n```\n\nCreating a test contract to test ContractB,\n\n```\nimport \"remix_tests.sol\"; // this import is automatically injected by Remix.\nimport \"./ContractB.sol\";\n\ncontract TestContractB {\n\n function testGetData () public {\n ContractB c = new ContractB();\n\n c.add(0, 1);\n c.add(0, 2);\n\n Assert.equal(c.data(0).length, 2, \"should have 2 elements\"); // There is error in this line\n }\n}\n```\n\nI could create a function in ContractB which returns array, though.\n\n========================================\n\nCode:\n```text\npragma solidity >=0.5.0 <0.6.0;\n\ncontract ContractB {\n    mapping(uint256 => uint256[]) public data;\n\n    function getData(uint256 index) public view returns(uint256[] memory) {\n        return data[index];\n    }\n\n    function add(uint256 index, uint256 value) public {\n        data[index].push(value);\n    }\n}\n```\n\n```text\nimport \"remix_tests.sol\"; // this import is automatically injected by Remix.\nimport \"./ContractB.sol\";\n\ncontract TestContractB {\n\n    function testGetData () public {\n        ContractB c = new ContractB();\n\n        c.add(0, 1);\n        c.add(0, 2);\n\n        Assert.equal(c.data(0).length, 2, \"should have 2 elements\"); // There is error in this line\n    }\n}\n```\n\n```text\nTypeError: Wrong argument count for function call: 1 arguments given but expected 2.\n```\n\n```text\ncontract TestContractB {\n\n    function testGetData () public {\n        ContractB c = new ContractB();\n\n        c.add(0, 1);\n        c.add(0, 2);\n\n        // Assert.equal(c.data(0).length, 2, \"should have 2 elements\"); // Don't use this\n        Assert.equal(c.data(0,0), 1, \"First element should be 1\"); \n        Assert.equal(c.data(0,1), 2, \"Second element should be 2\"); \n    }\n}\n```\n\n========================================\n\nComments:\n- Hi, looks like a bug, feel free to report this issue (but before check for duplicate) github.com/ethereum/solidity/issues if so, edit your question with a github link to your issue report, thanks :)\n- Thanks, @YegorZaremba, I'd like to report this to solidity to see if it could be improved.\n- Thanks, @ferit. I figured out that I can get elements one by one. But I'm wondering if this is a bug of solidity.\n- Not a bug. Just not supported yet. @sheng hu\n- I just added my answer about dynamic array in experimental version for this thread stackoverflow.com/questions/53985923/dynamic-array-in-solidi&zwnj;&#8203;ty/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:36.137Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":107,"estimatedTokens":784}}292{"id":"stack-50819979","source":"stackoverflow","questionId":50819979,"title":"Linking together smart contracts at deployment","tags":["ethereum","solidity","truffle"],"text":"Title: Linking together smart contracts at deployment\nTags: ethereum, solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nhttps://i.sstatic.net/oaFdX.png\nI'm building an application that is comprised of 3 smart contracts. The aim is to have the controller control the other two (contract A and B in the image). Previously, if I wanted to restrict the access to a smart contact, I would do it through a modifier \nExample:\n\n```\nmodifier onlyController {\n require(msg.sender == controller);\n _;\n }\n```\n\nAt contact creation, the smart contract would set controller to be equal to whatever ethereum address I want to make these calls ( for example the address that deployed the smart contract). The issue is that now I want the address of the controller smart contract to be the controller (in the modifier). How would it be best to do this considering I want to deploy these set of smart contacts at the same time using truffle. What would be the best way to link these, so that the controller smart contract is only able to make calls to A and B. Moreover, how does the controller have to be implemented so that the user can call function in A and B going through the controller ( so the user calls a function in the controller, then the controller calls the corresponding function in A or B)?\n\n========================================\n\nTop Answer:\nCan't you easily set up the controller contract as \n\n```\ncontract ControllerContract is ContractA, ContractB {\n ...\n}\n```\n\nThus giving it access to the functions in both contract A and contract B? \n\nI'm not sure why this way would be worse than how you are describing.\n\n========================================\n\nCode:\n```text\nmodifier onlyController {\n     require(msg.sender == controller);\n     _;\n  }\n```\n\n```text\ninterface Base{\n   function getValue() external view returns (string); \n}\n```\n\n```text\ncontract ControlledAccess{\n   \n    address controller;\n    \n    constructor() public {\n        controller = msg.sender;\n    }\n    \n    modifier onlyController() {\n        require(msg.sender == controller);\n        _;\n    }\n    \n}\n```\n\n```text\ncontract ContractA is Base, ControlledAccess{\n\n    function getValue() public view onlyController returns (string){\n        return \"Hi\";\n    }\n\n}\n\ncontract ContractB is Base, ControlledAccess{\n    \n    function getValue() public view onlyController returns (string){\n        return \"Hello\";\n    }\n\n}\n```\n\n```text\ncontract ProxyController is Base{\n\n    string public contractKey = \"a\";\n    mapping(string => Base) base;\n    \n    constructor() public {\n       base[\"a\"]=new ContractA();\n       base[\"b\"]=new ContractB();\n    }\n    \n    function setContractKey(string _contractKey) public{\n        contractKey = _contractKey;    \n    }\n    \n    function getValue() public view returns (string){\n        return base[contractKey].getValue();\n    }\n    \n}\n```\n\n```text\ncontract ProxyController{\n\n    ContractA a;\n    ContractB b;\n    \n    constructor() public {\n       a=new ContractA();\n       b=new ContractB();\n    }\n    \n    \n    function AgetValue() public view returns (string){\n        return a.getValue();\n    }\n    \n    function BgetValue() public view returns (string){\n        return b.getValue();\n    }        \n    \n}\n```\n\n```text\nproxy pattern\n```\n\n```text\njava\n```\n\n```text\ncontracts\n```\n\n```text\nContractA\n```\n\n```text\nContractB\n```\n\n```text\nContractA\n```\n\n```text\nContractB\n```\n\n```text\nBase\n```\n\n```text\nControlledAccess\n```\n\n```text\nProxyController\n```\n\n```text\nProxyController\n```\n\n```text\nmapping\n```\n\n```text\nsetContractKey\n```\n\n```text\ncontract ControllerContract is ContractA, ContractB {\n    ...\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.138Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":186,"estimatedTokens":903}}293{"id":"stack-50075162","source":"stackoverflow","questionId":50075162,"title":"In Remix - Solidity IDE, How to pass arguments?","tags":["solidity","remix"],"text":"Title: In Remix - Solidity IDE, How to pass arguments?\nTags: solidity, remix\nSource: Stack Overflow\n\nQuestion:\nI'm studying smart contracts on solidity and I ran into a problem. Every time I try to create this contract, my arguments are not confirmed.\n\nI expected a \"OreOreCoin\" to come out when I chose name, but instead I get an empty string.\n\nhttps://i.sstatic.net/P8lh6.png \n\nand \n\nhttps://i.sstatic.net/0OaYa.png\n\nThis my code:\n\n```\npragma solidity ^0.4.8;\n\ncontract OreOreCoin{\n string public name;\n string public symbol;\n uint8 public decimals;\n uint256 public totalSupply;\n\n mapping (address => uint256) public balanceOf;\n\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n function OreOreCoin(uint256 _supply, string _name, string _symbol, uint8 \n _demicals){\n balanceOf[msg.sender] = _supply;\n name = _name;\n symbol = _symbol;\n decimals = _demicals;\n totalSupply = _supply;\n }\n\n function transfer(address _to, uint256 _value){\n if(balanceOf[msg.sender] What could be the problem?\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.8;\n\ncontract OreOreCoin{\n    string public name;\n    string public symbol;\n    uint8 public decimals;\n    uint256 public totalSupply;\n\n    mapping (address => uint256) public balanceOf;\n\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    function OreOreCoin(uint256 _supply, string _name, string _symbol, uint8 \n    _demicals){\n        balanceOf[msg.sender] = _supply;\n        name = _name;\n        symbol = _symbol;\n        decimals = _demicals;\n        totalSupply = _supply;\n    }\n\n    function transfer(address _to, uint256 _value){\n        if(balanceOf[msg.sender] < _value) throw;\n        if(balanceOf[_to] + _value < balanceOf[_to]) throw;\n        balanceOf[msg.sender] -= _value;\n        balanceOf[_to] += _value;\n\n        Transfer(msg.sender,_to,_value);\n    }\n}\n```\n\n```text\nuint256\n```\n\n```text\n_supply\n```\n\n```text\n10000,”OreOreCoin”,”oc”,0\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.138Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":89,"estimatedTokens":495}}294{"id":"stack-48639557","source":"stackoverflow","questionId":48639557,"title":"Deploying Contracts with Circular Dependency in Truffle","tags":["solidity","truffle"],"text":"Title: Deploying Contracts with Circular Dependency in Truffle\nTags: solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nThe CryptoKitties contracts apparently have circular dependency. I don't know how to sequence the deployment of the contracts in Truffle.\n\nClockAuction's constructor requires an address to a contract that implements \"ERC721\".\n\nIn this code, ERC721 is implemented by KittyOwnership, which inherits from KittyBase.\n\nKittyBase contains reference to SaleClockAuction, which inherits from ClockAuction.\n\nHow should the Truffle deployment be structured here? \n\nKittyBase can't be deployed without SaleClockAuction being deployed first. However, SaleClockAuction's parent's constructor needs an address for KittyOwnership, which inherits from KittyBase.\n\nIn a nutshell:\n\n- ClockAuction needs the address of deployed KittyOwnership.\n\n- KittyOwnership inherits from KittyBase.\n\n- KittyBase needs SaleClockAuction.\n\n- SaleClockAuction inherits from ClockAuction.\n\n========================================\n\nCode:\n```text\nsetSiringAuctionAddress\n```\n\n```text\nsetSaleAuctionAddress\n```\n\n========================================\n\nComments:\n- Thanks. So the answer seems to be [1] Deploy KittyCore (which inherits from KittyOwnership). [2] Deploy Sale / Siring, passing address of KittyCore. [3] Call Setter in KittyCore with address of Sale / Siring.","metadata":{"transformedAt":"2026-08-18T18:33:36.138Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":42,"estimatedTokens":340}}295{"id":"stack-43250397","source":"stackoverflow","questionId":43250397,"title":"Unit testing Datetime values","tags":["unit-testing","ethereum","solidity"],"text":"Title: Unit testing Datetime values\nTags: unit-testing, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI have a function that makes use of the current time (`now`). The Contract as a whole is a Crowdfunding token and the cost of tokens differ depending on the date and time that tokens are purchased. \n\nHow does one simulate different times when testing a Smart Contract? For instance, with regards to the code below, I would like to do unit testing to find out if the code for setting price is correct but I can't change the value of `now`. \n\nWould it be a good solution to simply substitute the `now` keyword for another temporary testing variable, say `now_sim` and then manually changing `now_sim` during simulation?\n\n```\nif (now < (startTime + 1 days)) {\n currentPrice = safeDiv(safeMul(price, 80), 100); // 20 % discount (x * 80 / 100)\n } \n else if (now < (startTime + 2 days)) {\n currentPrice = safeDiv(safeMul(price, 90), 100); // 10 % discount (x * 90 / 100)\n }\n else if (now < (startTime + 12 days)) {\n // 1 % reduction in the discounted rate from day 2 until day 12 (sliding scale per second)\n // 8640000 is 60 x 60 x 24 x 100 (100 for 1%) (60 x 60 x 24 for seconds per day)\n currentPrice = price - safeDiv(safeMul((startTime + 12 days) - now), price), 8640000);\n }\n else {\n currentPrice = price;\n }\n```\n\n========================================\n\nCode:\n```text\nif (now < (startTime + 1 days)) {\n        currentPrice = safeDiv(safeMul(price, 80), 100);  // 20 % discount (x * 80 / 100)\n    } \n    else if (now < (startTime + 2 days)) {\n        currentPrice = safeDiv(safeMul(price, 90), 100);  // 10 % discount (x * 90 / 100)\n    }\n    else if (now < (startTime + 12 days)) {\n        // 1 % reduction in the discounted rate from day 2 until day 12 (sliding scale per second)\n        // 8640000 is 60 x 60 x 24 x 100 (100 for 1%) (60 x 60 x 24 for seconds per day)\n        currentPrice = price - safeDiv(safeMul((startTime + 12 days) - now), price), 8640000);\n    }\n    else {\n        currentPrice = price;\n    }\n```\n\n```text\nnow\n```\n\n```text\nnow\n```\n\n```text\nnow\n```\n\n```text\nnow_sim\n```\n\n```text\nnow_sim\n```\n\n```text\nself.s = t.state()\nself.s.block.timestamp = self.s.block.timestamp + 86400\nself.s.mine(1)\nsome_val = your_contract.do_something(some_parameter)\nself.assertEqual(some_val, whatever)\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.138Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":75,"estimatedTokens":580}}296{"id":"stack-47590811","source":"stackoverflow","questionId":47590811,"title":"Modifies clause error on a changed object","tags":["automated-tests","verification","solidity","dafny"],"text":"Title: Modifies clause error on a changed object\nTags: automated-tests, verification, solidity, dafny\nSource: Stack Overflow\n\nQuestion:\nHow can I state (in Dafny) an \"*ensures*\" guarantee that the object returned by a method will be \"new\", i.e., will not be the same as an object used anywhere else (yet)?\n\nThe following code shows a minimal example:\n\n```\nmethod newArray(a:array) returns (b:array)\nrequires a != null\nensures b != null\nensures a != b\nensures b.Length == a.Length+1\n{\n b := new int[a.Length+1];\n}\n\nclass Testing {\n var test : array;\n\n method doesnotwork()\n requires this.test!=null\n requires this.test.Length > 10;\n modifies this\n {\n this.test := newArray(this.test); //change array a with b\n this.test[3] := 9; //error modifies clause\n }\n\n method doeswork()\n requires this.test!=null\n requires this.test.Length > 10;\n modifies this\n {\n this.test := new int[this.test.Length+1];\n this.test[3] := 9;\n }\n\n}\n```\n\nThe \"*doeswork*\" function compiles (and verifies) correctly, but the other one does not, as the Dafny compiler cannot know that the object returned by the \"*newArray*\" function is new, i.e., is not required to be listed as modifiable in the \"require\" statement of the \"*doesnotwork*\" function in order for that function to fulfill the requirement that it only modifies \"*this*\". In the \"*doeswork*\" function, I simply inserted the definition of the \"*newArray*\" function, and then it works.\n\nYou can find the example above under https://rise4fun.com/Dafny/hHWwr, where it can also be ran online.\n\nThanks!\n\n========================================\n\nCode:\n```text\nmethod newArray(a:array<int>) returns (b:array<int>)\nrequires a != null\nensures b != null\nensures a != b\nensures b.Length == a.Length+1\n{\n  b := new int[a.Length+1];\n}\n\nclass Testing {\n  var test : array<int>;\n\n  method doesnotwork()\n  requires this.test!=null\n  requires this.test.Length > 10;\n  modifies this\n  {\n    this.test := newArray(this.test); //change array a with b\n    this.test[3] := 9;  //error modifies clause\n  }\n\n  method doeswork()\n  requires this.test!=null\n  requires this.test.Length > 10;\n  modifies this\n  {\n    this.test := new int[this.test.Length+1];\n    this.test[3] := 9;\n  }\n\n\n}\n```\n\n```text\nensures fresh(b)\n```\n\n```text\nnewArray\n```\n\n```text\nfresh\n```\n\n```text\nnewArray\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.138Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":102,"estimatedTokens":573}}297{"id":"stack-46345735","source":"stackoverflow","questionId":46345735,"title":"remix solidity contract how to pass multiple arguments into the create button","tags":["blockchain","solidity","smartcontracts","remix"],"text":"Title: remix solidity contract how to pass multiple arguments into the create button\nTags: blockchain, solidity, smartcontracts, remix\nSource: Stack Overflow\n\nQuestion:\nI have a sample code look like this:\n\n```\nfunction HubiiCrowdsale(address _teamMultisig, uint _start, uint _end) Crowdsale(_teamMultisig, _start, _end, hubii_minimum_funding) public {\n PricingStrategy p_strategy = new FlatPricing(token_in_wei);\n CeilingStrategy c_strategy = new FixedCeiling(chunked_multiple, limit_per_address);\n FinalizeAgent f_agent = new BonusFinalizeAgent(this, bonus_base_points, _teamMultisig); \n setPricingStrategy(p_strategy);\n setCeilingStrategy(c_strategy);\n // Testing values\n token = new CrowdsaleToken(token_name, token_symbol, token_initial_supply, token_decimals, _teamMultisig, token_mintable);\n token.setMintAgent(address(this), true);\n token.setMintAgent(address(f_agent), true);\n token.setReleaseAgent(address(f_agent));\n setFinalizeAgent(f_agent);\n }\n```\n\nit just needs me to pass (address _teamMultisig, uint _start, uint _end) three arguments into the create button to create the contract, I have tried \n\n```\n\"0xca35b7d915458ef540ade6068dfe2f44e8fa733c\" 1234 1235\n```\n\ngives error:\n\n```\ncreation of browser/ballot.sol:HubiiCrowdsale errored: Error encoding arguments: SyntaxError: Unexpected number in JSON at position 46\n```\n\nand:\n\n```\n{\"_teamMultisig\":\"0xca35b7d915458ef540ade6068dfe2f44e8fa733c\",\"_start\":1234,\"_end\":1235}\n```\n\ngives error\n\n```\ncreation of browser/ballot.sol:HubiiCrowdsale errored: Error encoding arguments: Error: Argument is not a number\n```\n\nwhat is the correct way to pass argument here?\n\n========================================\n\nCode:\n```text\nfunction HubiiCrowdsale(address _teamMultisig, uint _start, uint _end) Crowdsale(_teamMultisig, _start, _end, hubii_minimum_funding) public {\n      PricingStrategy p_strategy = new FlatPricing(token_in_wei);\n      CeilingStrategy c_strategy = new FixedCeiling(chunked_multiple, limit_per_address);\n      FinalizeAgent f_agent = new BonusFinalizeAgent(this, bonus_base_points, _teamMultisig); \n      setPricingStrategy(p_strategy);\n      setCeilingStrategy(c_strategy);\n      // Testing values\n      token = new CrowdsaleToken(token_name, token_symbol, token_initial_supply, token_decimals, _teamMultisig, token_mintable);\n      token.setMintAgent(address(this), true);\n      token.setMintAgent(address(f_agent), true);\n      token.setReleaseAgent(address(f_agent));\n      setFinalizeAgent(f_agent);\n  }\n```\n\n```text\n\"0xca35b7d915458ef540ade6068dfe2f44e8fa733c\" 1234 1235\n```\n\n```text\ncreation of browser/ballot.sol:HubiiCrowdsale errored: Error encoding arguments: SyntaxError: Unexpected number in JSON at position 46\n```\n\n```text\n{\"_teamMultisig\":\"0xca35b7d915458ef540ade6068dfe2f44e8fa733c\",\"_start\":1234,\"_end\":1235}\n```\n\n```text\ncreation of browser/ballot.sol:HubiiCrowdsale errored: Error encoding arguments: Error: Argument is not a number\n```\n\n```text\n\"0xca35b7d915458ef540ade6068dfe2f44e8fa733c\", 1234, 1235\n```\n\n========================================\n\nComments:\n- Are you have tried (`\"0xca35b7d915458ef540ade6068dfe2f44e8fa733c\", 1234, 1235`) - without parentheses - ?\n- i tried that, it said 'creation of browser/ballot.sol:HubiiCrowdsale errored: Send transaction failed: invalid address . if you use an injected provider, please check it is properly unlocked. '","metadata":{"transformedAt":"2026-08-18T18:33:36.138Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":93,"estimatedTokens":839}}298{"id":"stack-44316495","source":"stackoverflow","questionId":44316495,"title":"Testing ethereum events directly in solidity with truffle","tags":["unit-testing","events","ethereum","solidity","smartcontracts"],"text":"Title: Testing ethereum events directly in solidity with truffle\nTags: unit-testing, events, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI found the following question for testing event logging in truffle using javascript:\n\nTest ethereum Event Logs with truffle\n\nBut truffle also supports writing tests directly in solidity. However, I can't find any documentation for how to test event logging in solidity. Can somebody help me with this?\n\n========================================\n\nTop Answer:\nEvents are logs stored at blockchain. To get an event you need to watch the chain. \nhttp://solidity.readthedocs.io/en/develop/contracts.html#events\n\nSolidity Truffle tests are contracts. And contracts just Ethereum accounts storing code. That code gets executed when that account receives a transaction. Ethereum contracts can not watch chain to get an event logs. So Solidity does not support getting events. \nhttps://github.com/ethereum/wiki/wiki/White-Paper#ethereum-accounts\n\n========================================\n\nCode:\n```text\npragma solidity 0.5.12;\n\n    contract EventEmitter {\n\n    // ---- EVENTS -----------------------------------------------------------------------------------------------------\n    event ConstructorDone(address owner, string message);\n    event Counter(uint64 count);\n\n    // ---- FIELDS -----------------------------------------------------------------------------------------------------\n    uint64 private _count = 0;\n    string constant _message = '0x0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789';\n\n    // ---- CONSTRUCTOR ------------------------------------------------------------------------------------------------\n    constructor() public {\n        emit ConstructorDone(msg.sender, _message);\n    }\n\n    // ---- STATISTICS FUNCTIONS ---------------------------------------------------------------------------------------\n    function getCount() public view returns (uint count) {\n        return _count;\n    }\n\n    // ---- CORE FUNCTIONS ---------------------------------------------------------------------------------------------\n    function increment() public {\n        _count++;\n        emit Counter(_count);\n    }\n}\n```\n\n```text\npragma solidity 0.5.12;\n\nimport \"truffle/Assert.sol\";\nimport \"../contracts/EventEmitter.sol\";\n\ncontract TestAnEventEmitter {\n\n    EventEmitter private eventEmitter;\n\n    uint eContracts = 0;\n\n    address private owner;\n\n    function assertCount() private {\n        Assert.equal(eventEmitter.getCount(), eContracts, \"Unexpected count of created contracts\");\n    }\n\n    constructor() public{\n        eventEmitter = new EventEmitter();\n        owner = address(this);\n    }\n\n}\n```\n\n```text\nconst EventEmitter = artifacts.require(\"EventEmitter\");\nconst truffleAssert = require('truffle-assertions');\n\n/** Expected number of counter */\nvar eCount = 0;\n\n/** The Contract's instance */\nvar eventEmitter;\n\nglobal.CONTRACT_ADDRESS = '';\n\nasync function assertContractCount() {\n    assert.equal(await eventEmitter.getCount.call(), eCount, \"Wrong number of created contracts\");\n}\n\ncontract('EventEmitter', async () => {\n\n    before(async () => {\n        eventEmitter = await EventEmitter.new();\n    });\n\n    describe(\"1.1 Basic\", function () {\n\n        it(\"1.1.1 has been created\", async () => {\n            global.CONTRACT_ADDRESS = eventEmitter.address;\n            console.log('        contract => ' + global.CONTRACT_ADDRESS);\n            await assertContractCount();\n        });\n\n        it(\"1.1.2 should emit ConstructorDone event\", async () => {\n            // Get the hash of the deployment transaction\n            let txHash = eventEmitter.transactionHash;\n\n            // Get the transaction result using truffleAssert\n            let result = await truffleAssert.createTransactionResult(eventEmitter, txHash);\n\n            // Check event\n            truffleAssert.eventEmitted(result, 'ConstructorDone', (ev) => {\n                console.log('        owner => ' + ev.owner);\n                return true;\n            });\n        });\n    });\n\n    describe(\"1.2 Check calls of increment()\", function () {\n\n        it(\"1.2.1 first call should increase the counts correctly\", async () => {\n            // Pre-Conditions\n            await assertContractCount();\n\n            // Creation\n            let tx = await eventEmitter.increment();\n            eCount++;\n\n            // Expected Event\n            truffleAssert.eventEmitted(tx, 'Counter', (ev) => {\n                return parseInt(ev.count) === eCount;\n            });\n\n            // Post-Conditions\n            await assertContractCount();\n        });\n\n        it(\"1.2.2 second call should increase the counts correctly\", async () => {\n            // Pre-Conditions\n            await assertContractCount();\n\n            // Creation\n            let tx = await eventEmitter.increment();\n            eCount++;\n\n            // Expected Event\n            truffleAssert.eventEmitted(tx, 'Counter', (ev) => {\n                return parseInt(ev.count) === eCount;\n            });\n\n            // Post-Conditions\n            await assertContractCount();\n        });\n\n        it(\"1.2.3 third call should increase the counts correctly\", async () => {\n            // Pre-Conditions\n            await assertContractCount();\n\n            // Creation\n            let tx = await eventEmitter.increment();\n            eCount++;\n\n            // Expected Event\n            truffleAssert.eventEmitted(tx, 'Counter', (ev) => {\n                return parseInt(ev.count) === eCount;\n            });\n\n            // Post-Conditions\n            await assertContractCount();\n        });\n    });\n});\n```\n\n```text\n$ truffle test\nUsing network 'development'.\n\n\nCompiling your contracts...\n===========================\n> Compiling ./test/TestAnEventEmitter.sol\n\n\n\n  Contract: EventEmitter\n    1.1 Basic\n        contract => 0xeD62E72c2d04Aa385ec764c743219a93ae49e796\n      ✓ 1.1.1 has been created (56ms)\n        owner => 0xbD004d9048C9b9e5C4B5109c68dd569A65c47CF9\n      ✓ 1.1.2 should emit ConstructorDone event (63ms)\n    1.2 Check calls of increment()\n      ✓ 1.2.1 first call should increase the counts correctly (142ms)\n      ✓ 1.2.2 second call should increase the counts correctly (160ms)\n      ✓ 1.2.3 third call should increase the counts correctly (156ms)\n```\n\n```cs\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.3;\n\ncontract Test {\n    address public owner;\n\n    event ContractCreated();\n\n    constructor() {\n        owner = msg.sender;\n\n        emit ContractCreated();\n    }\n}\n```\n\n```js\nconst { expectEvent } = require('@openzeppelin/test-helpers');\n\nconst TestContract = artifacts.require('Test');\n\ncontract('Test', function (accounts) {\n    const [owner] = accounts;\n    const txParams = { from: owner };\n\n    beforeEach(async function () {\n        this.testContract = await TestContract.new(txParams);\n    });\n\n    describe('construction', function () {\n        it('initial state', async function () {\n            expect(await this.testContract.owner()).to.equal(owner);\n\n            await expectEvent.inConstruction(this.testContract, 'ContractCreated');\n        });\n    });\n});\n```\n\n```json\n{\n..\n  \"devDependencies\": {\n    \"@openzeppelin/test-helpers\": \"^0.5.10\"\n  }\n..\n}\n```\n\n========================================\n\nComments:\n- You could use Web3 into the test.","metadata":{"transformedAt":"2026-08-18T18:33:36.138Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":258,"estimatedTokens":1841}}299{"id":"stack-62639935","source":"stackoverflow","questionId":62639935,"title":"Chainlink node: What to do when transactions are pending?","tags":["blockchain","ethereum","solidity","smartcontracts"],"text":"Title: Chainlink node: What to do when transactions are pending?\nTags: blockchain, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI have a chainlink node, and there are transactions that seem to be stuck. How can I fix pending outgoing confirmations?\n\nhttps://i.sstatic.net/RwNfa.png\n\n========================================\n\nCode:\n```text\nDELETE FROM job_runs WHERE status = 'pending_outgoing_confirmations';\nDELETE FROM tx_attempts WHERE confirmed = 'f';\n```\n\n```text\nACCOUNT_ADDRESS\n```\n\n```text\nMIN_OUTGOING_CONFIRMATIONS\n```\n\n```text\n.env\n```\n\n```text\nACCOUNT_ADDRESS\n```\n\n```text\nMIN_OUTGOING_CONFIRMATIONS\n```\n\n```text\n.env\n```\n\n```text\nMIN_INCOMING_CONFIRMATIONS=0\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.138Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":44,"estimatedTokens":175}}300{"id":"stack-59345097","source":"stackoverflow","questionId":59345097,"title":"cannot call the function in smart contract","tags":["blockchain","solidity","truffle"],"text":"Title: cannot call the function in smart contract\nTags: blockchain, solidity, truffle\nSource: Stack Overflow\n\nQuestion:\ni am try to call a method in solidity smart contract through angular app. but i unable to call the method. can someone please help me. this is the error i get in console\n\n```\nTypeError: this.contract.methods.hello is not a function\nat CertificateContractService. (certificate-contract.service.ts:32)\nat Generator.next ()\nat fulfilled (tslib.es6.js:70)\nat ZoneDelegate.invoke (zone-evergreen.js:359)\nat Object.onInvoke (core.js:39699)\nat ZoneDelegate.invoke (zone-evergreen.js:358)\nat Zone.run (zone-evergreen.js:124)\nat zone-evergreen.js:855\nat ZoneDelegate.invokeTask (zone-evergreen.js:391)\nat Object.onInvokeTask (core.js:39680)\n```\n\n### Smart contract\n\n```\ncontract CertificateList {\n\n function hello() external pure returns (string memory ) {\n return \"Hello\";\n }\n\n}\n```\n\n### Angular service\n\n```\nimport Web3 from 'web3';\nimport {WEB3} from './WEB3';\n\ndeclare let require: any;\ndeclare let window: any;\n\n@Injectable({\n providedIn: 'root'\n})\nexport class CertificateContractService {\n private abi: any;\n private address = '0xb0fFD3498B219ad2A62Eb98fEDE591265b3C3B67';\n private contract;\n private accounts: string[];\n\n constructor(@Inject(WEB3) private web3: Web3) {\n this.init().then(res => {\n }).catch(err => {\n console.error(err);\n });\n }\n\n private async init() {\n this.abi = require('../assets/abi/CertificateList.json');\n // await this.web3.currentProvider.enable();\n this.accounts = await this.web3.eth.getAccounts();\n\n this.contract = new this.web3.eth.Contract(this.abi, this.address, {gas: 1000000, gasPrice: '10000000000000'});\n\n this.contract.methods.hello().send()\n .then(receipt => {\n console.log(receipt);\n }).catch(err => {\n console.error(err);\n });\n }\n}\n```\n\n### Provider\n\n```\nimport { InjectionToken } from '@angular/core';\nimport Web3 from 'web3';\n\nexport const WEB3 = new InjectionToken('web3', {\n providedIn: 'root',\n factory: () => {\n try {\n window['ethereum'].autoRefreshOnNetworkChange = false;\n const provider = ('ethereum' in window) ? window['ethereum'] : Web3['givenProvider'];\n return new Web3(provider);\n } catch (err) {\n throw new Error('Non-Ethereum browser detected. You should consider trying Mist or MetaMask!');\n }\n }\n});\n```\n\n========================================\n\nCode:\n```text\nTypeError: this.contract.methods.hello is not a function\nat CertificateContractService.<anonymous> (certificate-contract.service.ts:32)\nat Generator.next (<anonymous>)\nat fulfilled (tslib.es6.js:70)\nat ZoneDelegate.invoke (zone-evergreen.js:359)\nat Object.onInvoke (core.js:39699)\nat ZoneDelegate.invoke (zone-evergreen.js:358)\nat Zone.run (zone-evergreen.js:124)\nat zone-evergreen.js:855\nat ZoneDelegate.invokeTask (zone-evergreen.js:391)\nat Object.onInvokeTask (core.js:39680)\n```\n\n```text\ncontract CertificateList {\n\n    function hello() external pure returns (string memory )  {\n        return \"Hello\";\n    }\n\n}\n```\n\n```text\nimport Web3 from 'web3';\nimport {WEB3} from './WEB3';\n\ndeclare let require: any;\ndeclare let window: any;\n\n\n@Injectable({\n  providedIn: 'root'\n})\nexport class CertificateContractService {\n  private abi: any;\n  private address = '0xb0fFD3498B219ad2A62Eb98fEDE591265b3C3B67';\n  private contract;\n  private accounts: string[];\n\n  constructor(@Inject(WEB3) private web3: Web3) {\n    this.init().then(res => {\n    }).catch(err => {\n      console.error(err);\n    });\n  }\n\n  private async init() {\n    this.abi = require('../assets/abi/CertificateList.json');\n    // await this.web3.currentProvider.enable();\n    this.accounts = await this.web3.eth.getAccounts();\n\n    this.contract = new this.web3.eth.Contract(this.abi, this.address, {gas: 1000000, gasPrice: '10000000000000'});\n\n    this.contract.methods.hello().send()\n      .then(receipt => {\n        console.log(receipt);\n      }).catch(err => {\n      console.error(err);\n    });\n  }\n}\n```\n\n```text\nimport { InjectionToken } from '@angular/core';\nimport Web3 from 'web3';\n\nexport const WEB3 = new InjectionToken<Web3>('web3', {\n  providedIn: 'root',\n  factory: () => {\n    try {\n      window['ethereum'].autoRefreshOnNetworkChange = false;\n      const provider = ('ethereum' in window) ? window['ethereum'] : Web3['givenProvider'];\n      return new Web3(provider);\n    } catch (err) {\n      throw new Error('Non-Ethereum browser detected. You should consider trying Mist or MetaMask!');\n    }\n  }\n});\n```\n\n```js\nvar contractJson = require('../assets/abi/CertificateList.json');\nthis.abi = contractJson['abi'];\n```\n\n```js\nthis.contract.methods.hello().call()\n  .then(receipt => {\n    console.log(receipt);\n  }).catch(err => {\n  console.error(err);\n});\n```\n\n```text\n../assets/abi/CertificateList.json\n```\n\n```text\ntruffle compile\n```\n\n```text\nsolc CertificateList.sol\n```\n\n```text\nmethods.hello.send\n```\n\n```text\ncall\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.138Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":214,"estimatedTokens":1210}}301{"id":"stack-55947716","source":"stackoverflow","questionId":55947716,"title":"How to read public variable in solidity with truffle test codes?","tags":["javascript","ethereum","solidity","web3js","truffle"],"text":"Title: How to read public variable in solidity with truffle test codes?\nTags: javascript, ethereum, solidity, web3js, truffle\nSource: Stack Overflow\n\nQuestion:\nI try to get a value from my public variable in solidity with truffle console, but I don't know the correct syntax.\n\ntruffle version \n Truffle v5.0.14 (core: 5.0.14)\n Solidity - 0.5.4 (solc-js)\n Node v11.10.1\n Web3.js v1.0.0-beta.37\n\nHere's what I've already tried.\n\n- I installed truffle with below command.\n\n```\n$ npm install truffle -g\n$ truffle init\n$ truffle develop\n```\n\n- I have contract named ProxyContract and I set up the 2_deploy_migration.js\n\n```\nconst ProxyContract = artifacts.require(\"./ProxyContract.sol\");\n\nmodule.exports = function(deployer) {\n deployer.deploy(ProxyContract).then( () => console.log(\"ProxyContract: \" + ProxyContract.address))\n}\n```\n\n- migrated contract.\n\n```\ntruffle(develop)> migrate\n```\n\nWhen I typed ProxyContract to prompt I could see some object's piece of information and It looked like fine.\n\nand I tried to access 'committeeStatus' variable like this but it just occurred some error codes, even there's no parameter for the 'committeeStatus'\n\n```\ntruffle(develop)> var proxyContract = await ProxyContract.deployed()\nundefined\n\ntruffle(develop)> proxyContract.committeeStatus.call().then(function (res) {console.log(res)})\nThrown:\nError: Invalid number of parameters for \"committeeStatus\". Got 0 expected 1!\n at processTicksAndRejections (internal/process/next_tick.js:81:5)\n at Promise (/usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-contract/lib/execute.js:128:1)\n at Object._createTxObject (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-contract/src/index.js:699:1)\n at Object.InvalidNumberOfParams (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-contract/~/web3-core-helpers/src/errors.js:32:1)\n```\n\nHow to get a public variable value via truffle test codes?\n\n### What i tried the additional things...\n\n```\ntruffle(develop)> proxyContract.committeeStatus\n{ [Function]\n call: [Function],\n sendTransaction: [Function],\n estimateGas: [Function],\n request: [Function] }\n```\n\n```\ntruffle(develop)> proxyNemodax.committeeStatus.toString()\nfunction() { \n var params = {};\n var defaultBlock = \"latest\";\n var args = Array.prototype.slice.call(arguments);\n var lastArg = args[args.length - 1];\n\n // Extract defaultBlock parameter\n if (execute.hasDefaultBlock(args, lastArg, methodABI.inputs)) {\n defaultBlock = args.pop();\n }\n // Extract tx params\n if (execute.hasTxParams(lastArg)) {\n params = args.pop();\n }\n\n params.to = address;\n params = utils.merge(constructor.class_defaults, params);\n\n return new Promise(async (resolve, reject) => {\n let result;\n try {\n await constructor.detectNetwork();\n args = utils.convertToEthersBN(args);\n result = await fn(...args).call(params, defaultBlock);\n result = reformat.numbers.call(\n constructor,\n result,\n methodABI.outputs\n );\n resolve(result);\n } catch (err) {\n reject(err);\n }\n });\n }'\n```\n\n```\ntruffle(develop)> proxyNemodax.committeeStatus.call(0)\nThrown:\n{ Error: invalid address (arg=\"\", coderType=\"address\", value=0)\n at ABICoder.encodeParameters (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/src/index.js:96:1)\n at AbiCoder.encode (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:897:1)\n at CoderTuple.encode (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:764:1)\n at pack (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:604:1)\n at Array.forEach ()\n at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:605:21\n at CoderAddress.encode (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:467:1)\n at Object.throwError (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/errors.js:68:1)\n reason: 'invalid address',\n code: 'INVALID_ARGUMENT',\n arg: '',\n coderType: 'address',\n value: 0 }\n```\n\nHere's my solidity code\n\n```\npragma solidity 0.5.4;\n\n/**\n * @title SafeMath\n * @dev Math operations with safety checks that throw on error\n */\nlibrary SafeMath {\n\n /**\n * @dev Multiplies two numbers, throws on overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n // Gas optimization: this is cheaper than asserting 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\n if (a == 0) {\n return 0;\n }\n\n c = a * b;\n assert(c / a == b);\n return c;\n }\n\n /**\n * @dev Integer division of two numbers, truncating the quotient.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n // assert(b > 0); // Solidity automatically throws when dividing by 0\n // uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n return a / b;\n }\n\n /**\n * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n assert(b = a);\n return c;\n }\n}\n\n/**\n * @title MultiOwnable\n *\n * @dev Require majority approval of multiple owners to use and access to features\n * when restrictions on access to critical functions are required.\n *\n */\n\ncontract MultiOwnable {\n using SafeMath for uint8;\n\n struct CommitteeStatusPack{\n /**\n * Key informations for decisions.\n * To save some gas, choosing the struct.\n */\n uint8 numOfOwners;\n uint8 numOfVotes;\n uint8 numOfMinOwners;\n bytes proposedFuncData;\n }\n CommitteeStatusPack public committeeStatus;\n\n address[] public ballot; // To make sure if it already was voted\n mapping(address => bool) public owner;\n\n event Vote(address indexed proposer, bytes indexed proposedFuncData);\n event Propose(address indexed proposer, bytes indexed proposedFuncData);\n event Dismiss(address indexed proposer, bytes indexed proposedFuncData);\n event AddedOwner(address newOwner);\n event RemovedOwner(address removedOwner);\n event TransferOwnership(address from, address to);\n\n /**\n * Organize initial committee.\n *\n * @notice committee must be 3 at least.\n * you have to use this contract to be inherited because it is internal.\n *\n * @param _coOwner1 _coOwner2 _coOwner3 _coOwner4 _coOwner5 committee members\n */\n constructor(address _coOwner1, address _coOwner2, address _coOwner3, address _coOwner4, address _coOwner5) internal {\n require(_coOwner1 != address(0x0) &&\n _coOwner2 != address(0x0) &&\n _coOwner3 != address(0x0) &&\n _coOwner4 != address(0x0) &&\n _coOwner5 != address(0x0));\n require(_coOwner1 != _coOwner2 &&\n _coOwner1 != _coOwner3 &&\n _coOwner1 != _coOwner4 &&\n _coOwner1 != _coOwner5 &&\n _coOwner2 != _coOwner3 &&\n _coOwner2 != _coOwner4 &&\n _coOwner2 != _coOwner5 &&\n _coOwner3 != _coOwner4 &&\n _coOwner3 != _coOwner5 &&\n _coOwner4 != _coOwner5); // SmartDec Recommendations\n owner[_coOwner1] = true;\n owner[_coOwner2] = true;\n owner[_coOwner3] = true;\n owner[_coOwner4] = true;\n owner[_coOwner5] = true;\n committeeStatus.numOfOwners = 5;\n committeeStatus.numOfMinOwners = 5;\n emit AddedOwner(_coOwner1);\n emit AddedOwner(_coOwner2);\n emit AddedOwner(_coOwner3);\n emit AddedOwner(_coOwner4);\n emit AddedOwner(_coOwner5);\n }\n\n modifier onlyOwner() {\n require(owner[msg.sender]);\n _;\n }\n\n /**\n * Pre-check if it's decided by committee\n *\n * @notice If there is a majority approval,\n * the function with this modifier will not be executed.\n */\n modifier committeeApproved() {\n /* check if proposed Function Name and real function Name are correct */\n require( keccak256(committeeStatus.proposedFuncData) == keccak256(msg.data) ); // SmartDec Recommendations\n\n /* To check majority */\n require(committeeStatus.numOfVotes > committeeStatus.numOfOwners.div(2));\n _;\n _dismiss(); //Once a commission-approved proposal is made, the proposal is initialized.\n }\n\n /**\n * Suggest the functions you want to use.\n *\n * @notice To use some importan functions, propose function must be done first and voted.\n */\n function propose(bytes memory _targetFuncData) onlyOwner public {\n /* Check if there're any ongoing proposals */\n require(committeeStatus.numOfVotes == 0);\n require(committeeStatus.proposedFuncData.length == 0);\n\n /* regist function informations that proposer want to run */\n committeeStatus.proposedFuncData = _targetFuncData;\n emit Propose(msg.sender, _targetFuncData);\n }\n\n /**\n * Proposal is withdrawn\n *\n * @notice When the proposed function is no longer used or deprecated,\n * proposal is discarded\n */\n function dismiss() onlyOwner public {\n _dismiss();\n }\n\n /**\n * Suggest the functions you want to use.\n *\n * @notice 'dismiss' is executed even after successfully executing the proposed function.\n * If 'msg.sender' want to pass permission, he can't pass the 'committeeApproved' modifier.\n * internal functions are required to enable this.\n */\n\n function _dismiss() internal {\n emit Dismiss(msg.sender, committeeStatus.proposedFuncData);\n committeeStatus.numOfVotes = 0;\n committeeStatus.proposedFuncData = \"\";\n delete ballot;\n }\n\n /**\n * Owners vote for proposed item\n *\n * @notice if only there're proposals, 'vote' is processed.\n * the result must be majority.\n * one ticket for each owner.\n */\n\n function vote() onlyOwner public {\n // Check duplicated voting list.\n uint length = ballot.length; // SmartDec Recommendations\n for(uint i=0; i committeeStatus.numOfVotes); // SmartDec Recommendations\n committeeStatus.numOfVotes++;\n ballot.push(msg.sender);\n emit Vote(msg.sender, committeeStatus.proposedFuncData);\n }\n\n /**\n * Existing owner transfers permissions to new owner.\n *\n * @notice It transfers authority to the person who was not the owner.\n * Approval from the committee is required.\n */\n function transferOwnership(address _newOwner) onlyOwner committeeApproved public {\n require( _newOwner != address(0x0) ); // callisto recommendation\n require( owner[_newOwner] == false );\n owner[msg.sender] = false;\n owner[_newOwner] = true;\n emit TransferOwnership(msg.sender, _newOwner);\n }\n\n /**\n * Add new Owner to committee\n *\n * @notice Approval from the committee is required.\n *\n */\n function addOwner(address _newOwner) onlyOwner committeeApproved public {\n require( _newOwner != address(0x0) );\n require( owner[_newOwner] != true );\n owner[_newOwner] = true;\n committeeStatus.numOfOwners++;\n emit AddedOwner(_newOwner);\n }\n\n /**\n * Remove the Owner from committee\n *\n * @notice Approval from the committee is required.\n *\n */\n function removeOwner(address _toRemove) onlyOwner committeeApproved public {\n require( _toRemove != address(0x0) );\n require( owner[_toRemove] == true );\n require( committeeStatus.numOfOwners > committeeStatus.numOfMinOwners ); // must keep Number of Minimum Owners at least.\n owner[_toRemove] = false;\n committeeStatus.numOfOwners--;\n emit RemovedOwner(_toRemove);\n }\n}\n\ncontract Pausable is MultiOwnable {\n event Pause();\n event Unpause();\n\n bool internal paused;\n\n modifier whenNotPaused() {\n require(!paused);\n _;\n }\n\n modifier whenPaused() {\n require(paused);\n _;\n }\n\n modifier noReentrancy() {\n require(!paused);\n paused = true;\n _;\n paused = false;\n }\n\n /* When you discover your smart contract is under attack, you can buy time to upgrade the contract by\n immediately pausing the contract.\n */\n function pause() public onlyOwner committeeApproved whenNotPaused {\n paused = true;\n emit Pause();\n }\n\n function unpause() public onlyOwner committeeApproved whenPaused {\n paused = false;\n emit Unpause();\n }\n}\n\n/**\n * Contract Managing TokenExchanger's address used by ProxyNemodax\n */\ncontract RunningContractManager is Pausable {\n address public implementation; //SmartDec Recommendations\n\n event Upgraded(address indexed newContract);\n\n function upgrade(address _newAddr) onlyOwner committeeApproved external {\n require(implementation != _newAddr);\n implementation = _newAddr;\n emit Upgraded(_newAddr); // SmartDec Recommendations\n }\n\n /* SmartDec Recommendations\n function runningAddress() onlyOwner external view returns (address){\n return implementation;\n }\n */\n}\n\n/**\n * @title NemodaxStorage\n *\n * @dev This is contract for proxyNemodax data order list.\n * Contract shouldn't be changed as possible.\n * If it should be edited, please add from the end of the contract .\n */\n\ncontract NemodaxStorage is RunningContractManager {\n\n // Never ever change the order of variables below!!!!\n // Public variables of the token\n string public name;\n string public symbol;\n uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it\n uint256 public totalSupply;\n\n /* This creates an array with all balances */\n mapping (address => uint256) public balances;\n mapping (address => mapping (address => uint256)) public allowed;\n mapping (address => bool) public frozenExpired; // SmartDec Recommendations\n\n bool private initialized;\n\n uint256 public tokenPerEth;\n bool public opened = true;\n}\n\n/**\n * @title ProxyNemodax\n *\n * @dev The only fallback function will forward transaction to TokenExchanger Contract.\n * and the result of calculation would be stored in ProxyNemodax\n *\n */\n\ncontract ProxyNemodax is NemodaxStorage {\n\n /* Initialize new committee. this will be real committee accounts, not from TokenExchanger contract */\n constructor(address _coOwner1,\n address _coOwner2,\n address _coOwner3,\n address _coOwner4,\n address _coOwner5)\n MultiOwnable( _coOwner1, _coOwner2, _coOwner3, _coOwner4, _coOwner5) public {}\n\n function () payable external {\n address localImpl = implementation;\n require(localImpl != address(0x0));\n\n assembly {\n let ptr := mload(0x40)\n\n switch calldatasize\n case 0 { } // just to receive ethereum\n\n default{\n calldatacopy(ptr, 0, calldatasize)\n\n let result := delegatecall(gas, localImpl, ptr, calldatasize, 0, 0)\n let size := returndatasize\n returndatacopy(ptr, 0, size)\n switch result\n\n case 0 { revert(ptr, size) }\n default { return(ptr, size) }\n }\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nI tested your contract on remix.ethereum.org.\n\nThe abi of committeeStatus (no input data): \n\n```\n{\n \"constant\": true,\n \"inputs\": [],\n \"name\": \"committeeStatus\",\n \"outputs\": [\n {\n \"name\": \"numOfOwners\",\n \"type\": \"uint8\"\n },\n {\n \"name\": \"numOfVotes\",\n \"type\": \"uint8\"\n },\n {\n \"name\": \"numOfMinOwners\",\n \"type\": \"uint8\"\n },\n {\n \"name\": \"proposedFuncData\",\n \"type\": \"bytes\"\n }\n ],\n \"payable\": false,\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n},\n```\n\nSo you can just call: proxyNemodax.committeeStatus.call() in this contract.\n\n========================================\n\nCode:\n```text\n$ npm install truffle -g\n$ truffle init\n$ truffle develop\n```\n\n```text\nconst ProxyContract = artifacts.require(\"./ProxyContract.sol\");\n\nmodule.exports = function(deployer) {\n   deployer.deploy(ProxyContract).then( () => console.log(\"ProxyContract: \" + ProxyContract.address))\n}\n```\n\n```text\ntruffle(develop)> migrate\n```\n\n```text\ntruffle(develop)> var proxyContract = await ProxyContract.deployed()\nundefined\n\ntruffle(develop)> proxyContract.committeeStatus.call().then(function (res) {console.log(res)})\nThrown:\nError: Invalid number of parameters for \"committeeStatus\". Got 0 expected 1!\n    at processTicksAndRejections (internal/process/next_tick.js:81:5)\n    at Promise (/usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-contract/lib/execute.js:128:1)\n    at Object._createTxObject (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-contract/src/index.js:699:1)\n    at Object.InvalidNumberOfParams (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-contract/~/web3-core-helpers/src/errors.js:32:1)\n```\n\n```text\ntruffle(develop)> proxyContract.committeeStatus\n{ [Function]\n  call: [Function],\n  sendTransaction: [Function],\n  estimateGas: [Function],\n  request: [Function] }\n```\n\n```text\ntruffle(develop)> proxyNemodax.committeeStatus.toString()\nfunction() {     \n    var params = {};\n    var defaultBlock = \"latest\";\n    var args = Array.prototype.slice.call(arguments);\n    var lastArg = args[args.length - 1];\n\n    // Extract defaultBlock parameter\n    if (execute.hasDefaultBlock(args, lastArg, methodABI.inputs)) {\n        defaultBlock = args.pop();\n    }\n      // Extract tx params\n      if (execute.hasTxParams(lastArg)) {\n        params = args.pop();\n      }\n\n      params.to = address;\n      params = utils.merge(constructor.class_defaults, params);\n\n      return new Promise(async (resolve, reject) => {\n        let result;\n        try {\n          await constructor.detectNetwork();\n          args = utils.convertToEthersBN(args);\n          result = await fn(...args).call(params, defaultBlock);\n          result = reformat.numbers.call(\n            constructor,\n            result,\n            methodABI.outputs\n          );\n          resolve(result);\n        } catch (err) {\n          reject(err);\n        }\n      });\n    }'\n```\n\n```text\ntruffle(develop)> proxyNemodax.committeeStatus.call(0)\nThrown:\n{ Error: invalid address (arg=\"\", coderType=\"address\", value=0)\n    at ABICoder.encodeParameters (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/src/index.js:96:1)\n    at AbiCoder.encode (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:897:1)\n    at CoderTuple.encode (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:764:1)\n    at pack (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:604:1)\n    at Array.forEach (<anonymous>)\n    at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:605:21\n    at CoderAddress.encode (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/abi-coder.js:467:1)\n    at Object.throwError (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3-eth-abi/~/ethers/utils/errors.js:68:1)\n  reason: 'invalid address',\n  code: 'INVALID_ARGUMENT',\n  arg: '',\n  coderType: 'address',\n  value: 0 }\n```\n\n```text\npragma solidity 0.5.4;\n\n\n/**\n * @title SafeMath\n * @dev Math operations with safety checks that throw on error\n */\nlibrary SafeMath {\n\n  /**\n  * @dev Multiplies two numbers, throws on overflow.\n  */\n  function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // Gas optimization: this is cheaper than asserting 'a' not being zero, but the\n    // benefit is lost if 'b' is also tested.\n    // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\n    if (a == 0) {\n      return 0;\n    }\n\n    c = a * b;\n    assert(c / a == b);\n    return c;\n  }\n\n  /**\n  * @dev Integer division of two numbers, truncating the quotient.\n  */\n  function div(uint256 a, uint256 b) internal pure returns (uint256) {\n    // assert(b > 0); // Solidity automatically throws when dividing by 0\n    // uint256 c = a / b;\n    // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n    return a / b;\n  }\n\n  /**\n  * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).\n  */\n  function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n    assert(b <= a);\n    return a - b;\n  }\n\n  /**\n  * @dev Adds two numbers, throws on overflow.\n  */\n  function add(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    c = a + b;\n    assert(c >= a);\n    return c;\n  }\n}\n\n/**\n * @title MultiOwnable\n *\n * @dev Require majority approval of multiple owners to use and access to features\n *      when restrictions on access to critical functions are required.\n *\n */\n\ncontract MultiOwnable {\n    using SafeMath for uint8;\n\n    struct CommitteeStatusPack{\n      /**\n       * Key informations for decisions.\n       * To save some gas, choosing the struct.\n       */\n        uint8 numOfOwners;\n        uint8 numOfVotes;\n        uint8 numOfMinOwners;\n        bytes proposedFuncData;\n    }\n    CommitteeStatusPack public committeeStatus;\n\n    address[] public ballot; // To make sure if it already was voted\n    mapping(address => bool) public owner;\n\n    event Vote(address indexed proposer, bytes indexed proposedFuncData);\n    event Propose(address indexed proposer, bytes indexed proposedFuncData);\n    event Dismiss(address indexed proposer, bytes indexed proposedFuncData);\n    event AddedOwner(address newOwner);\n    event RemovedOwner(address removedOwner);\n    event TransferOwnership(address from, address to);\n\n\n    /**\n     * Organize initial committee.\n     *\n     * @notice committee must be 3 at least.\n     *         you have to use this contract to be inherited because it is internal.\n     *\n     * @param _coOwner1 _coOwner2 _coOwner3 _coOwner4 _coOwner5 committee members\n     */\n    constructor(address _coOwner1, address _coOwner2, address _coOwner3, address _coOwner4, address _coOwner5) internal {\n        require(_coOwner1 != address(0x0) &&\n                _coOwner2 != address(0x0) &&\n                _coOwner3 != address(0x0) &&\n                _coOwner4 != address(0x0) &&\n                _coOwner5 != address(0x0));\n        require(_coOwner1 != _coOwner2 &&\n                _coOwner1 != _coOwner3 &&\n                _coOwner1 != _coOwner4 &&\n                _coOwner1 != _coOwner5 &&\n                _coOwner2 != _coOwner3 &&\n                _coOwner2 != _coOwner4 &&\n                _coOwner2 != _coOwner5 &&\n                _coOwner3 != _coOwner4 &&\n                _coOwner3 != _coOwner5 &&\n                _coOwner4 != _coOwner5); // SmartDec Recommendations\n        owner[_coOwner1] = true;\n        owner[_coOwner2] = true;\n        owner[_coOwner3] = true;\n        owner[_coOwner4] = true;\n        owner[_coOwner5] = true;\n        committeeStatus.numOfOwners = 5;\n        committeeStatus.numOfMinOwners = 5;\n        emit AddedOwner(_coOwner1);\n        emit AddedOwner(_coOwner2);\n        emit AddedOwner(_coOwner3);\n        emit AddedOwner(_coOwner4);\n        emit AddedOwner(_coOwner5);\n    }\n\n\n    modifier onlyOwner() {\n        require(owner[msg.sender]);\n        _;\n    }\n\n    /**\n     * Pre-check if it's decided by committee\n     *\n     * @notice If there is a majority approval,\n     *         the function with this modifier will not be executed.\n     */\n    modifier committeeApproved() {\n      /* check if proposed Function Name and real function Name are correct */\n      require( keccak256(committeeStatus.proposedFuncData) == keccak256(msg.data) ); // SmartDec Recommendations\n\n      /* To check majority */\n      require(committeeStatus.numOfVotes > committeeStatus.numOfOwners.div(2));\n      _;\n      _dismiss(); //Once a commission-approved proposal is made, the proposal is initialized.\n    }\n\n\n    /**\n     * Suggest the functions you want to use.\n     *\n     * @notice To use some importan functions, propose function must be done first and voted.\n     */\n    function propose(bytes memory _targetFuncData) onlyOwner public {\n      /* Check if there're any ongoing proposals */\n      require(committeeStatus.numOfVotes == 0);\n      require(committeeStatus.proposedFuncData.length == 0);\n\n      /* regist function informations that proposer want to run */\n      committeeStatus.proposedFuncData = _targetFuncData;\n      emit Propose(msg.sender, _targetFuncData);\n    }\n\n    /**\n     * Proposal is withdrawn\n     *\n     * @notice When the proposed function is no longer used or deprecated,\n     *         proposal is discarded\n     */\n    function dismiss() onlyOwner public {\n      _dismiss();\n    }\n\n    /**\n     * Suggest the functions you want to use.\n     *\n     * @notice 'dismiss' is executed even after successfully executing the proposed function.\n     *          If 'msg.sender' want to pass permission, he can't pass the 'committeeApproved' modifier.\n     *          internal functions are required to enable this.\n     */\n\n    function _dismiss() internal {\n      emit Dismiss(msg.sender, committeeStatus.proposedFuncData);\n      committeeStatus.numOfVotes = 0;\n      committeeStatus.proposedFuncData = \"\";\n      delete ballot;\n    }\n\n\n    /**\n     * Owners vote for proposed item\n     *\n     * @notice if only there're proposals, 'vote' is processed.\n     *         the result must be majority.\n     *         one ticket for each owner.\n     */\n\n    function vote() onlyOwner public {\n      // Check duplicated voting list.\n      uint length = ballot.length; // SmartDec Recommendations\n      for(uint i=0; i<length; i++) // SmartDec Recommendations\n        require(ballot[i] != msg.sender);\n\n      //onlyOnwers can vote, if there's ongoing proposal.\n      require( committeeStatus.proposedFuncData.length != 0 );\n\n      //Check, if everyone voted.\n      //require(committeeStatus.numOfOwners > committeeStatus.numOfVotes); // SmartDec Recommendations\n      committeeStatus.numOfVotes++;\n      ballot.push(msg.sender);\n      emit Vote(msg.sender, committeeStatus.proposedFuncData);\n    }\n\n\n    /**\n     * Existing owner transfers permissions to new owner.\n     *\n     * @notice It transfers authority to the person who was not the owner.\n     *           Approval from the committee is required.\n     */\n    function transferOwnership(address _newOwner) onlyOwner committeeApproved public {\n        require( _newOwner != address(0x0) ); // callisto recommendation\n        require( owner[_newOwner] == false );\n        owner[msg.sender] = false;\n        owner[_newOwner] = true;\n        emit TransferOwnership(msg.sender, _newOwner);\n    }\n\n    /**\n     * Add new Owner to committee\n     *\n     * @notice Approval from the committee is required.\n     *\n     */\n    function addOwner(address _newOwner) onlyOwner committeeApproved public {\n        require( _newOwner != address(0x0) );\n        require( owner[_newOwner] != true );\n        owner[_newOwner] = true;\n        committeeStatus.numOfOwners++;\n        emit AddedOwner(_newOwner);\n    }\n\n    /**\n     * Remove the Owner from committee\n     *\n     * @notice Approval from the committee is required.\n     *\n     */\n    function removeOwner(address _toRemove) onlyOwner committeeApproved public {\n        require( _toRemove != address(0x0) );\n        require( owner[_toRemove] == true );\n        require( committeeStatus.numOfOwners > committeeStatus.numOfMinOwners ); // must keep Number of Minimum Owners at least.\n        owner[_toRemove] = false;\n        committeeStatus.numOfOwners--;\n        emit RemovedOwner(_toRemove);\n    }\n}\n\ncontract Pausable is MultiOwnable {\n    event Pause();\n    event Unpause();\n\n    bool internal paused;\n\n    modifier whenNotPaused() {\n        require(!paused);\n        _;\n    }\n\n    modifier whenPaused() {\n        require(paused);\n        _;\n    }\n\n    modifier noReentrancy() {\n        require(!paused);\n        paused = true;\n        _;\n        paused = false;\n    }\n\n    /* When you discover your smart contract is under attack, you can buy time to upgrade the contract by\n       immediately pausing the contract.\n     */\n    function pause() public onlyOwner committeeApproved whenNotPaused {\n        paused = true;\n        emit Pause();\n    }\n\n    function unpause() public onlyOwner committeeApproved whenPaused {\n        paused = false;\n        emit Unpause();\n    }\n}\n\n/**\n * Contract Managing TokenExchanger's address used by ProxyNemodax\n */\ncontract RunningContractManager is Pausable {\n    address public implementation; //SmartDec Recommendations\n\n    event Upgraded(address indexed newContract);\n\n    function upgrade(address _newAddr) onlyOwner committeeApproved external {\n        require(implementation != _newAddr);\n        implementation = _newAddr;\n        emit Upgraded(_newAddr); // SmartDec Recommendations\n    }\n\n    /* SmartDec Recommendations\n    function runningAddress() onlyOwner external view returns (address){\n        return implementation;\n    }\n    */\n}\n\n\n\n\n/**\n * @title NemodaxStorage\n *\n * @dev This is contract for proxyNemodax data order list.\n *      Contract shouldn't be changed as possible.\n *      If it should be edited, please add from the end of the contract .\n */\n\ncontract NemodaxStorage is RunningContractManager {\n\n    // Never ever change the order of variables below!!!!\n    // Public variables of the token\n    string public name;\n    string public symbol;\n    uint8 public decimals = 18;    // 18 decimals is the strongly suggested default, avoid changing it\n    uint256 public totalSupply;\n\n    /* This creates an array with all balances */\n    mapping (address => uint256) public balances;\n    mapping (address => mapping (address => uint256)) public allowed;\n    mapping (address => bool) public frozenExpired; // SmartDec Recommendations\n\n    bool private initialized;\n\n    uint256 public tokenPerEth;\n    bool public opened = true;\n}\n\n/**\n * @title ProxyNemodax\n *\n * @dev The only fallback function will forward transaction to TokenExchanger Contract.\n *      and the result of calculation would be stored in ProxyNemodax\n *\n */\n\ncontract ProxyNemodax is NemodaxStorage {\n\n    /* Initialize new committee. this will be real committee accounts, not from TokenExchanger contract */\n    constructor(address _coOwner1,\n                address _coOwner2,\n                address _coOwner3,\n                address _coOwner4,\n                address _coOwner5)\n        MultiOwnable( _coOwner1, _coOwner2, _coOwner3, _coOwner4, _coOwner5) public {}\n\n    function () payable external {\n        address localImpl = implementation;\n        require(localImpl != address(0x0));\n\n        assembly {\n            let ptr := mload(0x40)\n\n            switch calldatasize\n            case 0 {  } // just to receive ethereum\n\n            default{\n                calldatacopy(ptr, 0, calldatasize)\n\n                let result := delegatecall(gas, localImpl, ptr, calldatasize, 0, 0)\n                let size := returndatasize\n                returndatacopy(ptr, 0, size)\n                switch result\n\n                case 0 { revert(ptr, size) }\n                default { return(ptr, size) }\n            }\n        }\n    }\n}\n```\n\n```text\nproxyContract.committeeStatus.call().then(function (res) {console.log(res)})\n```\n\n```text\n{\n    \"constant\": true,\n    \"inputs\": [],\n    \"name\": \"committeeStatus\",\n    \"outputs\": [\n        {\n            \"name\": \"numOfOwners\",\n            \"type\": \"uint8\"\n        },\n        {\n            \"name\": \"numOfVotes\",\n            \"type\": \"uint8\"\n        },\n        {\n            \"name\": \"numOfMinOwners\",\n            \"type\": \"uint8\"\n        },\n        {\n            \"name\": \"proposedFuncData\",\n            \"type\": \"bytes\"\n        }\n    ],\n    \"payable\": false,\n    \"stateMutability\": \"view\",\n    \"type\": \"function\"\n},\n```\n\n========================================\n\nComments:\n- as per the error message from truffle that you shared it points out that committeeStatus is a function and needs an address type argument.\n- @SurajKohli Hmm.. that's weird. Why did it recognize a public variable as a function?\n- but it's just public variable. I think it has no argument which it needs\n- this answer doesn't solve the problem for solidity 0.8.4 & truffle 5.3.\n- yeah I know. but, as I said, I had a problem","metadata":{"transformedAt":"2026-08-18T18:33:36.138Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":1068,"estimatedTokens":7749}}302{"id":"stack-44179638","source":"stackoverflow","questionId":44179638,"title":"String conversion to Array in Solidity","tags":["arrays","string","ethereum","solidity"],"text":"Title: String conversion to Array in Solidity\nTags: arrays, string, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nIn Solidity, is there a way I can convert my string text to an array using a separator to identify the composite parts within the string\n\nExample\n\n```\nmystring = \"This-Is-A-Problem\";\n```\n\nto\n\n```\nmyArray = [This,Is,A,Problem]; // using hyphen as separator\n```\n\n========================================\n\nTop Answer:\nupdated answer, works on latest compiler\n\n```\nimport \"github.com/Arachnid/solidity-stringutils/strings.sol\";\n\ncontract Contract { \n using strings for *; \n\n function smt() public pure { \n strings.slice memory s = \"This-Is-A-Problem\".toSlice(); \n strings.slice memory delim = \"-\".toSlice(); \n string[] memory parts = new string[](s.count(delim)); \n for (uint i = 0; i https://ethfiddle.com/TgY5JxLKvn\n\n========================================\n\nCode:\n```text\nmystring = \"This-Is-A-Problem\";\n```\n\n```text\nmyArray = [This,Is,A,Problem];   // using hyphen as separator\n```\n\n```text\nimport \"github.com/Arachnid/solidity-stringutils/strings.sol\";\n\ncontract Contract {\n   using strings for *;\n\n   // ...\n\n   function smt() {\n    var s = \"\"This-Is-A-Problem\"\".toSlice();\n    var delim = \"-\".toSlice();\n    var parts = new string[](s.count(delim) + 1);\n\n    for(uint i = 0; i < parts.length; i++) {\n       parts[i] = s.split(delim).toString();\n    }\n   }\n}\n```\n\n```text\nimport \"github.com/Arachnid/solidity-stringutils/strings.sol\";\n\ncontract Contract {\n    using strings for *;\n\n    // ...\n\n    function smt() {\n        var s = \"\"This-Is-A-Problem\"\".toSlice();\n        var delim = \"-\".toSlice();\n        var parts = new string[](s.count(delim));\n        for(uint i = 0; i < parts.length; i++) {\n           parts[i] = s.split(delim).toString();\n        }\n    }\n}\n```\n\n```text\nimport \"github.com/Arachnid/solidity-stringutils/strings.sol\";\n\ncontract Contract {                                                            \n    using strings for *;                                                       \n\n    function smt() public pure {                                               \n        strings.slice memory s = \"This-Is-A-Problem\".toSlice();                \n        strings.slice memory delim = \"-\".toSlice();                            \n        string[] memory parts = new string[](s.count(delim));                  \n        for (uint i = 0; i < parts.length; i++) {                              \n           parts[i] = s.split(delim).toString();                               \n        }                                                                      \n    }                                                                          \n}\n```\n\n========================================\n\nComments:\n- Food for thought: every operation in EVM costs gas (which is money), so while doing this is possible, I'd not recommend doing this kind of processing in EVM to save cost. You should do all of these processing offline (e.g. before passing it to the contract), and only use the contract to execute logic that must be done on the blockchain (e.g. storing values)\n- @Dat It comes down to priorities. What costs more money, multiple oraclize_query calls returning single bits of data, or a single call that gets split it up in the contract.\n- This Strings Library fails to compile with my Contract, cause I'm using `pragma solidity ^0.6.0;` Is there no way for me to use it then?\n- So, they dropped \"var\"?\n- they removed `var` in solidity 0.7.0 (current is 0.8.9) `The keyword var cannot be used anymore. Previously, this keyword would parse but result in a type error and a suggestion about which type to use. Now, it results in a parser error.` docs.soliditylang.org/en/develop/&hellip;","metadata":{"transformedAt":"2026-08-18T18:33:36.138Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":111,"estimatedTokens":928}}303{"id":"stack-73171892","source":"stackoverflow","questionId":73171892,"title":"Unsupported method: eth_sendTransaction. Alchemy does not hold users' private keys","tags":["javascript","solidity","hardhat","alchemy"],"text":"Title: Unsupported method: eth_sendTransaction. Alchemy does not hold users' private keys\nTags: javascript, solidity, hardhat, alchemy\nSource: Stack Overflow\n\nQuestion:\nI can't execute a send transaction method of my smart contract from the frontend by Alchemy\n\nI am a beginner and I am trying to execute a method from my frontend that sends a transaction to the blockchain but I get an error from alchemy saying that the transaction needs to be signed with my private key but I have no idea how to do this and I did not find anything similar In Internet\n\nError in the front: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'transactionHash')\n\nError in Alchemy: Unsupported method: eth_sendTransaction. Alchemy does not hold users' private keys. See available methods at https://docs.alchemy.com/alchemy/documentation/apis\n\nError in Alchemy: {\n\"jsonrpc\": \"2.0\",\n\"error\": {\n\"code\": -32600,\n\"message\": \"Unsupported method: eth_sendTransaction. Alchemy does not hold users' private keys. See available methods at https://docs.alchemy.com/alchemy/documentation/apis\"\n},\n\"id\": 4\n}\n\n========================================\n\nComments:\n- You have no account/signer imported. People might not know the alchemy \"frontend\" maybe you can specify your problem of importing a signer.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":27,"estimatedTokens":395}}304{"id":"stack-71558241","source":"stackoverflow","questionId":71558241,"title":"Passing a Struct Array to constructor of Solidity Contract","tags":["solidity","ethers.js","hardhat"],"text":"Title: Passing a Struct Array to constructor of Solidity Contract\nTags: solidity, ethers.js, hardhat\nSource: Stack Overflow\n\nQuestion:\nI am building an NFT smart contract with solidity, and I am trying to pass and Array of Structs into the constructor when I deploy the contract. However I am getting the following error.\n\n```\nTypeError: Cannot read property 'length' of undefined\n```\n\nThe contact code is:\n\n```\ncontract MetropolisWorldGenesis {\n\n using Counters for Counters.Counter;\n Counters.Counter private _tokenIds;\n\n struct PropertyAttributes {\n uint id;\n string name;\n string description;\n string image;\n Properties properties;\n }\n\n struct Properties {\n string tower;\n string disctrict;\n string neighborhood;\n string primary_type;\n string sub_type_1;\n string sub_type_2;\n string structure;\n string feature_1;\n string feature_2;\n string feature_3;\n string feature_4;\n string feature_5;\n string rarity;\n // string internal_id;\n }\n\n //store a list of all the NFT's available to mint. \n //this is built on when the constructor is called. \n PropertyAttributes[] defaultProperties;\n\n //store which has been minted. \n mapping(uint => bool) public MintedNfts;\n\n //map the nft tokenid to the atributes \n mapping(uint256 => PropertyAttributes) public nftAttributes;\n\n constructor(PropertyAttributes[] memory props) { \n console.log(\"OK I am making the contract, just this once mind\");\n\n for (uint i = 0; i and I am calling it using the following:\n\n```\nconst main = async () => {\n\n // make up the data from t he json \n const nftList = require('./nft_list_finalv2.json')\n \n let props = []\n\n for(var i=0; i {\n try {\n await main();\n process.exit(0);\n } catch (error) {\n console.log(error);\n process.exit(1);\n }\n };\n \n runMain();\n```\n\nThe Json file is an arrary of items structured as follows.\n\n```\n{ 'nfts':[\n {\n \"id\": 1,\n \"metadata\": {\n \"id\": 1,\n \"name\": \"tester\",\n \"description\": \"Rtestt\",\n \"image\": \"\",\n \"properties\": {\n \"tower\": \"Tower 1\",\n \"district\": \"Hir\",\n \"neighborhood\": \"Fres\",\n \"primary_type\": \"Whause\",\n \"sub_type_1\": \"Aboned\",\n \"sub_type_2\": \"Fors\",\n \"structure\": \"Dark brick\",\n \"feature_1\": \"Df\",\n \"feature_2\": \"Gins\",\n \"feature_3\": \"Castes\",\n \"feature_4\": \"Cloors\",\n \"feature_5\": \"e walls\",\n \"rarity\": \"\",\n \"internal_id\": \"Tower 1_1\"\n }\n },\n \"price\": 10,\n \"ipfs\": \"\",\n \"img_name\": \"WqmYMT02j.png\",\n \"map_ref\": \"Z\"\n },\n....\n]}\n```\n\nI get the array of data fine on javascript side but seems to be some error as i pass it into the contract.\nWhat am i missing here?\n\n========================================\n\nTop Answer:\nActually, you can in fact pass a struct as an arg to a constructor in solidity. I'm doing it myself in one of my contracts:\n\n```\nstruct UserConfig {\n address user;\n address userToken;\n uint userSlippage; \n }\n\n struct FixedConfig { \n address inbox;\n address ops;\n address PYY;\n address emitter;\n uint maxGas;\n }\n\nFixedConfig fxConfig;\nVariableConfig varConfig;\n\nconstructor(\n FixedConfig memory fxConfig_,\n VariableConfig memory varConfig_\n ) {\n fxConfig = fxConfig_;\n varConfig = varConfig_;\n }\n```\n\nYou'd pass it as an array on ethers.js.\n\nThe problem that I'm having, and how I ended up in this post in the first place, is that when you pass the array to `deploy()` on ethers, it changes the order of the vars on the struct in the contract. So I'm trying to figure out why that's happening.\n\n========================================\n\nCode:\n```text\nTypeError: Cannot read property 'length' of undefined\n```\n\n```text\ncontract MetropolisWorldGenesis {\n\n    using Counters for Counters.Counter;\n    Counters.Counter private _tokenIds;\n\n    struct PropertyAttributes {\n        uint id;\n        string name;\n        string description;\n        string image;\n        Properties properties;\n    }\n\n    struct Properties {\n        string tower;\n        string disctrict;\n        string neighborhood;\n        string primary_type;\n        string sub_type_1;\n        string sub_type_2;\n        string structure;\n        string feature_1;\n        string feature_2;\n        string feature_3;\n        string feature_4;\n        string feature_5;\n        string rarity;\n        // string internal_id;\n    }\n\n    //store a list of all the NFT's available to mint. \n    //this is built on when the constructor is called. \n    PropertyAttributes[] defaultProperties;\n\n    //store which has been minted. \n    mapping(uint => bool) public MintedNfts;\n\n    //map the nft tokenid to the atributes \n    mapping(uint256 => PropertyAttributes) public nftAttributes;\n\n    constructor(PropertyAttributes[] memory props) { \n        console.log(\"OK I am making the contract, just this once mind\");\n\n        for (uint i = 0; i < props.length; i += 1){\n             defaultProperties.push(props[i]);\n\n             PropertyAttributes memory p = defaultProperties[i];\n             console.log(\"Done initializing %s w/ HP %s, img %s\", p.name, p.description, p.image);\n        \n    } \n}\n```\n\n```text\nconst main = async () => {\n\n    // make up the data from t he json \n    const nftList = require('./nft_list_finalv2.json')\n    \n    let props = []\n\n    for(var i=0; i < nftList['nfts'].length;i+=1){\n        \n        x = nftList['nfts'][i]['metadata']\n        props.push(x)\n    }\n    \n    console.log(props.length)\n\n    // deply the contract will the data made above. \n    const propertyContractFactory = await hre.ethers.getContractFactory('MetropolisWorldGenesis');\n    const propertyContract = await propertyContractFactory.deploy(\n        props\n    );\n    await propertyContract.deployed();\n    console.log(\"Contract deployed to:\", propertyContract.address);\n  };\n  \n  const runMain = async () => {\n    try {\n      await main();\n      process.exit(0);\n    } catch (error) {\n      console.log(error);\n      process.exit(1);\n    }\n  };\n  \n  runMain();\n```\n\n```text\n{ 'nfts':[\n     {\n            \"id\": 1,\n            \"metadata\": {\n                \"id\": 1,\n                \"name\": \"tester\",\n                \"description\": \"Rtestt\",\n                \"image\": \"\",\n                \"properties\": {\n                    \"tower\": \"Tower 1\",\n                    \"district\": \"Hir\",\n                    \"neighborhood\": \"Fres\",\n                    \"primary_type\": \"Whause\",\n                    \"sub_type_1\": \"Aboned\",\n                    \"sub_type_2\": \"Fors\",\n                    \"structure\": \"Dark brick\",\n                    \"feature_1\": \"Df\",\n                    \"feature_2\": \"Gins\",\n                    \"feature_3\": \"Castes\",\n                    \"feature_4\": \"Cloors\",\n                    \"feature_5\": \"e walls\",\n                    \"rarity\": \"\",\n                    \"internal_id\": \"Tower 1_1\"\n                }\n            },\n            \"price\": 10,\n            \"ipfs\": \"\",\n            \"img_name\": \"WqmYMT02j.png\",\n            \"map_ref\": \"Z\"\n        },\n....\n]}\n```\n\n```text\nconstructor (\n  int NFTsId,\n  int MetaId,\n  string MetaName,\n  string MetaDescription,\n  string MetaImage,\n  string PropertiesTower,\n  string PropertiesDistrict,\n  ...,\n  uint MetaPrice,\n  string MetaIPFS,\n  ...\n) {\n  // Assign values\n}\n```\n\n```text\nconstructor (\n  int[] memory NFTsIds,\n  int[] memory MetaIds,\n  string[] memory MetaNames,\n  string[] memory MetaDescriptions,\n  string[] memory MetaImages,\n  string[] memory PropertiesTowers,\n  string[] memory PropertiesDistricts,\n  ...,\n  uint[] memory MetaPrices,\n  string[] memory MetaIPFSs,\n  ...\n) {  \n  for (uint256 i=0; i < NFTsId.length; i ++){\n    NFTsId = NFTsIds[i];\n    ...\n    // Assign values\n  }\n}\n```\n\n```text\nstruct\n```\n\n```text\nconstructor function\n```\n\n```text\nfor\n```\n\n```js\nstruct UserConfig {\n        address user;\n        address userToken;\n        uint userSlippage; \n    }\n\n    struct FixedConfig { \n        address inbox;\n        address ops;\n        address PYY;\n        address emitter;\n        uint maxGas;\n    }\n\nFixedConfig fxConfig;\nVariableConfig varConfig;\n\n\nconstructor(\n        FixedConfig memory fxConfig_,\n        VariableConfig memory varConfig_\n    ) {\n        fxConfig = fxConfig_;\n        varConfig = varConfig_;\n    }\n```\n\n```text\ndeploy()\n```\n\n```text\nstruct YourStruct {\n    uint x;\n    string y;\n}\nfunction func(\n    uint a,\n    uint b,\n    string memory c,\n    YourStruct memory d\n    ) external;\n```\n\n```text\nlet args = [\n    1,\n    2,\n    \"c\",\n    {\n        x: 3,\n        y: \"y\"\n    }\n]\ncontract.func(...args);\n```\n\n========================================\n\nComments:\n- What is the contents of the `.&#47;nft_list_finalv2.json` file?\n- I've edited the question to include json format\n- Thanks very much that makes sense, originally I had the array approach but I ran into a an stack too deep error which I hoped to fix with the structs, looks like i'll need a full rethink.\n- I'm using 0.8.9 and I don't have any issue passing structs as constructor parameters. I'm using structs exactly to avoid a stack too deep error. The issue I'm having is that I now get an error when verifying on Etherscan. I'm trying to figure out if this is related.\n- thanks that is good to know. Any joy with the order issue?\n- No idea on that one\n- I'm not seeing this behavior. Ethers/Hardhat -> solidity keeps the order. What solidity version are you using?\n- sol 0.8.14 @ian\n- What do you mean with \"You'd pass it as an array on ethers.js\"? How does the contract know it is an array if you just declare it as a normal struct there?\n- Don't know how the contract knows it, but just that it does. Try it out yourself and you'll see @FalconStakepool","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":413,"estimatedTokens":2347}}305{"id":"stack-68107865","source":"stackoverflow","questionId":68107865,"title":"Chain Link VRF takes a long time to get random numbers","tags":["blockchain","ethereum","solidity","chainlink"],"text":"Title: Chain Link VRF takes a long time to get random numbers\nTags: blockchain, ethereum, solidity, chainlink\nSource: Stack Overflow\n\nQuestion:\n**Description**\n\nGetting a random number takes a really long time. After executing the getRandomNumber function, a few minutes go by before I can interact with my random number.\n\nBasically I click getRandomNumber and have to wait 2-3 minutes until the random number shows up in the randomResult variable.\n\n**Steps to Reproduce**\n\n- Head over to the documentation here : https://docs.chain.link/docs/get-a-random-number/\n\n- Scroll down and click on \"Deploy this contract using Remix\" (blue outline btn)\n\n- Click on one of the folders that looks like 536123b61468ad4442cfc4278e8de577 then RandomNumberConsumer.sol\n\n- Replace the LINK Token, VRF Coordinator, and Key Hash to be unique to rinkeby https://docs.chain.link/docs/vrf-contracts/\n\n- Navigation to the Solidity Compiler Tab and click on Compile RandomNumber.sol.\n\n- Deploy the contract on Rinkeby\n\n- Copy to contract address and send LINK token to fund the contract.\n\n- Click on the orange getRandomNumber btn in remix\n\n- Click on randomResult and observe how long it takes for the value in randomResult to change. (Keep clicking until it finally changes)\n\n**Additional Information**\n\nI am not sure if this behavior is intentional or if I need to change up the code. Ideally I would like to have the value of randomResult once the getRandomNumber function finishes executing. Right now I don't know when the value of randomResult will show up.\n\n========================================\n\nComments:\n- Thank you for your help! What is the best way to track when a random number is returned? I was thinking I could check on an interval or a fixed amount of time like 2 minutes.\n- A great way is to emit an event whenever you request a random number, and have a function read the chain for the event. Otherwise, a \"simple\" way to do it is to have your program sleep for maybe 60 seconds.\n- Do you know about how long the response takes on polygon? Thinking about building a game that requires some randomness, but if the response is too long, it probably wouldn't be playable\n- Usually within a few blocks.","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":42,"estimatedTokens":551}}306{"id":"stack-68514907","source":"stackoverflow","questionId":68514907,"title":"Testing Token with Uniswap liquidity provisioning using hardhat","tags":["testing","solidity","smartcontracts","hardhat"],"text":"Title: Testing Token with Uniswap liquidity provisioning using hardhat\nTags: testing, solidity, smartcontracts, hardhat\nSource: Stack Overflow\n\nQuestion:\nI'm attempting to fork Safemoon (or really NotSafeMoon), and use it as a vehicle to learn smart contract development. (I've got a substantial amount of what you might call \"Web 2.0\" dev experience).\n\nSo say I have something like so in my constructor:\n\n```\nconstructor () {\n _rOwned[_msgSender()] = _rTotal;\n IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // binance PANCAKE V2\n uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());\n```\n\nWhen I run my tests with `npx hardhat test` I get the following failure:\n\n```\nCompilation finished successfully\n\n TestToken contract\n Deployment\n 1) \"before each\" hook for \"Has the right name\"\n\n 0 passing (807ms)\n 1 failing\n\n 1) TestToken contract\n \"before each\" hook for \"Has the right name\":\n Error: Transaction reverted: function call to a non-contract account\n```\n\nNow, this does make perfect sense, after all I am attempting to call the Pancakeswap v2 router contract. How do I get around this limitation? Is there a way to inject the contract address for the router as an environment variable perhaps? Is there a mock constructor for the UniswapRouter I can be using? Generally, how is this sort of thing done in a way that remains testable (and how is it therefore tested) with smart contract development?\n\n========================================\n\nCode:\n```text\nconstructor () {\n        _rOwned[_msgSender()] = _rTotal;\n        IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E);       // binance PANCAKE V2\n        uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());\n```\n\n```text\nCompilation finished successfully\n\n\n  TestToken contract\n    Deployment\n      1) \"before each\" hook for \"Has the right name\"\n\n\n  0 passing (807ms)\n  1 failing\n\n  1) TestToken contract\n       \"before each\" hook for \"Has the right name\":\n     Error: Transaction reverted: function call to a non-contract account\n```\n\n```text\nnpx hardhat test\n```\n\n========================================\n\nComments:\n- Hardhat suggest using Alchemy but it doesn't support BSC mainnet currently.","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":70,"estimatedTokens":596}}307{"id":"stack-71636003","source":"stackoverflow","questionId":71636003,"title":"Solidity: decode byte data into two structs","tags":["ethereum","solidity","decode"],"text":"Title: Solidity: decode byte data into two structs\nTags: ethereum, solidity, decode\nSource: Stack Overflow\n\nQuestion:\nI have a function call which only accepts bytes data (dydx _getCallActions)\n\n```\n_getCallAction(bytes memory data)\n```\n\nDuring contract execution the data is passed to a user defined function named: \"callFunction\"\n\nWhen decoding into a single struct, it works, however I want to to decode the data into two separate structs.\n\n```\nfunction callFunction(bytes calldata _data){\n// This works, when passed in encoded data matching Struct1Type\nStruct1Type memory data1 = abi.decode(_data, (Struct1Type));\n}\n\nfunction callFunction(bytes calldata _data){\n// Doesnt work\nStruct1Type memory data1, Struct2Type memory data2 = abi.decode(_data, (Struct1Type,Struct2Type));\n}\n```\n\nI could decode the data into a single struct and then selectively cast it into the two desired structs, but this seems gas inefficient\n\n========================================\n\nCode:\n```text\n_getCallAction(bytes memory data)\n```\n\n```text\nfunction callFunction(bytes calldata _data){\n// This works, when passed in encoded data matching Struct1Type\nStruct1Type memory data1 = abi.decode(_data, (Struct1Type));\n}\n\n\nfunction callFunction(bytes calldata _data){\n// Doesnt work\nStruct1Type memory data1, Struct2Type memory data2 = abi.decode(_data, (Struct1Type,Struct2Type));\n}\n```\n\n```text\npragma solidity ^0.8;\n\ncontract MyContract {\n    struct Struct1Type {\n        uint8 number;\n    }\n\n    struct Struct2Type {\n        uint16 number;\n    }\n\n    function callFunction(bytes calldata _data) external pure returns (Struct1Type memory, Struct2Type memory) {\n        // `:32` returns a chunk \"from the beginning to the 32nd index\"\n        Struct1Type memory data1 = abi.decode(_data[:32], (Struct1Type));\n\n        // `32:` returns a chunk \"from the 32nd index to the end\"\n        Struct2Type memory data2 = abi.decode(_data[32:], (Struct2Type));\n\n        return (data1, data2);\n    }\n}\n```\n\n```text\n# two values: `1` and `2`\n0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002\n```\n\n```text\n0: tuple(uint8): 1\n1: tuple(uint16): 2\n```\n\n```text\nStruct1Type\n```\n\n========================================\n\nComments:\n- Is there a way to validate it decoded properly? stackoverflow.com/q/74967465/19361853","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":91,"estimatedTokens":590}}308{"id":"stack-43744697","source":"stackoverflow","questionId":43744697,"title":"I cannot get solidity installed with homebrew on macOS Sierra. Installation hangs at boost","tags":["macos","boost","homebrew","ethereum","solidity"],"text":"Title: I cannot get solidity installed with homebrew on macOS Sierra. Installation hangs at boost\nTags: macos, boost, homebrew, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI have tried to install solidity on my Mac with \n\n```\nbrew update\nbrew upgrade\nbrew tap ethereum/ethereum\nbrew install solidity\n\nbrew linkapps solidity\n```\n\nas suggested at solidity#binary-packages. But when I try to `brew install solidity` the installation process gets stuck right here when installing boost:\n\n```\nbash-3.2$ brew install solidity\n==> Installing solidity from ethereum/ethereum\n==> Installing dependencies for ethereum/ethereum/solidity: boost, cryptopp, gmp\n==> Installing ethereum/ethereum/solidity dependency: boost\n==> Using the sandbox\n==> Downloading https://dl.bintray.com/boostorg/release/1.64.0/source/boost_1_64_0.tar.bz2\nAlready downloaded: /Users/Me/Library/Caches/Homebrew/boost-1.64.0.tar.bz2\n==> Downloading https://github.com/boostorg/mpi/commit/f5bdcc1.patch\nAlready downloaded: /Users/Me/Library/Caches/Homebrew/boost--patch-c7af75a83fef90fdb9858bc988d64ca569ae8d940396b9bc60a57d63fca2587b.patch\n==> Downloading https://github.com/boostorg/serialization/commit/1d86261.diff\nAlready downloaded: /Users/Me/Library/Caches/Homebrew/boost--patch-155f603a00975a1702808be072c1420964feac8323de39c111a9d3a363a4ed9a.diff\n==> Patching\n==> Applying f5bdcc1.patch\npatching file boost/mpi/detail/mpi_datatype_primitive.hpp\npatching file boost/mpi/detail/packed_iprimitive.hpp\npatching file boost/mpi/detail/packed_oprimitive.hpp\nHunk #2 succeeded at 97 (offset -5 lines).\n==> Applying 1d86261.diff\npatching file boost/serialization/array.hpp\n==> ./bootstrap.sh --prefix=/usr/local/Cellar/boost/1.64.0_1 --libdir=/usr/local/Cellar/boost/1.64.0_1/lib --without-icu --without-libraries=python,mp\n==> ./b2 headers\n==> ./b2 --prefix=/usr/local/Cellar/boost/1.64.0_1 --libdir=/usr/local/Cellar/boost/1.64.0_1/lib -d2 -j4 --layout=tagged --user-config=user-config.jam\n```\n\nI did find this brew hanging thread and tried to fix everything `brew doctor` gave me and I have the latest command line tools installed. I could not get it to work yet. Any ideas?\n\n========================================\n\nCode:\n```text\nbrew update\nbrew upgrade\nbrew tap ethereum/ethereum\nbrew install solidity\n\nbrew linkapps solidity\n```\n\n```text\nbash-3.2$ brew install solidity\n==> Installing solidity from ethereum/ethereum\n==> Installing dependencies for ethereum/ethereum/solidity: boost, cryptopp, gmp\n==> Installing ethereum/ethereum/solidity dependency: boost\n==> Using the sandbox\n==> Downloading https://dl.bintray.com/boostorg/release/1.64.0/source/boost_1_64_0.tar.bz2\nAlready downloaded: /Users/Me/Library/Caches/Homebrew/boost-1.64.0.tar.bz2\n==> Downloading https://github.com/boostorg/mpi/commit/f5bdcc1.patch\nAlready downloaded: /Users/Me/Library/Caches/Homebrew/boost--patch-c7af75a83fef90fdb9858bc988d64ca569ae8d940396b9bc60a57d63fca2587b.patch\n==> Downloading https://github.com/boostorg/serialization/commit/1d86261.diff\nAlready downloaded: /Users/Me/Library/Caches/Homebrew/boost--patch-155f603a00975a1702808be072c1420964feac8323de39c111a9d3a363a4ed9a.diff\n==> Patching\n==> Applying f5bdcc1.patch\npatching file boost/mpi/detail/mpi_datatype_primitive.hpp\npatching file boost/mpi/detail/packed_iprimitive.hpp\npatching file boost/mpi/detail/packed_oprimitive.hpp\nHunk #2 succeeded at 97 (offset -5 lines).\n==> Applying 1d86261.diff\npatching file boost/serialization/array.hpp\n==> ./bootstrap.sh --prefix=/usr/local/Cellar/boost/1.64.0_1 --libdir=/usr/local/Cellar/boost/1.64.0_1/lib --without-icu --without-libraries=python,mp\n==> ./b2 headers\n==> ./b2 --prefix=/usr/local/Cellar/boost/1.64.0_1 --libdir=/usr/local/Cellar/boost/1.64.0_1/lib -d2 -j4 --layout=tagged --user-config=user-config.jam\n```\n\n```text\nbrew install solidity\n```\n\n```text\nbrew doctor\n```\n\n```text\n🍺  /usr/local/Cellar/boost/1.64.0_1: 12,630 files, 404.4MB, built in 17 minutes 38 seconds\n```\n\n========================================\n\nComments:\n- Just run brew with `--verbose` to get compilation output.\n- `🍺 &#47;usr&#47;local&#47;Cellar&#47;boost&#47;1.64.0_1: 12,630 files, 404.4MB, built in 58 minutes 26 seconds` for me. Boy that took a long time.\n- The command started the Exhaust fans of the machine. Wondered if everything is fine.","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":100,"estimatedTokens":1076}}309{"id":"stack-70997810","source":"stackoverflow","questionId":70997810,"title":"Hardhat node, error in browser on localhost","tags":["blockchain","ethereum","solidity","hardhat"],"text":"Title: Hardhat node, error in browser on localhost\nTags: blockchain, ethereum, solidity, hardhat\nSource: Stack Overflow\n\nQuestion:\nI'm trying to debug & test a smart contract I developed, however doing so on testnets takes a lot of time and I wanted to test properly on local node.\n\nI can create the node and deploy the contract, transfer from account to another in metamask, every thing works fine, except when I go to http://127.0.0.1:8545/ in browser, I get this error:\n\n```\n{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-32700,\"message\":\"Parse error: Unexpected end of JSON input\"}}\n```\n\nI've tried both brave & chrome, I tried creating a different hardhat project, same error.\n\nWhat can I do?\nThanks!\n\n========================================\n\nCode:\n```text\n{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-32700,\"message\":\"Parse error: Unexpected end of JSON input\"}}\n```\n\n```text\n# request\ncurl 'http://127.0.0.1:8545/' --data-raw ''\n```\n\n```text\n# response\n{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-32700,\"message\":\"Parse error: Unexpected end of JSON input\"}}\n```\n\n```text\n# request\ncurl 'http://127.0.0.1:8545' --data-raw '{\"jsonrpc\":\"2.0\",\"method\":\"net_listening\",\"params\":[],\"id\":1}'\n```\n\n```text\n# response\n{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":true}\n```\n\n========================================\n\nComments:\n- What do u expect to see?\n- I really don't know, I just expected to see something, is this normal?\n- Understood, thanks for the clear explanation !","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":51,"estimatedTokens":365}}310{"id":"stack-72261200","source":"stackoverflow","questionId":72261200,"title":"Chainlink vrf v2 request gas fee amount","tags":["blockchain","ethereum","solidity","chainlink"],"text":"Title: Chainlink vrf v2 request gas fee amount\nTags: blockchain, ethereum, solidity, chainlink\nSource: Stack Overflow\n\nQuestion:\nI'm trying to understand exactly how much it costs(in LINK) to fund the gas fee for a chainlink VRF V2 random value request on Ethereum mainnet.\n\nThere's a formula here about it but i'm not sure im getting it right.\n\nAny help would be appreciated.\n\n========================================\n\nComments:\n- Thanks, but the numbers I'm getting don't seem sensible to me could u do the math for 500gwei gas lane and 100000 Callback gas limit & 200000 Max verification gas & 0.25 LINK premium (thanks in advance I just wanna double check)\n- added an example, let me know if it doesn't make sense\n- thanks , I got the gist of it. PS are you sure about that 0.15 ETH = 0.15LINK part?\n- oops sorry, I forgot to convert the ETH/LINK properly using the price feed! Updated the answer again. This time I'm confident its correct\n- Thanks so much, wow that's a lot!\n- Remember this is just the upper limit, and the 500gwei lane isn't the cheapest lane either. If you take a look at some of the recent VRF calls on Ethereum mainnet lately, you'll see many transactions are only using around 12-20gwei gas limit, and have total fee in ETH of 0.01 ($3), so the total fee in LINK including the 0.25 premium is probably around the 1 LINK mark etherscan.io/address/0x271682DEB8C4E0901D1a1550aD2e64D568E69&zwnj;&#8203;909\n- yes, but if I want to charge the users beforehand I'm not sure it's worth it because I won't know how much to charge them exactly.\n- how would this answer be different if we're considering running vrf on MATIC? Also noting that there's no MATIC / LINK price oracle, would I convert to another denom to figure this out?","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":22,"estimatedTokens":438}}311{"id":"stack-54384890","source":"stackoverflow","questionId":54384890,"title":"Render JavaScript number as solidity ERC20 decimals","tags":["javascript","decimal","solidity","smartcontracts"],"text":"Title: Render JavaScript number as solidity ERC20 decimals\nTags: javascript, decimal, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nWhen you create an ERC20 cryptocurrency in solidity you initialize it with a number of decimals. If you total supply is 10k and the number of decimals is 4, your token supply will display as 100000000 (10,000.0000). \n\nIn Solidity, you simply do YourNumber*10**4 to initialize a number like 10,000.0000 where YourNumber = 10,000\n\nI wanted to do a simple calculator in JavaScript where, based on the user input we give them their input in decimals of a token. \n\nSay the maximum number of decimals is 4 and the user inputs 250,000, we will show them 250,000.0000. If the user inputs 1, we will show them 1.0000. However, if the user inputs 25.5, we will show them 25.5000 Unfortunately, this logic doesn't work in JavaScript or any other programming language I know\n\n```\nlet converted = (this.state.conversion)*(10**14);\n```\n\nWhat are the potential solutions?\n\n========================================\n\nCode:\n```text\nlet converted = (this.state.conversion)*(10**14);\n```\n\n```js\nvar a = 250000, b = 1, c = 25.5\n\nconsole.log(a.toFixed(4), b.toFixed(4), c.toFixed(4))\n```\n\n```js\nconsole.log(new Intl.NumberFormat('en-GB', { useGrouping: true, minimumFractionDigits: 4 }).format(250000))\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":35,"estimatedTokens":333}}312{"id":"stack-73426947","source":"stackoverflow","questionId":73426947,"title":"How would you call a contract method that takes Enum type via hardhat?","tags":["solidity","hardhat"],"text":"Title: How would you call a contract method that takes Enum type via hardhat?\nTags: solidity, hardhat\nSource: Stack Overflow\n\nQuestion:\nIn your contract, if you have method that receives an Enum type, how would you pass the arguments from hardhat script?\n\n```\ncontract SomeContract {\n\nenum WinStatus {\n PENDING,\n LOST,\n WON\n}\n\nWinStatus status;\n\nfunction updateWinStatus(WinStatus _status) public {\n status = _status;\n}\n}\n```\n\n```\n// in your hardhat script\n...\nawait someContract.updateWinStatus() // how should i call it. bare in mind hardhat is setup using javascript not typescript in my case.\n```\n\ni tried passing a number, hoping it will get it by order(index). But I am getting 'invalid BigNumber value'. Also, I tried passing a string like \"PENDING\" or \"WinType.PENDING\" :thinking:\n\n========================================\n\nTop Answer:\nAs an alternative, you can the work-around used by the OpenZeppelin team on their tests.\n\nCreate a new `utils.js` file and add the following method:\n\n```\nfunction Enum(...options) {\n return Object.fromEntries(options.map((key, i) => [key, web3.utils.toBN(i)]));\n}\n```\n\nAfter that you'll be able to add any custom enum by using:\n\n```\nexport const MyCustomEnum = Enum(\"State1\", \"State2\", \"State3\");\n```\n\nSpeaking about your case, the new Enum format defined in the `utils.js` will be:\n\n```\nexport const WinStatus = Enum(\"PENDING\", \"LOST\", \"WON\");\n```\n\nImport the new `WinStatus` enum in your script and use it like this:\n\n```\n// in your hardhat script\n...\nawait someContract.updateWinStatus(WinStatus.PENDING)\n```\n\n========================================\n\nCode:\n```text\ncontract SomeContract {\n\nenum WinStatus {\n    PENDING,\n    LOST,\n    WON\n}\n\nWinStatus status;\n\nfunction updateWinStatus(WinStatus _status) public {\n   status = _status;\n}\n}\n```\n\n```text\n// in your hardhat script\n...\nawait someContract.updateWinStatus() // how should i call it. bare in mind hardhat is setup using  javascript not typescript in my case.\n```\n\n```text\nconst myNumber = ethers.BigNumber.from(\"0\") // pass the numeric value as a string\nawait someContract.updateWinStatus(myNumber) // pass the BigNumber instance\n```\n\n```text\nuint256\n```\n\n```text\nfunction Enum(...options) {\n  return Object.fromEntries(options.map((key, i) => [key, web3.utils.toBN(i)]));\n}\n```\n\n```text\nexport const MyCustomEnum = Enum(\"State1\", \"State2\", \"State3\");\n```\n\n```text\nexport const WinStatus = Enum(\"PENDING\", \"LOST\", \"WON\");\n```\n\n```text\n// in your hardhat script\n...\nawait someContract.updateWinStatus(WinStatus.PENDING)\n```\n\n```text\nutils.js\n```\n\n```text\nutils.js\n```\n\n```text\nWinStatus\n```\n\n========================================\n\nComments:\n- Partially true now that JS support `bigint`\n- @RicardoPedroni `BigInt` max value depends on the environment. E.g. 32bit systems have different max value of `BigInt` compared 64bit systems or even to 8bit systems (that might not be able to fit in the whole `uint256` type)... So I can only guess that Ethers.js developers prefer `BigNumber` not because they're not aware of `BigInt` - but rather simply because its functionality is not dependent on the specific environment.","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":137,"estimatedTokens":782}}313{"id":"stack-69940402","source":"stackoverflow","questionId":69940402,"title":"Compute the LP Address of a token pair using web3.py","tags":["python","solidity","web3py","binance-smart-chain"],"text":"Title: Compute the LP Address of a token pair using web3.py\nTags: python, solidity, web3py, binance-smart-chain\nSource: Stack Overflow\n\nQuestion:\nI managed to have this code run after few hours of searches but unfortunately, this does not produce the output I wanted which is to get the LP Pool Address in (TOKEN/BNB LP).\n\nGiven the Token Address: **0xe56842ed550ff2794f010738554db45e60730371**\n\nI wanted to get the BIN/BNB Pool Address: **0xe432afB7283A08Be24E9038C30CA6336A7cC8218**.\n\nAny ideas what could be the problem?\n\n```\nfrom web3 import Web3\nfrom eth_abi.packed import encode_abi_packed\nfrom eth_abi import encode_abi\nimport eth_abi\n\n\"\"\"\nContract: 0xe56842ed550ff2794f010738554db45e60730371\nBIN/BNB Address: 0xe432afB7283A08Be24E9038C30CA6336A7cC8218\nBIN/BNB LP URL: https://bscscan.com/token/0xe432afB7283A08Be24E9038C30CA6336A7cC8218#balances\n\"\"\"\n\nCONTRACTS = {\"CONTRACT\": \"0xe56842ed550ff2794f010738554db45e60730371\",}\n\nPANCAKE_SWAP_FACTORY = \"0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73\"\nPANCAKE_SWAP_ROUTER = \"0x10ED43C718714eb63d5aA57B78B54704E256024E\"\nWBNB_ADDRESS = \"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c\"\n\nhexadem_= '0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'\nfactory = PANCAKE_SWAP_FACTORY\nabiEncoded_1 = encode_abi_packed(['address', 'address'], (CONTRACTS['CONTRACT'], WBNB_ADDRESS))\nsalt_ = Web3.solidityKeccak(['bytes'], ['0x' +abiEncoded_1.hex()])\nabiEncoded_2 = encode_abi_packed([ 'address', 'bytes32'], ( factory, salt_))\nresPair = Web3.solidityKeccak(['bytes','bytes'], ['0xff' + abiEncoded_2.hex(), hexadem_])[12:]\n\n# resPair is the address for the pancakeswap CONTRACT /WBNB pair\nprint(\"Token Contract: \", CONTRACTS)\nprint(\"BNB-LP Address: \", resPair.hex()) #-- expecting to get 0xe432afB7283A08Be24E9038C30CA6336A7cC8218\n```\n\nCurrent Output:\n\n```\nBNB-LP Address: 0xde173b8a63b9641a531de0fbb1c5c9eee3b4bc0c\n```\n\nExpected Output:\n\n```\nToken Contract: 0xe56842ed550ff2794f010738554db45e60730371\nBNB-LP Address: 0xe432afB7283A08Be24E9038C30CA6336A7cC8218 #-- correct LP Address\n```\n\n========================================\n\nTop Answer:\nFor Pancake Swap the `hexadem_` should be like this I think:\n\n```\nhexadem_= '0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5' ## Pancake SWAP\n```\n\nThe one in your code is for UniSwap\n\n========================================\n\nCode:\n```text\nfrom web3 import Web3\nfrom eth_abi.packed import encode_abi_packed\nfrom eth_abi import encode_abi\nimport eth_abi\n\n\"\"\"\nContract: 0xe56842ed550ff2794f010738554db45e60730371\nBIN/BNB Address: 0xe432afB7283A08Be24E9038C30CA6336A7cC8218\nBIN/BNB LP URL: https://bscscan.com/token/0xe432afB7283A08Be24E9038C30CA6336A7cC8218#balances\n\"\"\"\n\nCONTRACTS = {\"CONTRACT\": \"0xe56842ed550ff2794f010738554db45e60730371\",}\n\nPANCAKE_SWAP_FACTORY = \"0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73\"\nPANCAKE_SWAP_ROUTER  = \"0x10ED43C718714eb63d5aA57B78B54704E256024E\"\nWBNB_ADDRESS = \"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c\"\n\nhexadem_= '0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'\nfactory = PANCAKE_SWAP_FACTORY\nabiEncoded_1 = encode_abi_packed(['address', 'address'], (CONTRACTS['CONTRACT'], WBNB_ADDRESS))\nsalt_ = Web3.solidityKeccak(['bytes'], ['0x' +abiEncoded_1.hex()])\nabiEncoded_2 = encode_abi_packed([ 'address', 'bytes32'], ( factory, salt_))\nresPair = Web3.solidityKeccak(['bytes','bytes'], ['0xff' + abiEncoded_2.hex(), hexadem_])[12:]\n\n# resPair is the address for the pancakeswap CONTRACT /WBNB pair\nprint(\"Token Contract: \", CONTRACTS)\nprint(\"BNB-LP Address: \", resPair.hex())    #-- expecting to get  0xe432afB7283A08Be24E9038C30CA6336A7cC8218\n```\n\n```text\nBNB-LP Address:  0xde173b8a63b9641a531de0fbb1c5c9eee3b4bc0c\n```\n\n```text\nToken Contract:  0xe56842ed550ff2794f010738554db45e60730371\nBNB-LP Address:  0xe432afB7283A08Be24E9038C30CA6336A7cC8218   #-- correct LP Address\n```\n\n```text\npair_traded = [token_a, token_b] #token_a, token_b are the address's\npair_traded.sort()\n\nhexadem_1 = 0xff\nabiEncoded_1 = encode_abi_packed(['address', 'address'], (token_list[0], token_list[1] ))\nsalt_ = w3.solidityKeccak(['bytes'], ['0x' +abiEncoded_1.hex()])\nabiEncoded_2 = encode_abi_packed([ 'address', 'bytes32'], ( factory, salt_))\npair_address = w3.solidityKeccak(['bytes','bytes'], ['0xff' + abiEncoded_2.hex(), pair_code_hash])[12:]\n```\n\n```text\nhexadem_= '0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5'  ## Pancake SWAP\n```\n\n```text\nhexadem_\n```\n\n```text\nhexadem_ = '0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5' # This is pancake right hex。\nfactory = PANCAKE_SWAP_FACTORY\nabiEncoded_1 = encode_abi_packed(['address', 'address'], (CONTRACTS['CONTRACT'], WBNB_ADDRESS))\nsalt_ = Web3.solidityKeccak(['bytes'], ['0x' +abiEncoded_1.hex()])\nabiEncoded_2 = encode_abi_packed([ 'address', 'bytes32'], ( factory, salt_))\nresPair = Web3.solidityKeccak(['bytes','bytes'], ['0xff' + abiEncoded_2.hex(), hexadem_])[12:]\n```\n\n```text\nToken Contract:  {'CONTRACT': '0xe56842ed550ff2794f010738554db45e60730371'}\nBNB-LP Address:  0xdbb161367d9a2a852ebeef3cbfcbf2c43b85064b\n```\n\n```text\ndef compute_pool_address(self, token_address_a, token_address_b):\n    pair_traded = [token_address_a.lower(), token_address_b.lower()]\n    pair_traded.sort()\n    hexadem = '0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5'\n    abiEncoded_1 = encode_abi_packed(['address', 'address'], (pair_traded[0], pair_traded[1]))\n    salt_ = self.web3.solidityKeccak(['bytes'], ['0x' + abiEncoded_1.hex()])\n    abiEncoded_2 = encode_abi_packed(['address', 'bytes32'], (PANCAKE_FACTORY_ADDRESS, salt_))\n    return self.web3.toChecksumAddress(self.web3.solidityKeccak(['bytes', 'bytes'], ['0xff' + abiEncoded_2.hex(), hexadem])[12:])\n```\n\n```text\nkeccak256(\n  abi.encodePacked(\n    hex'ff',\n    factory,\n    keccak256(abi.encode(key.token0, key.token1, key.fee)),\n    POOL_INIT_CODE_HASH\n  )\n)\n```\n\n```text\nencoded_internal_data = abi.encode(['address', 'address', 'uint24'], (token0, token1, fee))\nkey_hash = web3.solidityKeccak(['bytes'], [encoded_internal_data])\nencoded_full_data = encode_abi_packed(\n    [\"bytes1\", \"address\", \"bytes\", \"bytes\"],\n    (HexBytes('ff'), UNISWAPV3_FACTORY_ADDRESS, key_hash, HexBytes(UNISWAPV3_POOL_INIT_CODE_HASH))\n)\npair_address = web3.solidityKeccak(['bytes'], [encoded_full_data])[12:].hex()\n```\n\n========================================\n\nComments:\n- Even though the parameter order is correct, the reasoning is different. The pair contract was created by passing arguments in the order WBNB, BIN. You can check the transaction event logs that created the pair contract - specifically you're looking for the `PairCreated` event. So if you want to get the same pair contract address as a result, you need to pass the same input params (in the correct order).\n- Im getting the error: pair_address = Web3.solidityKeccak(['bytes','bytes'], ['0xff' + abiEncoded_2.hex(), pair_code_hash])[12:] NameError: name 'pair_code_hash' is not defined\n- tried replacing: pair_code_hash into hexadem_1 and it works but the lp address is still wrong\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- can the process be reverse? For example, I have the LP Address instead and I want to display the Token Address","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":182,"estimatedTokens":1851}}314{"id":"stack-78182497","source":"stackoverflow","questionId":78182497,"title":"How to calculate sqrtPricex96 for uniswap pool creation?","tags":["ethereum","solidity","ethers.js","erc20","uniswap"],"text":"Title: How to calculate sqrtPricex96 for uniswap pool creation?\nTags: ethereum, solidity, ethers.js, erc20, uniswap\nSource: Stack Overflow\n\nQuestion:\n### Hello everyone\n\nI'm trying to create a uniswap pool for my erc20 token (SwapToken) / wETH on sepolia just to figure out how things are working on uniswap V3. I'm having a hard time calculating the `sqrtPriceX96` for `createAndInitializePoolIfNecessary` function in `NonfungiblePositionManager` contract.\n\nthe ratio that i'm going to have in the pool is : 100 SWAP / 0.1 WETH\n\nwhat is the calculation process of sqrtPriceX96 in javascript?\n** I also appreciate it if you check my code and correct me if i have done anything wrong\n\n### My code :\n\n```\nconst { ethers } = require(\"ethers\");\nrequire(\"dotenv\").config({ path: \"../.env\" });\nconst providerUrl = process.env.SEPOLIA_RPC_URL;\nconst privateKey = process.env.SEPOLIA_PRIVATE_KEY;\nconst provider = new ethers.providers.JsonRpcProvider(providerUrl);\nconst wallet = new ethers.Wallet(privateKey, provider);\n\nconst swapTokenAbi = require(\"./abi/SwapTokenABI.json\");\nconst wEthAbi = require(\"./abi/wEthAbi.json\");\nconst positionManagerAbi = require(\"./abi/NonfungiblePositionManagerABI.json\");\n\nconst swapTokenAddress = \"0x51ffBe766d3b7B9Aa670CaBa326231A053210983\";\nconst wEthAddress = \"0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14\";\nconst positionManagerAddress = \"0x1238536071E1c677A632429e3655c799b22cDA52\";\n\nconst swapTokenContract = new ethers.Contract(\n swapTokenAddress,\n swapTokenAbi,\n wallet\n);\n\nconst wEthContract = new ethers.Contract(wEthAddress, wEthAbi, wallet);\n\nconst positionManagerContract = new ethers.Contract(\n positionManagerAddress,\n positionManagerAbi,\n wallet\n);\n\nconst fee = 3000;\nconst swapTokenAmount = 100;\nconst wEthAmount = 0.1;\nconst conversion = swapTokenAmount / wEthAmount;\nconst sqrtPriceX96 = \"???\"\n\nasync function createPool() {\n let approveTx = await swapTokenContract.approve(\n positionManagerAddress,\n ethers.utils.parseEther(swapTokenAmount.toString())\n );\n console.log(` Swap approve transaction hash : ${approveTx.hash}`);\n let approveReceipt = await approveTx.wait();\n console.log(` Transaction confirmed in block ${approveReceipt.blockNumber}`);\n\n approveTx = await wEthContract.approve(\n positionManagerAddress,\n ethers.utils.parseEther(wEthAmount.toString())\n );\n console.log(` WETH approve transaction hash : ${approveTx.hash}`);\n approveReceipt = await approveTx.wait();\n console.log(` Transaction confirmed in block ${approveReceipt.blockNumber}`);\n\n const params = {\n token0: swapTokenAddress,\n token1: wEthAddress,\n fee: fee,\n sqrtPriceX96: \"\",\n };\n\n const createPoolTx =\n await positionManagerContract.createAndInitializePoolIfNecessary(params);\n console.log(` Create Pool transaction hash : ${approveTx.hash}`);\n const createPoolReceipt = await approveTx.wait();\n console.log(\n ` Create Pool transaction confirmed in block ${createPoolReceipt.blockNumber}`\n );\n}\n```\n\nI tried searching the web and reading the uniswap documents\n\n========================================\n\nCode:\n```js\nconst { ethers } = require(\"ethers\");\nrequire(\"dotenv\").config({ path: \"../.env\" });\nconst providerUrl = process.env.SEPOLIA_RPC_URL;\nconst privateKey = process.env.SEPOLIA_PRIVATE_KEY;\nconst provider = new ethers.providers.JsonRpcProvider(providerUrl);\nconst wallet = new ethers.Wallet(privateKey, provider);\n\nconst swapTokenAbi = require(\"./abi/SwapTokenABI.json\");\nconst wEthAbi = require(\"./abi/wEthAbi.json\");\nconst positionManagerAbi = require(\"./abi/NonfungiblePositionManagerABI.json\");\n\nconst swapTokenAddress = \"0x51ffBe766d3b7B9Aa670CaBa326231A053210983\";\nconst wEthAddress = \"0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14\";\nconst positionManagerAddress = \"0x1238536071E1c677A632429e3655c799b22cDA52\";\n\nconst swapTokenContract = new ethers.Contract(\n  swapTokenAddress,\n  swapTokenAbi,\n  wallet\n);\n\nconst wEthContract = new ethers.Contract(wEthAddress, wEthAbi, wallet);\n\nconst positionManagerContract = new ethers.Contract(\n  positionManagerAddress,\n  positionManagerAbi,\n  wallet\n);\n\nconst fee = 3000;\nconst swapTokenAmount = 100;\nconst wEthAmount = 0.1;\nconst conversion = swapTokenAmount / wEthAmount;\nconst sqrtPriceX96 = \"???\"\n\nasync function createPool() {\n  let approveTx = await swapTokenContract.approve(\n    positionManagerAddress,\n    ethers.utils.parseEther(swapTokenAmount.toString())\n  );\n  console.log(` Swap approve transaction hash : ${approveTx.hash}`);\n  let approveReceipt = await approveTx.wait();\n  console.log(` Transaction confirmed in block ${approveReceipt.blockNumber}`);\n\n  approveTx = await wEthContract.approve(\n    positionManagerAddress,\n    ethers.utils.parseEther(wEthAmount.toString())\n  );\n  console.log(` WETH approve transaction hash : ${approveTx.hash}`);\n  approveReceipt = await approveTx.wait();\n  console.log(` Transaction confirmed in block ${approveReceipt.blockNumber}`);\n\n  const params = {\n    token0: swapTokenAddress,\n    token1: wEthAddress,\n    fee: fee,\n    sqrtPriceX96: \"\",\n  };\n\n  const createPoolTx =\n    await positionManagerContract.createAndInitializePoolIfNecessary(params);\n  console.log(` Create Pool transaction hash : ${approveTx.hash}`);\n  const createPoolReceipt = await approveTx.wait();\n  console.log(\n    ` Create Pool transaction confirmed in block ${createPoolReceipt.blockNumber}`\n  );\n}\n```\n\n```text\nsqrtPriceX96\n```\n\n```text\ncreateAndInitializePoolIfNecessary\n```\n\n```text\nNonfungiblePositionManager\n```\n\n```js\nconst yourToken_amount = 1000; // Token0 amount with 0 decimals\nconst WETH_amount = 1; // Token1 amount with 0 decimals\nconst SqrtPriceX96 = BigInt(Math.sqrt(WETH_amount / yourToken_amount) * 2 ** 96);\n```\n\n```js\nconst price = Number(SqrtPriceX96) ** 2 / 2 ** 192;\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":182,"estimatedTokens":1426}}315{"id":"stack-63071968","source":"stackoverflow","questionId":63071968,"title":"How to pass struct from contract A to contract B? Best practice","tags":["structure","solidity"],"text":"Title: How to pass struct from contract A to contract B? Best practice\nTags: structure, solidity\nSource: Stack Overflow\n\nQuestion:\nI found such way, when one general interface with structure is created and then contract A and B inherit the interface with structure.\n\nBut I'm wondering if there are other ways?\n\nAnd could there be a case where a contract with a structure can be updated?\n\n```\npragma experimental ABIEncoderV2;\npragma solidity ^0.6.0;\n \ninterface params {\n struct structTest {\n uint256 data;\n }\n}\n\ncontract contractA is params{\n function testCall(structTest calldata _structParams) public pure returns (uint256){\n return _structParams.data;\n }\n}\n\ncontract contractB is params{\n contractA aContractInstance;\n \n constructor (address _a) public {\n aContractInstance = contractA(_a);\n }\n \n function test(structTest calldata _structParams) public view returns(uint256){\n // call contract A from B and pass structure\n return aContractInstance.testCall(_structParams);\n }\n}\n```\n\n========================================\n\nCode:\n```text\npragma experimental ABIEncoderV2;\npragma solidity ^0.6.0;\n \ninterface params {\n     struct  structTest {\n        uint256 data;\n    }\n}\n\ncontract contractA is params{\n    function testCall(structTest calldata _structParams) public pure returns (uint256){\n        return _structParams.data;\n    }\n}\n\ncontract contractB is params{\n    contractA aContractInstance;\n    \n    constructor (address _a) public {\n        aContractInstance = contractA(_a);\n    }\n    \n    function test(structTest calldata _structParams) public view returns(uint256){\n        // call contract A from B and pass structure\n        return aContractInstance.testCall(_structParams);\n    }\n}\n```\n\n```text\ninterface IContractA {\n\n    struct User {\n        address addr;\n    }\n    function getUser(aaddress addr) external view returns (User memory user);\n}\n\ncontract contractB{\n\n    function getUserFromContractA(address addr) public view\n        returns (IContractA.User memory user)\n    {\n      ContractA = IContractA(addrContractA);\n      user = ContractA.getUser(addr);\n    }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":93,"estimatedTokens":524}}316{"id":"stack-72541086","source":"stackoverflow","questionId":72541086,"title":"How to check or know that a wallet has tokens in web3 python","tags":["solidity","smartcontracts","web3py","binance-smart-chain","uniswap"],"text":"Title: How to check or know that a wallet has tokens in web3 python\nTags: solidity, smartcontracts, web3py, binance-smart-chain, uniswap\nSource: Stack Overflow\n\nQuestion:\nI am trying to find out if its possible to know or check in python web3 if a certain bsc address has tokens or transactions.\n\nI can check if an address has bnb or bsc transactions using `nonce = web3.eth.getTransactionCount(address)` but what I want to know is if a certain address has tokens aside from bnb or bsc.\n\nFor example, this address `0x7DBbA1e788b169139F5602CCb734137F45a59aa9` has a token but no bnb or bsc transaction.\n\n========================================\n\nTop Answer:\nSee this sample PY code. I don't remember if it's working properly.\n\n```\nimport json\nfrom web3 import Web3, HTTPProvider\n\n# truffle development blockchain address\nblockchain_address = 'http//:127.0.0.1:7545'\n#client instance to interact with the blockchain\nweb3 = Web3(HTTPProvider(blockchain_address))\n\ncompiled_contract_path = 'build/contracts/FirstContract.json'\ndeployed_contract_address = '0x'\n\nwith open(compiled_contract_path) as file:\n contract_json = json.load(file) #load contract info as JSON\n contract_abi = contract_json['abi']\n\ncontract = web3.eth.contract(address=deployed_contract_address, abi=contract_abi)\n\nresult = contract.functions.setValue(10).transact() #use transact to store value in blockchain\nprint(result)\nprint(result.hex())\nmessage = contract.functions.getValue().call()\nprint(message)\n\nabi = '[]'\n```\n\nSee the line:\n\n```\nmessage = contract.functions.getValue().call()\n```\n\nThe **message** variable receives information from the PY getValue() function.\nYou can implement the erc20 balanceOf ABI and call this function directly in the token contract.\n\nAs for the way BSCscan and Etherscan show the balances, they don't query balanceOf of the token contract. They simply pull the Emit Transfer event histories and do the sending and receiving calculations to display balances. This is a laborious, strange and non-trivial way and I don't know exactly why they prefer to work this way.\n\n========================================\n\nCode:\n```text\nnonce = web3.eth.getTransactionCount(address)\n```\n\n```text\n0x7DBbA1e788b169139F5602CCb734137F45a59aa9\n```\n\n```text\nmapping(address => uint256) private _balances;\n```\n\n```text\nuint256 userBalance = IERC20(tokenAddress).balanceOf(account);\n```\n\n```text\nbalanceOf\n```\n\n```text\nimport json\nfrom web3 import Web3, HTTPProvider\n\n# truffle development blockchain address\nblockchain_address = 'http//:127.0.0.1:7545'\n#client instance to interact with the blockchain\nweb3 = Web3(HTTPProvider(blockchain_address))\n\ncompiled_contract_path = 'build/contracts/FirstContract.json'\ndeployed_contract_address = '0x'\n\nwith open(compiled_contract_path) as file:\n    contract_json = json.load(file) #load contract info as JSON\n    contract_abi = contract_json['abi']\n\ncontract = web3.eth.contract(address=deployed_contract_address, abi=contract_abi)\n\nresult = contract.functions.setValue(10).transact() #use transact to store value in blockchain\nprint(result)\nprint(result.hex())\nmessage = contract.functions.getValue().call()\nprint(message)\n\n\nabi = '[]'\n```\n\n```text\nmessage = contract.functions.getValue().call()\n```\n\n========================================\n\nComments:\n- very informative. this is good enough","metadata":{"transformedAt":"2026-08-18T18:33:36.139Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":113,"estimatedTokens":830}}317{"id":"stack-69825236","source":"stackoverflow","questionId":69825236,"title":"Ethers.js, send money to a smart contract (receive function)","tags":["solidity","ethers.js","decentralized-applications"],"text":"Title: Ethers.js, send money to a smart contract (receive function)\nTags: solidity, ethers.js, decentralized-applications\nSource: Stack Overflow\n\nQuestion:\nI have a smart contract with a receive function :\n\n```\nreceive() external payable {\n Wallets[msg.sender] += msg.value;\n}\n```\n\nI have a front end and I want to send Ethers to this smart contract using the receive() function.\n\n```\nasync function transfer() {\nif(typeof window.ethereum !== 'undefined') {\n const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });\n const provider = new ethers.providers.Web3Provider(window.ethereum);\n const signer = provider.getSigner();\n const contract = new ethers.Contract(WalletAddress, Wallet.abi, signer);\n\n const transaction = await contract.send({\n from: accounts[0],\n value: amount\n })\n await transaction.wait();\n alert('ok');\n setAmount('');\n getBalance();\n}\n```\n\n}\n\nSaldy, there is no \"send\" function, what is the function I need to use there ?\nThx a lot !\n\n========================================\n\nCode:\n```text\nreceive() external payable {\n    Wallets[msg.sender] += msg.value;\n}\n```\n\n```text\nasync function transfer() {\nif(typeof window.ethereum !== 'undefined') {\n  const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });\n  const provider = new ethers.providers.Web3Provider(window.ethereum);\n  const signer = provider.getSigner();\n  const contract = new ethers.Contract(WalletAddress, Wallet.abi, signer);\n\n  const transaction = await contract.send({\n    from: accounts[0],\n    value: amount\n  })\n  await transaction.wait();\n  alert('ok');\n  setAmount('');\n  getBalance();\n}\n```\n\n```text\n// not defining `data` field will use the default value - empty data\nconst transaction = signer.sendTransaction({\n    from: accounts[0],\n    to: WalletAddress,\n    value: amount\n});\n```\n\n```text\nreceive()\n```\n\n```text\ndata\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":83,"estimatedTokens":468}}318{"id":"stack-52690481","source":"stackoverflow","questionId":52690481,"title":"how to create new ethereum/solidity contract for each test in javascript/truffle","tags":["javascript","testing","solidity","smartcontracts","truffle"],"text":"Title: how to create new ethereum/solidity contract for each test in javascript/truffle\nTags: javascript, testing, solidity, smartcontracts, truffle\nSource: Stack Overflow\n\nQuestion:\n### background\n\nI have written an ethereum smart-contract in the Solidity language. In order to test things, I can run a local node using Ganache and deploy my contract on it using `truffle migrate`.\n\n### requirements\n\nI want to test my contract using JavaScript. I want to create a *new* instance of my contract for each test.\n\n### what i've tried\n\nI created a test file `tests/test.js` in my project:\n\n```\nconst expect = require('chai').expect\n\nconst Round = artifacts.require('Round')\n\ncontract('pledgersLength1', async function(accounts) {\n it('1 pledger', async function() {\n let r = await Round.deployed()\n await r.pledge(5)\n let len = (await r.pledgersLength()).toNumber()\n expect(len).to.equal(1)\n })\n})\ncontract('pledgersLength2', async function(accounts) {\n it('2 pledgers', async function() {\n let r = await Round.deployed()\n await r.pledge(5)\n await r.pledge(6)\n let len = (await r.pledgersLength()).toNumber()\n expect(len).to.equal(2)\n })\n})\n```\n\nI run it with `truffle test`. It's basically Mocha, but truffle defines `artifacts` for you with a JavaScript connection to the smart contracts. \n\nThe truffle `contract` function is almost the same as Mocha's `describe` function, with a small change that I don't understand! I assumed that `contract` would make my contract new each time. It doesn't. Perhaps I can use something like `new Round()` instead of `Round.deployed()`, but I just don't know how.\n\nThe solution does not *have* to use truffle.\n\n========================================\n\nCode:\n```text\nconst expect = require('chai').expect\n\nconst Round = artifacts.require('Round')\n\n\ncontract('pledgersLength1', async function(accounts) {\n    it('1 pledger', async function() {\n        let r = await Round.deployed()\n        await r.pledge(5)\n        let len = (await r.pledgersLength()).toNumber()\n        expect(len).to.equal(1)\n    })\n})\ncontract('pledgersLength2', async function(accounts) {\n    it('2 pledgers', async function() {\n        let r = await Round.deployed()\n        await r.pledge(5)\n        await r.pledge(6)\n        let len = (await r.pledgersLength()).toNumber()\n        expect(len).to.equal(2)\n    })\n})\n```\n\n```text\ntruffle migrate\n```\n\n```text\ntests/test.js\n```\n\n```text\ntruffle test\n```\n\n```text\nartifacts\n```\n\n```text\ncontract\n```\n\n```text\ndescribe\n```\n\n```text\ncontract\n```\n\n```text\nnew Round()\n```\n\n```text\nRound.deployed()\n```\n\n```text\n// Path of this file: ./test/SimpleStorage.js\nvar simpleStorage = artifacts.require(\"./SimpleStorage.sol\");\n\ncontract('SimpleStorage', function(accounts) {\n\n  var contract_instance;\n\n  before(async function() {\n    contract_instance = await simpleStorage.new();\n  });\n\n  it(\"owner is the first account\", async function(){\n    var owner = await contract_instance.owner.call();\n    expect(owner).to.equal(accounts[0]);\n  });\n\n});\n```\n\n```text\n.new\n```\n\n```text\n.deployed\n```\n\n```text\n.new\n```\n\n```text\n.deployed\n```\n\n```text\ntruffle migrate\n```\n\n```text\n.new\n```\n\n========================================\n\nComments:\n- Are you sure it is not the same contract? On their site they claim that is will be a new contract instance in every `describe` function. How do you know that is the same instance?\n- Check this Twitter thread — twitter.com/zulhhandyplast/status/1026181801239171072\n- @nikosfotiadis I am sure. The way that I know is probably irrelevant to the question, but if you try to pledge the same amount twice, the contract will error. So in the example I typed above, I get an error when I expect to not get an error.\n- @ZulhilmiZainudin Yes, using `.new()` instead of `.deployed()` is working like a charm! That should really be added to the truffle documentation. Could you post it as an answer?\n- I'm glad it helped. I've posted my answer. Appreciate if you can upvote and accept it.\n- This is a great answer and clears the fog over `new()` and `deployed()`.","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":164,"estimatedTokens":1008}}319{"id":"stack-68716896","source":"stackoverflow","questionId":68716896,"title":"Python equivalent to Solidity u256","tags":["python","solidity","web3py"],"text":"Title: Python equivalent to Solidity u256\nTags: python, solidity, web3py\nSource: Stack Overflow\n\nQuestion:\nI am working on a Solidity Smart Contract. The idea is to automate some of the tasks using Python. So I have this code:\n\n```\nidx = 1\nevent_id = cDF.iloc[idx][\"A\"].astype(int)\nevent_date = cDF.iloc[idx][\"B\"].astype(int)\nx = cDF.iloc[idx][\"C\"].astype(int)\ny = cDF.iloc[idx][\"D\"].astype(int)\n\na = 69295\nprint(type(a))\nprint(type(event_id))\n\ntxcreation_txn = contract.functions.publishEvent(event_id, event_date, x, y).buildTransaction({\n 'from': , \n 'value': 0,\n 'gas': 3000000000000,\n 'gasPrice': w3.toWei('1', 'gwei'),\n 'nonce': nonce_var})\nsigned_txn = w3.eth.account.sign_transaction(txcreation_txn, private_key=private_key)\nresult = w3.eth.send_raw_transaction(signed_txn.rawTransaction)\nprint(f\"result # {idx} - {result.hex()}\")\n```\n\nfor which I get the following error:\n\n```\nCould not identify the intended function with name `publishEvent`, positional argument(s) of type \n`(, , , )` and keyword \nargument(s) of type `{}`.\nFound 1 function(s) with the name `publishEvent`: ['publishEvent(uint256,uint256,uint256,uint256)']\nFunction invocation failed due to no matching argument types.\n```\n\nHowever, it works and send the tx to the blockchain when I ran this manually:\n\n```\nbetcreation_txn = contract.functions.publishEvent(69295,1628516242331,24,28)\n.buildTransaction({'from': '0xDaf36E4570e2f0A587331b8E1E3645Ce8861B6A5', 'value': 0,\n'gas': 3000000,'gasPrice': w3.toWei('1', 'gwei'),'nonce': nonce_var})\n```\n\nthe function signature in Solidity:\n\n```\nfunction publishEvent(uint256 _event_id, uint256 _event_date, uint256 _x, uint256 _y) payable public\n```\n\nSo I guess the issue is that the data I am sending from Python is not compatible with Solidity u256. Is there any way to solve this?\n\n========================================\n\nCode:\n```text\nidx = 1\nevent_id = cDF.iloc[idx][\"A\"].astype(int)\nevent_date = cDF.iloc[idx][\"B\"].astype(int)\nx = cDF.iloc[idx][\"C\"].astype(int)\ny = cDF.iloc[idx][\"D\"].astype(int)\n\na = 69295\nprint(type(a))\nprint(type(event_id))\n\ntxcreation_txn = contract.functions.publishEvent(event_id, event_date, x, y).buildTransaction({\n    'from': <some_testing_wallet>, \n    'value': 0,\n    'gas': 3000000000000,\n    'gasPrice': w3.toWei('1', 'gwei'),\n    'nonce': nonce_var})\nsigned_txn = w3.eth.account.sign_transaction(txcreation_txn, private_key=private_key)\nresult = w3.eth.send_raw_transaction(signed_txn.rawTransaction)\nprint(f\"result # {idx} - {result.hex()}\")\n```\n\n```text\nCould not identify the intended function with name `publishEvent`, positional argument(s) of type \n`(<class 'numpy.int64'>, <class 'numpy.int64'>, <class 'numpy.int64'>, <class 'numpy.int64'>)` and keyword \nargument(s) of type `{}`.\nFound 1 function(s) with the name `publishEvent`: ['publishEvent(uint256,uint256,uint256,uint256)']\nFunction invocation failed due to no matching argument types.\n```\n\n```text\nbetcreation_txn = contract.functions.publishEvent(69295,1628516242331,24,28)\n.buildTransaction({'from': '0xDaf36E4570e2f0A587331b8E1E3645Ce8861B6A5', 'value': 0,\n'gas': 3000000,'gasPrice': w3.toWei('1', 'gwei'),'nonce': nonce_var})\n```\n\n```text\nfunction publishEvent(uint256 _event_id, uint256 _event_date, uint256 _x, uint256 _y) payable public\n```\n\n```py\nx = cDF.iloc[idx][\"C\"].astype(int).item()\ny = cDF.iloc[idx][\"D\"].astype(int).item()\n```\n\n```text\nx\n```\n\n```text\ny\n```\n\n```text\nint64\n```\n\n```text\nint\n```\n\n========================================\n\nComments:\n- `betcreation_txn = contract.functions.publishEvent(69295,1628516242331,24,28).b&zwnj;&#8203;uildTransaction({'fr&zwnj;&#8203;om': , 'value': 0,'gas': 3000000,'gasPrice': w3.toWei('1', 'gwei'),'nonce': nonce_var})` `signed_txn = w3.eth.account.sign_transaction(betcreation_txn, private_key=pk)` `result = w3.eth.send_raw_transaction(signed_txn.rawTransaction)` this is the code...this works with 'publishEvent(69295,1628516242331,24,28)'\n- Thanks a lot for the pointer...I am getting this error now... `TypeError: Unsupported type: ''. Must be one of: bool, str, bytes, bytearrayor int.`\n- @MartinRasumoff just gave it an edit, let me know how that works.\n- thanks a lot sir....no, it did not...it is converting it as strings now: `ValidationError: Could not identify the intended function with name `publishEvent`, positional argument(s) of type `(, , , )` and keyword argument(s) of type `{}`. Found 1 function(s) with the name `publishEvent`: ['publishEvent(uint256,uint256,uint256,uint256)'] Function invocation failed due to no matching argument types.` have been working on this for 2 days now :( thanks for any pointer...\n- @MartinRasumoff try giving that answer a go, get rid of the toHex lines, and just use this `x` and `y`\n- YES!!!!! now I am getting a gas error but at least not the data type!!!! Thanks a lot sir!!!!!\n- @MartinRasumoff :) happy coding, Solidity / Python / Numpy data types are a bit of a headache to deal with sometimes.","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":129,"estimatedTokens":1235}}320{"id":"stack-76068568","source":"stackoverflow","questionId":76068568,"title":"Solidity: Functions that require a return value it doesn't return anything but still work","tags":["ethereum","solidity","uniswap"],"text":"Title: Solidity: Functions that require a return value it doesn't return anything but still work\nTags: ethereum, solidity, uniswap\nSource: Stack Overflow\n\nQuestion:\nI was reading some functions of UniswapV2Router and I face the following code:\n\n```\nfunction swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n external\n virtual\n override\n payable\n ensure(deadline)\n returns (uint[] memory amounts)\n {\n require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');\n amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);\n require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');\n IWETH(WETH).deposit{value: amounts[0]}();\n assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n _swap(amounts, path, to);\n }\n```\n\nThe function return `uint[] memory amounts` but actually there is no return in the body. Can you explain me what I miss?\n\nI was expecting to see this variable declared somewhere but I still didn't see it anywhere.\n\n========================================\n\nCode:\n```js\nfunction swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        virtual\n        override\n        payable\n        ensure(deadline)\n        returns (uint[] memory amounts)\n    {\n        require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');\n        amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);\n        require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');\n        IWETH(WETH).deposit{value: amounts[0]}();\n        assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n        _swap(amounts, path, to);\n    }\n```\n\n```text\nuint[] memory amounts\n```\n\n```text\nreturns (uint[] memory amounts)\n```\n\n```text\namounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);\n```\n\n```text\nfunction foo() external pure returns (uint256 number) {\n    number = 100;\n    // TODO rest of your function\n}\n```\n\n```text\nfunction foo() external pure returns (uint256) {\n    uint256 number = 100;\n    // TODO rest of your function\n    return number;\n}\n```\n\n```text\namounts\n```\n\n```text\namounts\n```\n\n```text\namounts\n```\n\n```text\nreturn\n```\n\n```text\nreturn\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":96,"estimatedTokens":584}}321{"id":"stack-73545153","source":"stackoverflow","questionId":73545153,"title":"\"Transaction reverted: trying to deploy a contract whose code is too large\", Is 10KB too large?","tags":["unit-testing","ethereum","solidity","hardhat","contract"],"text":"Title: \"Transaction reverted: trying to deploy a contract whose code is too large\", Is 10KB too large?\nTags: unit-testing, ethereum, solidity, hardhat, contract\nSource: Stack Overflow\n\nQuestion:\nI wrote a simple auction contract file and its size is 9.49KB(12KB on disk), and when I run this contract using `npx hardhat test`, I get this error:\n\n```\nError: cannot estimate gas; transaction may fail or may require manual gas limit [ See: https://links.ethers.org/v5-errors-UNPREDICTABLE_GAS_LIMIT ] (reason=\"Transaction reverted: trying to deploy a contract whose code is too large\", method=\"estimateGas\", transaction={\"from\":\"0xf39Fd6e...\n```\n\nI think this error occurs when the contract files exceeds more than 24,576 bytes, which means 24KB.\nBut my file exceeds only 10Kbs and I can't downsize my code anymore.\nWhat should I do?\n\n========================================\n\nCode:\n```text\nError: cannot estimate gas; transaction may fail or may require manual gas limit [ See: https://links.ethers.org/v5-errors-UNPREDICTABLE_GAS_LIMIT ] (reason=\"Transaction reverted: trying to deploy a contract whose code is too large\", method=\"estimateGas\", transaction={\"from\":\"0xf39Fd6e...\n```\n\n```text\nnpx hardhat test\n```\n\n========================================\n\nComments:\n- Be careful though, you may have the problem when you attempt to deploy to an actual network. One thing that will add a lot of size to a contract is any use of the 'new' function inside a contract function. It will bloat the size of the contract that calls new with the size of the contract that is created inside of it. You will not be able overcome the problem by ignoring it, which you can do in ahrdhat but not an a actual network. Also when you say the contract is 10K in size, do you mean the .sol file? That's not what is being measured. Its the size of the compiled bytecode.","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":30,"estimatedTokens":463}}322{"id":"stack-70479339","source":"stackoverflow","questionId":70479339,"title":"Can chainlink external adapters be made so they can only called by a specific smart contract?","tags":["encryption","ethereum","solidity","chainlink"],"text":"Title: Can chainlink external adapters be made so they can only called by a specific smart contract?\nTags: encryption, ethereum, solidity, chainlink\nSource: Stack Overflow\n\nQuestion:\nI want to make an external adapter which can only be called by a specific function in a smart contract so that I can assure that the caller is an authorized address. Is anyone able to make a call to an external adapter or can I restrict it to a certain smart contract? If anyone is able to make a call, is there a way for me to ensure that the caller is from the smart contract?\n\nWhat I am trying to do is to have a smart contract which can provide a decryption key for a file.\nEssentially, the smart contract would store a decryption key encrypted to the adapter's public key. Then, when an event in the smart contract occurs where someone should gain access to the file, the smart contract makes a call to the adapter. The adapter would then take the encrypted decryption key, decrypt it, and return the decryption key encrypted to the recipient's public key. The smart contract would then receive the decryption key encrypted to the recipient's public key and store this so that the recipient could use this to decrypt the file. Is something like this possible with an external adapter?\n\n========================================\n\nTop Answer:\nIf whitelisting addresses doesn't do the trick, I believe you can do the following to the oracle contract:\n\n```\n/**\n * @notice Creates the Chainlink request. This is a backwards compatible API\n * with the Oracle.sol contract, but the behavior changes because\n * callbackAddress is assumed to be the same as the request sender.\n * @param callbackAddress The consumer of the request\n * @param payment The amount of payment given (specified in wei)\n * @param specId The Job Specification ID\n * @param callbackAddress The address the oracle data will be sent to\n * @param callbackFunctionId The callback function ID for the response\n * @param nonce The nonce sent by the requester\n * @param dataVersion The specified data version\n * @param data The extra request parameters\n */\n function oracleRequest(\n address sender,\n uint256 payment,\n bytes32 specId,\n address callbackAddress,\n bytes4 callbackFunctionId,\n uint256 nonce,\n uint256 dataVersion,\n bytes calldata data\n ) external override validateFromLINK validateIsAuthorizedConsumer(sender) {\n revert(\"use the operatorRequest only\");\n }\n\n /**\n * @notice Creates the Chainlink request\n * @dev Stores the hash of the params as the on-chain commitment for the request.\n * Emits OracleRequest event for the Chainlink node to detect.\n * @param sender The sender of the request\n * @param payment The amount of payment given (specified in wei)\n * @param specId The Job Specification ID\n * @param callbackFunctionId The callback function ID for the response\n * @param nonce The nonce sent by the requester\n * @param dataVersion The specified data version\n * @param data The extra request parameters\n */\n function operatorRequest(\n address sender,\n uint256 payment,\n bytes32 specId,\n bytes4 callbackFunctionId,\n uint256 nonce,\n uint256 dataVersion,\n bytes calldata data\n ) external override validateIsAuthorizedConsumer(sender) validateFromLINK {\n (\n bytes32 requestId,\n uint256 expiration\n ) = _verifyAndProcessOracleRequest(\n sender,\n payment,\n sender,\n callbackFunctionId,\n nonce,\n dataVersion\n );\n emit OracleRequest(\n specId,\n sender,\n requestId,\n payment,\n sender,\n callbackFunctionId,\n expiration,\n dataVersion,\n data\n );\n }\n```\n\nI removed the `oracleRequest()` function because it exceeds stack size by adding more modifiers to it and since I can use `operatorRequest()` to fulfill both multi-word and single-word requests I will make that method deprecated by reverting everytime it's called.\n\nThe modifier that sets the authorized consumer is basically the following:\n\n```\n/**\n * @dev function used to change the authorized consumer. Can only be set once\n */\n function setAuthorizedConsumer(address _consumer) public onlyOwner {\n require(\n authorizedConsumer == address(0),\n \"authorized consumer is already set\"\n );\n authorizedConsumer = _consumer;\n }\n\n /**\n * @notice validates the consumer is an authorized consumer\n */\n function _validateIsAuthorizedConsumer(address _consumer) internal view {\n require(_consumer == authorizedConsumer, \"Not authorized sender\");\n }\n\n /**\n * @notice prevents non-authorized addresses from calling this method\n */\n modifier validateIsAuthorizedConsumer(address _consumer) {\n _validateIsAuthorizedConsumer(_consumer);\n _;\n }\n```\n\n========================================\n\nCode:\n```js\n/**\n     * @notice Creates the Chainlink request. This is a backwards compatible API\n     * with the Oracle.sol contract, but the behavior changes because\n     * callbackAddress is assumed to be the same as the request sender.\n     * @param callbackAddress The consumer of the request\n     * @param payment The amount of payment given (specified in wei)\n     * @param specId The Job Specification ID\n     * @param callbackAddress The address the oracle data will be sent to\n     * @param callbackFunctionId The callback function ID for the response\n     * @param nonce The nonce sent by the requester\n     * @param dataVersion The specified data version\n     * @param data The extra request parameters\n     */\n    function oracleRequest(\n        address sender,\n        uint256 payment,\n        bytes32 specId,\n        address callbackAddress,\n        bytes4 callbackFunctionId,\n        uint256 nonce,\n        uint256 dataVersion,\n        bytes calldata data\n    ) external override validateFromLINK validateIsAuthorizedConsumer(sender) {\n        revert(\"use the operatorRequest only\");\n    }\n\n    /**\n     * @notice Creates the Chainlink request\n     * @dev Stores the hash of the params as the on-chain commitment for the request.\n     * Emits OracleRequest event for the Chainlink node to detect.\n     * @param sender The sender of the request\n     * @param payment The amount of payment given (specified in wei)\n     * @param specId The Job Specification ID\n     * @param callbackFunctionId The callback function ID for the response\n     * @param nonce The nonce sent by the requester\n     * @param dataVersion The specified data version\n     * @param data The extra request parameters\n     */\n    function operatorRequest(\n        address sender,\n        uint256 payment,\n        bytes32 specId,\n        bytes4 callbackFunctionId,\n        uint256 nonce,\n        uint256 dataVersion,\n        bytes calldata data\n    ) external override validateIsAuthorizedConsumer(sender) validateFromLINK {\n        (\n            bytes32 requestId,\n            uint256 expiration\n        ) = _verifyAndProcessOracleRequest(\n                sender,\n                payment,\n                sender,\n                callbackFunctionId,\n                nonce,\n                dataVersion\n            );\n        emit OracleRequest(\n            specId,\n            sender,\n            requestId,\n            payment,\n            sender,\n            callbackFunctionId,\n            expiration,\n            dataVersion,\n            data\n        );\n    }\n```\n\n```js\n/**\n     * @dev function used to change the authorized consumer. Can only be set once\n     */\n    function setAuthorizedConsumer(address _consumer) public onlyOwner {\n        require(\n            authorizedConsumer == address(0),\n            \"authorized consumer is already set\"\n        );\n        authorizedConsumer = _consumer;\n    }\n\n    /**\n     * @notice validates the consumer is an authorized consumer\n     */\n    function _validateIsAuthorizedConsumer(address _consumer) internal view {\n        require(_consumer == authorizedConsumer, \"Not authorized sender\");\n    }\n\n    /**\n     * @notice prevents non-authorized addresses from calling this method\n     */\n    modifier validateIsAuthorizedConsumer(address _consumer) {\n        _validateIsAuthorizedConsumer(_consumer);\n        _;\n    }\n```\n\n```text\noracleRequest()\n```\n\n```text\noperatorRequest()\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":231,"estimatedTokens":2000}}323{"id":"stack-73059934","source":"stackoverflow","questionId":73059934,"title":"jnius.JavaException: JVM exception occurred: exceeded maximum","tags":["python","java","ethereum","solidity","hedera-hashgraph"],"text":"Title: jnius.JavaException: JVM exception occurred: exceeded maximum\nTags: python, java, ethereum, solidity, hedera-hashgraph\nSource: Stack Overflow\n\nQuestion:\nI am creating a DApp on the Hedera Blockchain using Hedera-sdk-py, a python wrapper of Hedera SDK in Java. I keep getting *JVM exception occurred: exceeded maximum attempts for request with the last exception being com.hedera.hashgraph.sdk.MaxAttemptsExceededException* each time I try to create an account. The error occurs at: *resp = tran.setKey(newPublicKey).setInitialBalance(Hbar(2)).execute(client).* Any help will be appreciated as I have tried repeatedly without success to fix it.\n\n```\nfrom hedera import (\n Hbar,\n PrivateKey,\n AccountCreateTransaction,\n)\nfrom get_client import client\n\n# Generate a Ed25519 private, public key pair\nnewKey = PrivateKey.generate()\nnewPublicKey = newKey.getPublicKey()\n\nprint(\"private key = \", newKey.toString())\nprint(\"public key = \", newPublicKey.toString())\n\ntran = AccountCreateTransaction()\n# need a certain number of hbars, otherwise it can not be deleted later\nresp = tran.setKey(newPublicKey).setInitialBalance(Hbar(2)).execute(client)\nreceipt = resp.getReceipt(client)\nprint(\"account = \", receipt.accountId.toString()\n```\n\n========================================\n\nCode:\n```text\nfrom hedera import (\n    Hbar,\n    PrivateKey,\n    AccountCreateTransaction,\n)\nfrom get_client import client\n\n# Generate a Ed25519 private, public key pair\nnewKey = PrivateKey.generate()\nnewPublicKey = newKey.getPublicKey()\n\nprint(\"private key = \", newKey.toString())\nprint(\"public key = \", newPublicKey.toString())\n\ntran = AccountCreateTransaction()\n# need a certain number of hbars, otherwise it can not be deleted later\nresp = tran.setKey(newPublicKey).setInitialBalance(Hbar(2)).execute(client)\nreceipt = resp.getReceipt(client)\nprint(\"account = \",  receipt.accountId.toString()\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":53,"estimatedTokens":469}}324{"id":"stack-52436491","source":"stackoverflow","questionId":52436491,"title":"how to make contract fetch ether from an account","tags":["ethereum","solidity","smartcontracts","ether"],"text":"Title: how to make contract fetch ether from an account\nTags: ethereum, solidity, smartcontracts, ether\nSource: Stack Overflow\n\nQuestion:\nI am new to solidity. I was playing around and wanted to know if I could make a contract fetch ether from one account and transfer it to another account.\nThank You\n\n========================================\n\nTop Answer:\nUnless the account you are retrieving the ether from is also a contract and provides a method allowing ether withdrawal, this is not possible. A contract cannot autonomously retrieve ether from a externally owned account.\n\nAn alternative is to move your ether to the Wrapped Ether (WETH) contract, which provides you an ether-backed ERC20 token instead, which then gives you access to `approve()` and `transferFrom()`\n\n========================================\n\nCode:\n```text\napprove()\n```\n\n```text\ntransferFrom()\n```\n\n========================================\n\nComments:\n- Maybe this can give you some ideas ethereum.stackexchange.com/q/28233/26362\n- @ZulhilmiZainudin The link was helpful thank you. But I don't want any of my contracts to store the ether values.\n- Thank you for your answer. Can you tell me more about pre-signed transaction.\n- Take a look at this article. The basic idea is that a transaction is simply a signed message that is broadcasted to the ETH network. A pre-signed transaction is that same transaction that hasn't yet been broadcast to the network.","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":33,"estimatedTokens":358}}325{"id":"stack-53595223","source":"stackoverflow","questionId":53595223,"title":"Error Whilst running Solidity with Python(py-solc)","tags":["python-3.x","solidity"],"text":"Title: Error Whilst running Solidity with Python(py-solc)\nTags: python-3.x, solidity\nSource: Stack Overflow\n\nQuestion:\nI have been running my code which involves deployment of smart contract to Ethereum Ropsten network. I ran this successfully for some time but last week did installed another software after which I started getting these errors:\n`command: solc --combined-json abi,asm,ast,bin,bin-runtime,clone-bin,devdoc,interface,opcodes,userdoc\nreturn code: 1\nstderr:\nstdout:\nInvalid option to --combined-json: clone-bin`\n\nI have no clue why I'm getting them. Anyone can help?\n\n========================================\n\nCode:\n```text\ncommand: solc --combined-json abi,asm,ast,bin,bin-runtime,clone-bin,devdoc,interface,opcodes,userdoc\nreturn code: 1\nstderr:\nstdout:\nInvalid option to --combined-json: clone-bin\n```\n\n```text\npy-solc\n```\n\n```text\nversion 0.4.25\n```\n\n```text\nSOLC_BINARY\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":36,"estimatedTokens":223}}326{"id":"stack-52685530","source":"stackoverflow","questionId":52685530,"title":"How to deploy multiple solidity smart contracts that uses functions of each other?","tags":["blockchain","ethereum","solidity","smartcontracts","truffle"],"text":"Title: How to deploy multiple solidity smart contracts that uses functions of each other?\nTags: blockchain, ethereum, solidity, smartcontracts, truffle\nSource: Stack Overflow\n\nQuestion:\nI have three smart contracts say a.sol, b.sol and c.sol... Out of these three, first two are independent smart contracts whereas c.sol uses the functions of a.sol and b.sol and thus c.sol requires to \"import\" the first two smart contracts. \"Import\" works locally but how to deploy all of them via remix/truffle on testnet such that c.sol can still access the functions of a.sol and b.sol?\n\n========================================\n\nTop Answer:\nIf your project was created with Truffle, you can set up `c.sol` in the following way:\n\n```\nimport \"./a.sol\";\nimport \"./b.sol\";\n\ncontract c is a, b {\n ...\n}\n```\n\nIf this is the structure of your code, you will be able to deploy your Truffle project using `truffle migrate` (provided your migrations are set up correctly).\n\n========================================\n\nCode:\n```text\ncontract A {\n  function doSomething() {\n        ...\n  }\n}\n```\n\n```text\ncontract C {\n  A a;\n\n  function setA(address addressOfContractA) {\n    a = A(address);\n  }\n\n  function makeADoSomething() {\n    a.doSomething();\n  }\n}\n```\n\n```text\nimport \"./a.sol\";\nimport \"./b.sol\";\n\ncontract c is a, b {\n   ...\n}\n```\n\n```text\nc.sol\n```\n\n```text\ntruffle migrate\n```\n\n========================================\n\nComments:\n- This answer only works for as long as the total size does not exceed block size limit. To avoid hitting block size limit, @bhoomtawath-plinsut 's answer works.","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":69,"estimatedTokens":395}}327{"id":"stack-71589805","source":"stackoverflow","questionId":71589805,"title":"Declaration Error: Undeclared identifier Solidity","tags":["solidity"],"text":"Title: Declaration Error: Undeclared identifier Solidity\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI am new to Solidity. I am using an interface and a library for an exercise in Solidity. The contract must implement the methods from the interface, with the help of the functions from the library. I get a Declaration Error: Undeclared identifier for mapPerson and mapCompany. Where do I go wrong? I have tried to put the structs in the library, but then I get other errors, because of the logic I have implemented. Here is my code:\n\n```\n//SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.7.0;\n\nstruct Person{\n address addr;\n string name;\n string surname;\n}\n\nstruct Company{\n address addr;\n string name;\n}\n\ninterface Interface{\n\n function addPerson(address addr, string memory name, string memory surname) external;\n \n function addCompany(address addr, string memory name) external;\n\n function getPerson() external view returns (address addr);\n\n function getCompany() external view returns (address addr);\n}\n \n\nlibrary Lib{\n\n function addPerson(address addr, string memory name, string memory surname) public{\n addr = msg.sender;\n mapPerson[addr] = Person(name, surname, addr);\n }\n\n function addCompany(address addr, string memory name) public{\n addr = msg.sender;\n mapCompany[addr] = Company(addr, name);\n } \n}\n\ncontract Lab03 is Interface{\n\n Person p;\n Company c;\n\n mapping(address => Person) mapPerson;\n mapping(address => Company) mapCompany;\n\n function addPerson(address addr, string memory name, string memory surname) public override {\n Lib.addPerson(addr, name, surname);\n emit addPersonEvent(addr, name, surname);\n }\n\n function addCompany(address addr, string memory name) public override{\n Lib.addCompany(addr, name);\n emit addCompanyEvent(addr, name);\n }\n\n function getPerson() public override view returns (address addr) {\n return p.addr;\n }\n\n function getCompany() public override view returns (address addr) {\n return c.addr;\n }\n\n event addPersonEvent(address addr, string name, string surname);\n event addCompanyEvent(address addr, string name);\n}\n```\n\n========================================\n\nTop Answer:\nThese lines should be outside of the structs (`Person`, `Company`):\n\n```\nmapping(address => Person) mapPerson;\n\nmapping(address => Company) mapCompany;\n```\n\nlike :\n\n```\nstruct Person{\n address addr;\n string name;\n string surname;\n}\nmapping(address => Person) mapPerson;\n```\n\n========================================\n\nCode:\n```text\n//SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.7.0;\n\nstruct Person{\n    address addr;\n    string name;\n    string surname;\n}\n\nstruct Company{\n    address addr;\n    string name;\n}\n\n\ninterface Interface{\n\n    function addPerson(address addr, string memory name, string memory surname) external;\n    \n    function addCompany(address addr, string memory name) external;\n\n    function getPerson() external view returns (address addr);\n\n    function getCompany() external view returns (address addr);\n}\n    \n\nlibrary Lib{\n\n\n    function addPerson(address addr, string memory name, string memory surname) public{\n        addr = msg.sender;\n        mapPerson[addr] = Person(name, surname, addr);\n    }\n\n    function addCompany(address addr, string memory name) public{\n        addr = msg.sender;\n        mapCompany[addr] = Company(addr, name);\n    }     \n}\n\ncontract Lab03 is Interface{\n\n    Person p;\n    Company c;\n\n    mapping(address => Person) mapPerson;\n    mapping(address => Company) mapCompany;\n\n    function addPerson(address addr, string memory name, string memory surname) public override {\n        Lib.addPerson(addr, name, surname);\n        emit addPersonEvent(addr, name, surname);\n    }\n\n    function addCompany(address addr, string memory name) public override{\n        Lib.addCompany(addr, name);\n        emit addCompanyEvent(addr, name);\n    }\n\n    function getPerson() public override view returns (address addr) {\n        return p.addr;\n    }\n\n    function getCompany() public override view returns (address addr) {\n        return c.addr;\n    }\n\n    event addPersonEvent(address addr, string name, string surname);\n    event addCompanyEvent(address addr, string name);\n}\n```\n\n```text\ncontract Lab03 is Interface{\n    // Add here the mappings and remove them from the struct\n    mapping(address => Person) mapPerson;\n    mapping(address => Company) mapCompany;\n\n    Person p;\n    Company c;\n ...\n```\n\n```text\n//SPDX-License-Identifier: UNLICENSED\n\npragma solidity ^0.7.0;\n\nstruct Person{\n    address addr;\n    string name;\n    string surname;\n}\n\nstruct Company{\n    address addr;\n    string name;\n}\n\n\ninterface Interface{\n\n    function addPerson(address addr, string memory name, string memory surname) external;\n    \n    function addCompany(address addr, string memory name) external;\n\n    function getPerson(address addrFind) external view returns (address addr);\n\n    function getCompany(address addrFind) external view returns (address addr);\n}\n    \n\nlibrary Lib{\n    // define struct with mapping\n    struct LibPerson {\n        mapping(address => Person) mapPerson;\n    }\n\n    struct LibCompany {\n        mapping(address => Company) mapCompany;\n    }\n\n    function addPerson(LibPerson storage lp, address addr, string memory name, string memory surname) public{\n        addr = msg.sender;\n        lp.mapPerson[addr] = Person(addr, name, surname);\n    }\n\n    function addCompany(LibCompany storage lc, address addr, string memory name) public{\n        addr = msg.sender;\n        lc.mapCompany[addr] = Company(addr, name);\n    }    \n\n    function getCompany(LibCompany storage lc, address addrFind) view external returns(address){\n        return lc.mapCompany[addrFind].addr;\n    }   \n\n    function getPerson(LibPerson storage lp, address addrFind) view external returns(address){\n        return lp.mapPerson[addrFind].addr;\n    }     \n}\n\ncontract Lab03 is Interface{\n    // define state variable for two struct present in the library\n    Lib.LibPerson libP;\n    Lib.LibCompany libC;\n    Person p;\n    Company c;\n\n    function addPerson(address addr, string memory name, string memory surname) public override {\n        Lib.addPerson(libP, addr, name, surname);\n        emit addPersonEvent(addr, name, surname);\n    }\n\n    function addCompany(address addr, string memory name) public override{\n        Lib.addCompany(libC, addr, name);\n        emit addCompanyEvent(addr, name);\n    }\n\n    function getPerson(address _addressFind) public override view returns (address addr) {\n        return Lib.getPerson(libP, _addressFind);\n    }\n\n    function getCompany(address _addressFind) public override view returns (address addr) {\n        return Lib.getCompany(libC, _addressFind);\n    }\n\n    event addPersonEvent(address addr, string name, string surname);\n    event addCompanyEvent(address addr, string name);\n}\n```\n\n```text\nmapPerson\n```\n\n```text\nmap Company\n```\n\n```text\nmapping(address => Person) mapPerson;\n\nmapping(address => Company) mapCompany;\n```\n\n```text\nstruct Person{\n    address addr;\n    string name;\n    string surname;\n}\nmapping(address => Person) mapPerson;\n```\n\n```text\nPerson\n```\n\n```text\nCompany\n```\n\n========================================\n\nComments:\n- I've updated the post, I moved them into the contract, but that doesn't solve my problem.\n- I already did that, still the same problem..\n- Please update the code with this last modify\n- It is updated now","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":315,"estimatedTokens":1842}}328{"id":"stack-66819732","source":"stackoverflow","questionId":66819732,"title":"State Variables in Storage: \"lower-order aligned\" What does this sentence in the docs mean?","tags":["solidity"],"text":"Title: State Variables in Storage: \"lower-order aligned\" What does this sentence in the docs mean?\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI am new to solidity and am trying to understand this sentence in the docs covering state variables in storage.\n\nhttps://docs.soliditylang.org/en/latest/internals/layout_in_storage.html#layout-of-state-variables-in-storage\n\nA bullet item says the following:\n\nThe first item in a storage slot is stored lower-order aligned.\n\nWhat does this mean exactly?\n\n========================================\n\nCode:\n```text\nassembly\n```\n\n========================================\n\nComments:\n- Thank you! Just happens that I am reading about this now. Thanks for the help.","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":26,"estimatedTokens":176}}329{"id":"stack-70447003","source":"stackoverflow","questionId":70447003,"title":"How do I input the parameter with bytes4 type in Remix?","tags":["solidity","remix"],"text":"Title: How do I input the parameter with bytes4 type in Remix?\nTags: solidity, remix\nSource: Stack Overflow\n\nQuestion:\nI created a simple contract as blow shows. When I deployed it and try to call `get` function, I found that I couldn't input the correct parameter with `bytes4` type. No matter I used `0x01,11,\"11\"...`, it always told that error encoding argument like this.\n\ntransact to Test.get errored: Error encoding arguments: Error: invalid arrayify value (argument=\"value\" value=\"11\" code=INVALID_ARGUMENT version=bytes/5.5.0)\n\ntransact to Test.get errored: Error encoding arguments: Error: invalid arrayify value (argument=\"value\" value=\"0x6162\" code=INVALID_ARGUMENT version=bytes/5.5.0)\n\nWhat should I do ?\n\n```\npragma solidity ^0.4.0;\n\ncontract Test {\n mapping (bytes8 => string) public map;\n function setMapping() public {\n map[\"k1\"] = \"yes\";\n }\n function get(bytes4 a) public {\n \n }\n}\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.0;\n\ncontract Test {\n    mapping (bytes8 => string) public  map;\n    function setMapping() public {\n        map[\"k1\"] = \"yes\";\n    }\n    function get(bytes4 a) public {\n        \n    }\n}\n```\n\n```text\nget\n```\n\n```text\nbytes4\n```\n\n```text\n0x01,11,\"11\"...\n```\n\n```text\n0x12345678\n```\n\n```text\nbytes4\n```\n\n```text\n12\n```\n\n```text\n34\n```\n\n```text\n00\n```\n\n```text\n0x00340078\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":79,"estimatedTokens":338}}330{"id":"stack-68632466","source":"stackoverflow","questionId":68632466,"title":"How to check transfer of eth from an address to smart contract","tags":["ethereum","solidity","smartcontracts"],"text":"Title: How to check transfer of eth from an address to smart contract\nTags: ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nIf i have a function like this:\n\n```\nfunction sendToAuthor (uint tokenId) public payable{\n\n //here I want to get some ether from the msg.sender, store it in a \n mapping and send it to another address (author). \n\n}\n```\n\nWhat I don't understand is how to check if the msg.sender gave the smart contract the money or not. If I can check that, I can take the msg.value from the mapping and send it to the author, but how do I check that the sender actually made the eth transfer to the contract?\n\n========================================\n\nTop Answer:\npsuedocode:\n\n```\ncontract someContract {\n address author = \"0x00...\";\n mapping (address => uint) public sentToAuthor;\n function sendToAuthor () public payable {\n sentToAuthor[msg.sender] = msg.value;\n author.call{value: msg.value}(\"\");\n }\n}\n```\n\nYour question doesn't really make sense.\n\nWhat I don't understand is how to check if the msg.sender gave the smart contract the money or not.\n\nYou just look at the value of `msg.value`. If the transaction doesn't revert, and the function is payable, and you don't send it anywhere else, then your contract receives those funds. Period. No \"checking\" needed. If you do want to check, you could on the client side, but just looking at the contract balance (e.g., `ethers.utils.balanceOf(contractAddress)`, or something). You could also just look at the mapping here, it will be correct and show you.\n\nIf I can check that, I can take the msg.value from the mapping and send it to the author, but how do I check that the sender actually made the eth transfer to the contract?\n\nThe \"msg.value\" won't actually be \"in\" the mapping, mappings can't actually hold eth, they can only hold a uint. It just tells you how much was sent to the contract.\n\nBtw, as written here, it sends it straight to the author, so it won't stay in the contract. If you remove the last line of \"sendToAuthor\" (the `author.call` line), then the eth will just stay in the contract itself, instead.\n\n(btw, there's an ethereum stackoverflow, you should be asking there.)\n\n========================================\n\nCode:\n```text\nfunction sendToAuthor (uint tokenId) public payable{\n\n  //here I want to get some ether from the msg.sender, store it in a \n  mapping and send it to another address (author). \n\n}\n```\n\n```text\nmsg.value\n```\n\n```text\npayable\n```\n\n```text\ncontract someContract {\n  address author = \"0x00...\";\n  mapping (address => uint) public sentToAuthor;\n  function sendToAuthor () public payable {\n    sentToAuthor[msg.sender] = msg.value;\n    author.call{value: msg.value}(\"\");\n  }\n}\n```\n\n```text\nmsg.value\n```\n\n```text\nethers.utils.balanceOf(contractAddress)\n```\n\n```text\nauthor.call\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":90,"estimatedTokens":702}}331{"id":"stack-51971413","source":"stackoverflow","questionId":51971413,"title":"How to implement self destruct pattern in Solidity?","tags":["ethereum","solidity"],"text":"Title: How to implement self destruct pattern in Solidity?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nHi I am working on the auction app in block chain using solidity as smart contract in `Ethereum`. The requirements are\n\n- The DAPP will ask for the auction in the public domain like for example selling an iPhone\n\n- All the users will bid for the item\n\n- The smart contract will find the winner based on the highest money and declare him as the winner.\n\nI want to add another functionality by `self destructing` the auction after specified amount of time and no other auction will take place after that.\n\nHow can we do this in solidity?\n\nAny help would be really appreciated.Thanks!\n\n========================================\n\nCode:\n```text\nEthereum\n```\n\n```text\nself destructing\n```\n\n```text\nrequire(block.timestamp > auction.endTime, \"Auction is closed.\");\n```\n\n```text\nblock.timestamp\n```\n\n========================================\n\nComments:\n- so the value auction.endTime can be set from a timer or a predefined end time?\n- It can be either hardcoded (which you probably do not want to do) or can be set with a transaction, which creates or updates auction. Typically you either set it to block.timestamp during call or pass desired time as parameter to your method.","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":43,"estimatedTokens":322}}332{"id":"stack-65622958","source":"stackoverflow","questionId":65622958,"title":"How to use RNS domains with non-fungible token standards? (such as ERC721)","tags":["dns","subdomain","solidity","smartcontracts","rsk"],"text":"Title: How to use RNS domains with non-fungible token standards? (such as ERC721)\nTags: dns, subdomain, solidity, smartcontracts, rsk\nSource: Stack Overflow\n\nQuestion:\nI have registered a `.rsk` domain using RNS,\nand am wondering if I can transfer ownership of it to other accounts,\nlike an NFT.\n\nIs this possible with domains and subdomains? If so how?\n\n========================================\n\nCode:\n```text\n.rsk\n```\n\n```text\ncontract FIFSRegistrar is FIFSRegistrarBase, PricedContract {\n```\n\n```text\nNodeOwner nodeOwner;\n```\n\n```text\ncontract NodeOwner is ERC721, Ownable, AbstractNodeOwner {\n```\n\n```text\nuint256 tokenId = uint256(label);\n```\n\n```text\nFIFSRegistrar\n```\n\n```text\nFIFSRegistrarBase\n```\n\n```text\nNodeOwner\n```\n\n```text\nERC721\n```\n\n```text\ntokenId\n```\n\n```text\nFIFSRegistrarBase\n```\n\n```text\nFIFSRegistrar.sol#L9\n```\n\n```text\nNodeOwner\n```\n\n```text\nFIFSRegistrarBase.sol#L27\n```\n\n```text\nERC721\n```\n\n```text\nNodeOwner.sol#L9\n```\n\n```text\ntokenId\n```\n\n```text\nNodeOwner.sol#L113\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":18,"totalLines":85,"estimatedTokens":250}}333{"id":"stack-67142347","source":"stackoverflow","questionId":67142347,"title":"Access to inherited variable in solidity to overwrite it","tags":["solidity"],"text":"Title: Access to inherited variable in solidity to overwrite it\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI want to override the following inherited function:\n\n```\nfunction _setBaseURI(string memory baseURI) public override(ERC721Full, ERC721Metadata) {\n _baseURI = baseURI;\n}\n```\n\nThe problem is that I get an error\n\nUndeclared Identifier\n\nwith `_baseURI`.\n\nThe variable was implemented private. Is it for that reason that it cannot be overwritten? And if so, why can the function be?\n\nMy contract:\n\n```\npragma solidity ^0.6.0;\n\nimport \"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0-beta.0/contracts/token/ERC721/ERC721Full.sol\";\nimport \"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0-beta.0/contracts/drafts/Counters.sol\";\n\ncontract GameItem is ERC721Full {\n using Counters for Counters.Counter;\n Counters.Counter private _tokenIds;\n\n constructor() ERC721Full(\"GameItem\", \"ITM\") public {\n }\n\n function awardItem(address player, string memory tokenURI) public returns (uint256) {\n _tokenIds.increment();\n\n uint256 newItemId = _tokenIds.current();\n _mint(player, newItemId);\n _setTokenURI(newItemId, tokenURI);\n\n return newItemId;\n }\n \n function _setBaseURI(string memory baseURI) public override(ERC721Full, ERC721Metadata) {\n _baseURI = baseURI;\n }\n}\n```\n\nThe Heritage\n\n```\npragma solidity ^0.6.0;\n\nimport \"../../GSN/Context.sol\";\nimport \"./ERC721.sol\";\nimport \"./IERC721Metadata.sol\";\nimport \"../../introspection/ERC165.sol\";\n\ncontract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Base URI\n string private _baseURI;\n\n // Optional mapping for token URIs\n mapping(uint256 => string) private _tokenURIs;\n\n /*\n * bytes4(keccak256('name()')) == 0x06fdde03\n * bytes4(keccak256('symbol()')) == 0x95d89b41\n * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd\n *\n * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f\n */\n bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;\n\n /**\n * @dev Constructor function\n */\n constructor (string memory name, string memory symbol) public {\n _name = name;\n _symbol = symbol;\n\n // register the supported interfaces to conform to ERC721 via ERC165\n _registerInterface(_INTERFACE_ID_ERC721_METADATA);\n }\n\n /**\n * @dev Gets the token name.\n * @return string representing the token name\n */\n function name() external view override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Gets the token symbol.\n * @return string representing the token symbol\n */\n function symbol() external view override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the URI for a given token ID. May return an empty string.\n *\n * If the token's URI is non-empty and a base URI was set (via\n * {_setBaseURI}), it will be added to the token ID's URI as a prefix.\n *\n * Reverts if the token ID does not exist.\n */\n function tokenURI(uint256 tokenId) external view override returns (string memory) {\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\n\n string memory _tokenURI = _tokenURIs[tokenId];\n\n // Even if there is a base URI, it is only appended to non-empty token-specific URIs\n if (bytes(_tokenURI).length == 0) {\n return \"\";\n } else {\n // abi.encodePacked is being used to concatenate strings\n return string(abi.encodePacked(_baseURI, _tokenURI));\n }\n }\n\n /**\n * @dev Internal function to set the token URI for a given token.\n *\n * Reverts if the token ID does not exist.\n *\n * TIP: if all token IDs a prefix (e.g. if your URIs look like\n * `http://api.myproject.com/token/`), use {_setBaseURI} to store\n * it and save gas.\n */\n function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {\n require(_exists(tokenId), \"ERC721Metadata: URI set of nonexistent token\");\n _tokenURIs[tokenId] = _tokenURI;\n }\n\n /**\n * @dev Internal function to set the base URI for all token IDs. It is\n * automatically added as a prefix to the value returned in {tokenURI}.\n *\n * _Available since v2.5.0._\n */\n function _setBaseURI(string memory baseURI) internal virtual {\n _baseURI = baseURI;\n }\n\n /**\n * @dev Returns the base URI set via {_setBaseURI}. This will be\n * automatically added as a prefix in {tokenURI} to each token's URI, when\n * they are non-empty.\n *\n * _Available since v2.5.0._\n */\n function baseURI() external view returns (string memory) {\n return _baseURI;\n }\n\n function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {\n super._beforeTokenTransfer(from, to, tokenId);\n\n if (to == address(0)) { // When burning tokens\n // Clear metadata (if any)\n if (bytes(_tokenURIs[tokenId]).length != 0) {\n delete _tokenURIs[tokenId];\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```js\nfunction _setBaseURI(string memory baseURI) public override(ERC721Full, ERC721Metadata) {\n    _baseURI = baseURI;\n}\n```\n\n```js\npragma solidity ^0.6.0;\n\nimport \"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0-beta.0/contracts/token/ERC721/ERC721Full.sol\";\nimport \"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0-beta.0/contracts/drafts/Counters.sol\";\n\ncontract GameItem is ERC721Full {\n    using Counters for Counters.Counter;\n    Counters.Counter private _tokenIds;\n\n    constructor() ERC721Full(\"GameItem\", \"ITM\") public {\n    }\n\n    function awardItem(address player, string memory tokenURI) public returns (uint256) {\n        _tokenIds.increment();\n\n        uint256 newItemId = _tokenIds.current();\n        _mint(player, newItemId);\n        _setTokenURI(newItemId, tokenURI);\n\n        return newItemId;\n    }\n    \n      function _setBaseURI(string memory baseURI) public override(ERC721Full, ERC721Metadata) {\n        _baseURI = baseURI;\n    }\n}\n```\n\n```js\npragma solidity ^0.6.0;\n\nimport \"../../GSN/Context.sol\";\nimport \"./ERC721.sol\";\nimport \"./IERC721Metadata.sol\";\nimport \"../../introspection/ERC165.sol\";\n\ncontract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {\n    // Token name\n    string private _name;\n\n    // Token symbol\n    string private _symbol;\n\n    // Base URI\n    string private _baseURI;\n\n    // Optional mapping for token URIs\n    mapping(uint256 => string) private _tokenURIs;\n\n    /*\n     *     bytes4(keccak256('name()')) == 0x06fdde03\n     *     bytes4(keccak256('symbol()')) == 0x95d89b41\n     *     bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd\n     *\n     *     => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f\n     */\n    bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;\n\n    /**\n     * @dev Constructor function\n     */\n    constructor (string memory name, string memory symbol) public {\n        _name = name;\n        _symbol = symbol;\n\n        // register the supported interfaces to conform to ERC721 via ERC165\n        _registerInterface(_INTERFACE_ID_ERC721_METADATA);\n    }\n\n    /**\n     * @dev Gets the token name.\n     * @return string representing the token name\n     */\n    function name() external view override returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Gets the token symbol.\n     * @return string representing the token symbol\n     */\n    function symbol() external view override returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the URI for a given token ID. May return an empty string.\n     *\n     * If the token's URI is non-empty and a base URI was set (via\n     * {_setBaseURI}), it will be added to the token ID's URI as a prefix.\n     *\n     * Reverts if the token ID does not exist.\n     */\n    function tokenURI(uint256 tokenId) external view override returns (string memory) {\n        require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\n\n        string memory _tokenURI = _tokenURIs[tokenId];\n\n        // Even if there is a base URI, it is only appended to non-empty token-specific URIs\n        if (bytes(_tokenURI).length == 0) {\n            return \"\";\n        } else {\n            // abi.encodePacked is being used to concatenate strings\n            return string(abi.encodePacked(_baseURI, _tokenURI));\n        }\n    }\n\n    /**\n     * @dev Internal function to set the token URI for a given token.\n     *\n     * Reverts if the token ID does not exist.\n     *\n     * TIP: if all token IDs share a prefix (e.g. if your URIs look like\n     * `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store\n     * it and save gas.\n     */\n    function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {\n        require(_exists(tokenId), \"ERC721Metadata: URI set of nonexistent token\");\n        _tokenURIs[tokenId] = _tokenURI;\n    }\n\n    /**\n     * @dev Internal function to set the base URI for all token IDs. It is\n     * automatically added as a prefix to the value returned in {tokenURI}.\n     *\n     * _Available since v2.5.0._\n     */\n    function _setBaseURI(string memory baseURI) internal virtual {\n        _baseURI = baseURI;\n    }\n\n    /**\n    * @dev Returns the base URI set via {_setBaseURI}. This will be\n    * automatically added as a prefix in {tokenURI} to each token's URI, when\n    * they are non-empty.\n    *\n    * _Available since v2.5.0._\n    */\n    function baseURI() external view returns (string memory) {\n        return _baseURI;\n    }\n\n\n    function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {\n        super._beforeTokenTransfer(from, to, tokenId);\n\n        if (to == address(0)) { // When burning tokens\n            // Clear metadata (if any)\n            if (bytes(_tokenURIs[tokenId]).length != 0) {\n                delete _tokenURIs[tokenId];\n            }\n        }\n    }\n}\n```\n\n```text\n_baseURI\n```\n\n```text\n_baseURI\n```\n\n```text\ninternal\n```\n\n```text\nprivate\n```\n\n```text\nERC721Metadata.sol\n```\n\n```text\n_setBaseURI()\n```\n\n========================================\n\nComments:\n- `function _setBaseURI(string memory baseURI) internal override { }` Overwriting this function would have no effect. In this case then you would have to import the two files. Because Metadata is inherited in ERC721Full. not?\n- @FernandoL&#243;pez Overriding (in `GameItem`) the function (defined in `ERC721Metadata`) would have an effect - you would be able to override the function (but not set the `_baseURI` property without changing its visibility first)... But as you're saying, you'd need to import the two files to be able to change the `_basURI` property visiblity (and to be able to access it in `GameItem`).","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":376,"estimatedTokens":2632}}334{"id":"stack-40924990","source":"stackoverflow","questionId":40924990,"title":"Creating Ethereums tokens and set up transaction fees","tags":["ethereum","solidity"],"text":"Title: Creating Ethereums tokens and set up transaction fees\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nSince creating a smart contract with Ethereum involves the user of ether, refilling all of the users' ethers becomes costly for a company. So let's say a company decide to issue a token over the ethereum network, and that token represents a new currency. Can the original creator of the token receive transaction fees everytime each user send tokens to someone else? That way the company could easily refill everyone's token's with ether.\n\n========================================\n\nTop Answer:\nIf you look at the problem as a whole, every user should spend some ether (as fees) to perform any transaction. If you are planning to fill the users accounts' with ether paid by users, the net sum is zero (looking at all users as an entity and company as another entity). So, either you have to fill the users accounts with ether from your pocket or Users have to burn their own pockets to make transactions (transfer tokens etc.)\n\n========================================\n\nCode:\n```text\nfunction transferFrom(address _from, address _to, uint256 _value) returns (bool success) {\n    // accept fees\n    if (msg.value < FEE) {\n        return false;\n    }\n    if (!MYADDR.send(msg.value) {\n        throw;\n    }\n\n    // do token transfer (WARNING, no validation here, don't use, it's for current example only)\n    balances[_to]   += _value;\n    balances[_from] -= _value;\n    return true;\n}\n```\n\n========================================\n\nComments:\n- But what if the user of that token doesn't have enough ether? Can I require users to send a bigger amount of tokens for each token transfer? And just take a cut (in tokens, not ether) from each token transfer?\n- yes, sure. so instead of that fees lines of code, just add part of the `_value` to `balances[your system address]`","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":1,"totalLines":37,"estimatedTokens":472}}335{"id":"stack-71670989","source":"stackoverflow","questionId":71670989,"title":"Easy way to view a list of the tokens owned by a user?","tags":["blockchain","solidity","smartcontracts","nft","openzeppelin"],"text":"Title: Easy way to view a list of the tokens owned by a user?\nTags: blockchain, solidity, smartcontracts, nft, openzeppelin\nSource: Stack Overflow\n\nQuestion:\nI'm sure this could be done on the front end as well as from solidity. I saw a few posts that seemed inefficient, where they are creating a new mapping and storing unnecessary data to the blockchain when the ERC721 package already has the functions it needs in order to procure this information, from my understanding.\n\nFigured out the answer to the first part!!\n\n```\nfunction ownerOfTokenIds(address tokenOwner) external view returns (uint256[] memory) {\n uint256[] memory result = new uint256[](balanceOf(tokenOwner));\n uint256 counter = 0;\n for (uint256 i = 0; i < tokenCounter; i++) {\n if (ownerOf(i) == tokenOwner) {\n result[counter] = i;\n counter++;\n }\n }\n return result;\n }\n```\n\n========================================\n\nCode:\n```text\nfunction ownerOfTokenIds(address tokenOwner) external view returns (uint256[] memory) {\n        uint256[] memory result = new uint256[](balanceOf(tokenOwner));\n        uint256 counter = 0;\n        for (uint256 i = 0; i < tokenCounter; i++) {\n            if (ownerOf(i) == tokenOwner) {\n                result[counter] = i;\n                counter++;\n            }\n        }\n        return result;\n    }\n```\n\n========================================\n\nComments:\n- I saw similar code snippet in Gnosis' Multisig Wallet and thought the same. I thing there isn't more efficent way to do it with current version of Solidity.","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":44,"estimatedTokens":380}}336{"id":"stack-74719578","source":"stackoverflow","questionId":74719578,"title":"Where event LogFeeTransfer is used in polygon contract?","tags":["solidity","polygon","cryptocurrency","evm","matic"],"text":"Title: Where event LogFeeTransfer is used in polygon contract?\nTags: solidity, polygon, cryptocurrency, evm, matic\nSource: Stack Overflow\n\nQuestion:\nWhen I decoded and checked a transaction's log about the polygon contract (0x0000000000000000000000000000000000001010), I found the signature like \"LogFeeTransfer(address,address,address,uint256,uint256,uint256,uint256,uint256)\".\n\nHowever I can't find that polygon contract emits this event.\n\nWhat's this event for and where is used in the contract?\n\nThank you.\n\nI searched the contract source code on polygonscan for \"emit LogFeeContract\".\n\n========================================\n\nCode:\n```text\n...1010\n```\n\n========================================\n\nComments:\n- Thank you. I have two new quwstions about precompiled contract. 1. EIP-1352 status is Stagnant. Is the decision made to reserve a particular range for precompiled contracts? 2. Are there precompiled contract list about Polygon?","metadata":{"transformedAt":"2026-08-18T18:33:36.140Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":26,"estimatedTokens":236}}337{"id":"stack-62778277","source":"stackoverflow","questionId":62778277,"title":"Most efficient way to check byte array values are within a range/below threshold?","tags":["arrays","validation","solidity"],"text":"Title: Most efficient way to check byte array values are within a range/below threshold?\nTags: arrays, validation, solidity\nSource: Stack Overflow\n\nQuestion:\nI have a `uint256` that I'm using as a byte array consisting of 10 numbers, 3 bytes each (which takes up 30 bytes, the first 2 bytes of the 32 bytes are ignored):\n\n```\n0x0000aaaaaabbbbbbccccccddddddeeeeeeffffff111111222222333333444444\n xxxx^ ^ ^ ^ ^ ^ ^ ^ ^ ^\n```\n\nI need to validate that these numbers are within a certain range. They are `uint24` so they are always positive, and the lowest index is 0 so I only really need to check if they are below a certain upper threshold.\n\nAt present I am reading the relevant bytes into `uint24` objects and checking that the number is below the threshold:\n\n```\nuint256 constant NUM_OF_GROUPS = 129600; // all numbers have to be between 0 and 129599\n\n....... \n\nfunction decodeAndCheckGroupIndexes(uint256 x)\n public\n pure\n returns (\n uint24 a,\n uint24 b,\n uint24 c,\n uint24 d,\n uint24 e,\n uint24 f,\n uint24 g,\n uint24 h,\n uint24 i,\n uint24 j\n )\n {\n assembly {\n j := x\n mstore(0x1B, x)\n a := mload(0)\n mstore(0x18, x)\n b := mload(0)\n mstore(0x15, x)\n c := mload(0)\n mstore(0x12, x)\n d := mload(0)\n mstore(0x0F, x)\n e := mload(0)\n mstore(0x0C, x)\n f := mload(0)\n mstore(0x09, x)\n g := mload(0)\n mstore(0x06, x)\n h := mload(0)\n mstore(0x03, x)\n i := mload(0)\n }\n require(\n a however I was wondering if there was a better way to check it involving less computation? This check happens in a loop with an array of `uint256` so I'm attempting to achieve maximum efficiency to reduce gas cost.\n\n========================================\n\nCode:\n```text\n0x0000aaaaaabbbbbbccccccddddddeeeeeeffffff111111222222333333444444\n  xxxx^     ^     ^     ^     ^     ^     ^     ^     ^     ^\n```\n\n```text\nuint256 constant NUM_OF_GROUPS = 129600; // all numbers have to be between 0 and 129599\n\n....... \n\nfunction decodeAndCheckGroupIndexes(uint256 x)\n        public\n        pure\n        returns (\n            uint24 a,\n            uint24 b,\n            uint24 c,\n            uint24 d,\n            uint24 e,\n            uint24 f,\n            uint24 g,\n            uint24 h,\n            uint24 i,\n            uint24 j\n        )\n    {\n        assembly {\n            j := x\n            mstore(0x1B, x)\n            a := mload(0)\n            mstore(0x18, x)\n            b := mload(0)\n            mstore(0x15, x)\n            c := mload(0)\n            mstore(0x12, x)\n            d := mload(0)\n            mstore(0x0F, x)\n            e := mload(0)\n            mstore(0x0C, x)\n            f := mload(0)\n            mstore(0x09, x)\n            g := mload(0)\n            mstore(0x06, x)\n            h := mload(0)\n            mstore(0x03, x)\n            i := mload(0)\n        }\n        require(\n            a < NUM_OF_GROUPS &&\n                b < NUM_OF_GROUPS &&\n                c < NUM_OF_GROUPS &&\n                d < NUM_OF_GROUPS &&\n                e < NUM_OF_GROUPS &&\n                f < NUM_OF_GROUPS &&\n                g < NUM_OF_GROUPS &&\n                h < NUM_OF_GROUPS &&\n                i < NUM_OF_GROUPS &&\n                j < NUM_OF_GROUPS,\n            \"group is out of range\"\n        ); \n    }\n```\n\n```text\nuint256\n```\n\n```text\nuint24\n```\n\n```text\nuint24\n```\n\n```text\nuint256\n```\n\n```text\n0x0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000\n  xxxx^     ^     ^     ^     ^     ^     ^     ^     ^     ^\n```\n\n```text\n0x0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000\n  xxxx^     ^     ^     ^     ^     ^     ^     ^     ^     ^\n```\n\n```c\nuint256 valid_mask = 0x0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000FF0000;\nuint256 invalid_mask = 0x0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000;\n\n// returns true if all ten numbers encoded in `input` are\n// less than 129,600\nbool less_than_129600(uint256 input) {\n    // check if all ten numbers are definitely valid\n    if (valid_mask & input == 0)\n        return true;\n    \n    // check if at least one number is definitely invalid\n    if (invalid_mask & input != 0)\n        return false;\n\n    // check each number and return false if an invalid number\n    // is encountered\n    ...\n\n    // if we haven't returned after the last check, all numbers\n    // are valid\n    return true;\n}\n```\n\n```text\n129,600\n```\n\n```text\n000000011111101001000000\n```\n\n```text\n65,535\n```\n\n```text\n129,600\n```\n\n```text\n131,072\n```\n\n```text\n129,600\n```\n\n```text\n129,600\n```\n\n```text\nand\n```\n\n```text\n0xFF0000\n```\n\n```text\n129,600\n```\n\n```text\nand\n```\n\n```text\n0xFE0000\n```\n\n```text\n129,600\n```\n\n```text\n129,600\n```\n\n```text\nuint256\n```\n\n```text\nand\n```\n\n```text\nand\n```\n\n```text\nuint256\n```\n\n```text\n65,535\n```\n\n```text\n129,600\n```\n\n```text\nand\n```\n\n```text\nuint256\n```\n\n```text\n131,072\n```\n\n```text\n129,600\n```\n\n```text\n129,600\n```\n\n```text\n&\n```\n\n```text\nand\n```\n\n========================================\n\nComments:\n- Any specificity on the upper limit? And is it the same upper limit for every value?\n- Yes every value has the same upper limit\n- variable, or fixed upper limit? what is the upper limit if fixed?\n- Fixed upper limit, defined as a constant as part of the contract\n- So what I was thinking is if the upper limit were fixed enough, and a power of 2, you could create a bitmask like 0xF00F00F00 and xor against that - if anything hits you've exceeded the limit. If values are much more dynamic, that won't work. Your other option might be to just make them all 32-bit, use a little more memory, it's probably just as fast, maybe faster, given dealing with bit alignment.\n- so in this case the NUM_OF_GROUPS is 129600 (which is a power of 2) so all values have to be between 0 and 129599. Added it to the code above for clarity.\n- That's a multiple of 2, not power of 2. You could still do something similar. In that case mask the top 3 (unused, too large) bits. So over=0xE00000E000000.... repeated. Do your int256 xor over, and if that is > 0, then some value is definitely over. Assuming none, then do maybe=0x100000100000... xor your int256, and if that's > 0, then some value *could* be over, and you need to check every one. If values are rarely \"large\" it might help.\n- Or just xor with F00000F00000... and if that tests > 0, then do the long version compare of each value. That would also be easy to figure out what that masks needs to be for any dynamic value, just mask up to and including the highest bit, and repeat.\n- Just realised I had the ignored bytes placement wrong, its the first 2 bytes that are ignored (addressed above) but I assume your suggestions would still hold, just the masks will need shifting by 2 bytes.\n- Thanks for this, shame that there's no direct way to check but this is definitely going to help. The bounty expired though I'm not sure how i can reward you some points?","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":36,"totalLines":299,"estimatedTokens":1699}}338{"id":"stack-43198038","source":"stackoverflow","questionId":43198038,"title":"Solidity Functions Not Returning Expected Data","tags":["ethereum","solidity"],"text":"Title: Solidity Functions Not Returning Expected Data\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI have a contract with the following function:\n\n```\nfunction supply () constant returns (uint sup) {\n sup = 100;\n return sup;\n }\n```\n\nRunning \n\n```\nvar token = web3.eth.contract(contractAbi).at(contractAddress);\n token.supply.call()\n```\n\nreturns:\n\n```\n{ [String: '0'] s: 1, e: 0, c: [ 0 ] }\n```\n\nWhat's wrong here? This is happening with all my functions in the contract.\n\nThanks!\n\n========================================\n\nCode:\n```text\nfunction supply () constant returns (uint sup) {\n    sup = 100;\n    return sup;\n  }\n```\n\n```text\nvar token = web3.eth.contract(contractAbi).at(contractAddress);\n  token.supply.call()\n```\n\n```text\n{ [String: '0'] s: 1, e: 0, c: [ 0 ] }\n```\n\n```text\ntoken.supply.call().then(function(returned) {\n   console.log(returned.toString(10));\n}\n```\n\n```text\ntoken.supply.call(function(error, returned) {\n  if(!error) {\n    console.log(returned.toString(10));\n  } else {\n    console.error(error);\n});\n```\n\n========================================\n\nComments:\n- Thanks Rob, can you see any reason why I'm not getting the expected 100 back, but instead getting 0?\n- Are you in geth, truffle console or something else? Are you waiting for the callback?\n- Thanks Rob, that clears things up. I am using a truffle and testrpc and using exec to test things. I have everything working now, I wasn't updating the contract address with each new deploy.","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":71,"estimatedTokens":371}}339{"id":"stack-50238914","source":"stackoverflow","questionId":50238914,"title":"Py-solc and solidity imports","tags":["python","solidity","web3py"],"text":"Title: Py-solc and solidity imports\nTags: python, solidity, web3py\nSource: Stack Overflow\n\nQuestion:\nHow can I compile solidity files which perform relative imports through `py-solc`? Here's a minimal example:\n\nDirectory structure\n\nmy-project\n - main.py\n - bar.sol\n - baz.sol\n\nmain.py:\n\nfrom solc import compile_source\n\ndef get_contract_source(file_name):\n with open(file_name) as f:\n return f.read()\n\ncontract_source_code = get_contract_source(\"bar.sol\")\n\ncompiled_sol = compile_source(contract_source_code) # Compiled source code\n\nbaz.sol:\n\npragma solidity ^0.4.0;\n\ncontract baz {\n function baz(){\n\n }\n}\n\nbar.sol:\n\npragma solidity ^0.4.0;\n\nimport \"./baz\" as baz;\n\ncontract bar {\n function bar(){\n\n }\n}\n\nWhen I try to run the python file I get the following error:\n\nsolc.exceptions.SolcError: An error occurred during execution\n > command: `solc --combined-json abi,asm,ast,bin,bin-runtime,clone-bin,devdoc,interface,opcodes,userdoc`\n > return code: `1`\n > stderr:\n\n > stdout:\n :17:1: Error: Source \"baz\" not found: File outside of allowed directories.\nimport \"./baz\" as baz;\n^----------------------^\n\nI'm still not 100% clear on how imports work. I've reviewed the docs and it seems like I need to pass some extra arguments to the `compile_source` command. I've found some potentially useful docs here and I think I need to play around with `allow_paths` or `compile_files` which I will. If I find a solution before I get an answer I will post what I find.\n\n========================================\n\nTop Answer:\nAssume we have a smart contract man.sol, and it contains two contract in a file, like this:\n\n```\npragma solidity ^0.8.0;\nimport \"./SafeERC20.sol\";\ncontract mainContract {\n ... (Any code can be here ...)\n}contract childContract {\n ... (Other code here)}\n```\n\nSo we have a directory like this:\n\nmain.sol\n-SafeERC20.sol\n-deploy.py\n\nDeploy.py :\n\n```\nimport json\nimport os\n\nimport web3.eth\nfrom web3 import Web3, HTTPProvider\n\nfrom solcx import install_solc, set_solc_version,compile_standard\nfrom dotenv import load_dotenv#here install solidity version\ninstall_solc('v0.8.0')\nset_solc_version('v0.8.0')\n\nfile_path = \".\"\nname = \"main.sol\"\ninput = {\n 'language': 'Solidity',\n 'sources': {\n name: {'urls': [file_path + \"/\" + name]}},\n 'settings': {\n 'outputSelection': {\n '*': {\n '*': [\"abi\", \"metadata\", \"evm.bytecode\", \"evm.bytecode.sourceMap\"],\n },\n 'def': {name: [\"abi\", \"evm.bytecode.opcodes\"]},\n }\n }\n}\n\noutput = compile_standard(input, allow_paths=file_path)\n\ncontracts = output[\"contracts\"]\n\nwith open('compiled_code.json', \"w\") as file:\n json.dump(output, file)\n\nbytecode = contracts[\"SC-.sol\"][\"mainContract\"][\"evm\"][\"bytecode\"][\"object\"]\n\nabi = contracts[\"main.sol\"][\"mainContract\"][\"abi\"]\n\n# Deploy on local ganache# w3 = Web3(Web3.HTTPProvider(\"HTTP://127.0.0.1:7545\"))\n# chainId = 1337\n# myAddress = \"0x6235207DE426B0E3739529F1c53c14aaA271D...\"\n# privateKey = \"0xdbe7f5a9c95ea2df023ad9.......\"\n\n#Deploy on rinkeby infura rinkebyw3 = Web3(Web3.HTTPProvider(\"https://rinkeby.infura.io/v3/......\"))\nchainId = 4\n\nmyAddress = \"0xBa842323C4747609CeCEd164d61896d2Cf4...\"\nprivateKey =\"0x99de2de028a52668d3e94a00d47c4500db0afed3fe8e40...\"\n\nSCOnline = w3.eth.contract(abi=abi, bytecode=bytecode)\n\nnonce = w3.eth.getTransactionCount(myAddress)\n\ntransaction = SCOnline.constructor().buildTransaction({\n \"gasPrice\": w3.eth.gas_price, \"chainId\": chainId, \"from\": myAddress, \"nonce\": nonce\n})\n\nsignedTrx = w3.eth.account.sign_transaction(transaction, private_key= privateKey)\n\ntxHash = w3.eth.send_raw_transaction(signedTrx.rawTransaction)\n\ntxReceipt = w3.eth.wait_for_transaction_receipt(txHash)\n```\n\n========================================\n\nCode:\n```text\nmy-project\n   - main.py\n   - bar.sol\n   - baz.sol\n```\n\n```text\nfrom solc import compile_source\n\ndef get_contract_source(file_name):\n    with open(file_name) as f:\n        return f.read()\n\ncontract_source_code = get_contract_source(\"bar.sol\")\n\ncompiled_sol = compile_source(contract_source_code)  # Compiled source code\n```\n\n```text\npragma solidity ^0.4.0;\n\ncontract baz {\n    function baz(){\n\n    }\n}\n```\n\n```text\npragma solidity ^0.4.0;\n\nimport \"./baz\" as baz;\n\ncontract bar {\n    function bar(){\n\n    }\n}\n```\n\n```text\nsolc.exceptions.SolcError: An error occurred during execution\n        > command: `solc --combined-json abi,asm,ast,bin,bin-runtime,clone-bin,devdoc,interface,opcodes,userdoc`\n        > return code: `1`\n        > stderr:\n\n        > stdout:\n        :17:1: Error: Source \"baz\" not found: File outside of allowed directories.\nimport \"./baz\" as baz;\n^----------------------^\n```\n\n```text\npy-solc\n```\n\n```text\ncompile_source\n```\n\n```text\nallow_paths\n```\n\n```text\ncompile_files\n```\n\n```text\nimport os\n\nPROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))\ncompiled_sol = compile_files([os.path.join(self.PROJECT_ROOT, \"bar.sol\"), os.path.join(self.PROJECT_ROOT, \"baz.sol\")])\n```\n\n```text\ncompile_files\n```\n\n```text\nbaz\n```\n\n```text\nimport \"./baz.sol\" as baz;\n```\n\n```text\n.sol\n```\n\n```text\npragma solidity ^0.8.0;\nimport \"./SafeERC20.sol\";\ncontract mainContract {\n  ... (Any code can be here ...)\n}contract childContract {\n ... (Other code here)}\n```\n\n```text\nimport json\nimport os\n\nimport web3.eth\nfrom web3 import Web3, HTTPProvider\n\nfrom solcx import install_solc, set_solc_version,compile_standard\nfrom dotenv import load_dotenv#here install solidity version\ninstall_solc('v0.8.0')\nset_solc_version('v0.8.0')\n\n\nfile_path = \".\"\nname = \"main.sol\"\ninput = {\n    'language': 'Solidity',\n    'sources': {\n        name: {'urls': [file_path + \"/\" + name]}},\n    'settings': {\n        'outputSelection': {\n            '*': {\n                '*': [\"abi\", \"metadata\", \"evm.bytecode\", \"evm.bytecode.sourceMap\"],\n            },\n            'def': {name: [\"abi\", \"evm.bytecode.opcodes\"]},\n        }\n    }\n}\n\noutput = compile_standard(input, allow_paths=file_path)\n\ncontracts = output[\"contracts\"]\n\nwith open('compiled_code.json', \"w\") as file:\n    json.dump(output, file)\n\nbytecode = contracts[\"SC-.sol\"][\"mainContract\"][\"evm\"][\"bytecode\"][\"object\"]\n\nabi = contracts[\"main.sol\"][\"mainContract\"][\"abi\"]\n\n\n# Deploy on local ganache# w3 = Web3(Web3.HTTPProvider(\"HTTP://127.0.0.1:7545\"))\n# chainId = 1337\n# myAddress = \"0x6235207DE426B0E3739529F1c53c14aaA271D...\"\n# privateKey = \"0xdbe7f5a9c95ea2df023ad9.......\"\n\n#Deploy on rinkeby infura rinkebyw3 = Web3(Web3.HTTPProvider(\"https://rinkeby.infura.io/v3/......\"))\nchainId = 4\n\nmyAddress = \"0xBa842323C4747609CeCEd164d61896d2Cf4...\"\nprivateKey =\"0x99de2de028a52668d3e94a00d47c4500db0afed3fe8e40...\"\n\nSCOnline = w3.eth.contract(abi=abi, bytecode=bytecode)\n\nnonce = w3.eth.getTransactionCount(myAddress)\n\ntransaction = SCOnline.constructor().buildTransaction({\n    \"gasPrice\": w3.eth.gas_price, \"chainId\": chainId, \"from\": myAddress, \"nonce\": nonce\n})\n\nsignedTrx = w3.eth.account.sign_transaction(transaction, private_key= privateKey)\n\n\n\ntxHash = w3.eth.send_raw_transaction(signedTrx.rawTransaction)\n\ntxReceipt = w3.eth.wait_for_transaction_receipt(txHash)\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":321,"estimatedTokens":1745}}340{"id":"stack-73306677","source":"stackoverflow","questionId":73306677,"title":"How to compare an ascii string with a uint8 array in Solidity?","tags":["ethereum","solidity"],"text":"Title: How to compare an ascii string with a uint8 array in Solidity?\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI have a uint8 array containing ASCII codes for characters and a string variable, and I wish to make a comparison between them. For example:\n\n```\nuint8[3] memory foo = [98, 97, 122]; // baz\nstring memory bar = \"baz\";\n\nbool result = keccak256(abi.encodePacked(foo)) == keccak256(abi.encodePacked(bytes(bar))); // false\n```\n\nHere I want the comparison to succeed, but it's a failure because `encodePacked` will keep the padding of all the uint8 elements in the array when encoding it.\n\nHow can I do it instead?\n\n========================================\n\nCode:\n```text\nuint8[3] memory foo = [98, 97, 122]; // baz\nstring memory bar = \"baz\";\n\nbool result = keccak256(abi.encodePacked(foo)) == keccak256(abi.encodePacked(bytes(bar))); // false\n```\n\n```text\nencodePacked\n```\n\n```text\n0x\n0000000000000000000000000000000000000000000000000000000000000062\n0000000000000000000000000000000000000000000000000000000000000061\n000000000000000000000000000000000000000000000000000000000000007a\n```\n\n```text\n0x\n0000000000000000000000000000000000000000000000000000000000000020 # pointer\n0000000000000000000000000000000000000000000000000000000000000003 # length\n62617a0000000000000000000000000000000000000000000000000000000000 # value\n```\n\n```text\npragma solidity ^0.8;\n\ncontract MyContract {\n    function compare() external pure returns (bool) {\n        uint8[3] memory foo = [98, 97, 122]; // baz\n        string memory bar = \"baz\";\n\n        // typecast the `string` to `bytes` dynamic-length array\n        // so that you can use its `.length` member property\n        // and access its items individually (see `barBytes[i]` below, not possible with `bar[i]`)\n        bytes memory barBytes = bytes(bar);\n\n        // prevent accessing out-of-bounds index in the following loop\n        // as well as false positive if `foo` contains just the beginning of `bar` but not the whole string\n        if (foo.length != barBytes.length) {\n            return false;\n        }\n\n        // loop through each item of `foo`\n        for (uint i; i < foo.length; i++) {\n            uint8 barItemDecimal = uint8(barBytes[i]);\n            // and compare it to each decimal value of `bar` character\n            if (foo[i] != barItemDecimal) {\n                return false;\n            }\n        }\n\n        // all items have equal values\n        return true;\n    }\n}\n```\n\n```text\nabi.encodePacked(foo))\n```\n\n```text\nkeccak256(abi.encodePacked(bytes(bar))\n```\n\n```text\nuint8\n```\n\n```text\nstring\n```\n\n========================================\n\nComments:\n- I wish there was another way to make the comparison without wasting computation time comparing each character one by one, but I guess at least this approach works. Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":100,"estimatedTokens":703}}341{"id":"stack-71693698","source":"stackoverflow","questionId":71693698,"title":"Curly Bracket in a solidity function","tags":["solidity","curly-braces"],"text":"Title: Curly Bracket in a solidity function\nTags: solidity, curly-braces\nSource: Stack Overflow\n\nQuestion:\nI would like to know what curly brackets mean in that case ?\n\n```\nuint64 configCount = s_configCount;\n {\n s_hotVars.latestConfigDigest = configDigestFromConfigData(\n address(this),\n configCount,\n _signers,\n _transmitters,\n _threshold,\n _encodedConfigVersion,\n _encoded\n );\n s_hotVars.latestEpochAndRound = 0;\n }```\n```\n\nWhy did they use {} ? why they didn't wrote the code like this :\n\n```\nuint64 configCount = s_configCount;\ns_hotVars.latestConfigDigest = configDigestFromConfigData(address(this),configCount,_signers,_transmitters,_threshold,_encodedConfigVersion,_encoded);\ns_hotVars.latestEpochAndRound = 0;\n```\n\n========================================\n\nCode:\n```text\nuint64 configCount = s_configCount;\n    {\n      s_hotVars.latestConfigDigest = configDigestFromConfigData(\n        address(this),\n        configCount,\n        _signers,\n        _transmitters,\n        _threshold,\n        _encodedConfigVersion,\n        _encoded\n      );\n      s_hotVars.latestEpochAndRound = 0;\n    }```\n```\n\n```text\nuint64 configCount = s_configCount;\ns_hotVars.latestConfigDigest = configDigestFromConfigData(address(this),configCount,_signers,_transmitters,_threshold,_encodedConfigVersion,_encoded);\ns_hotVars.latestEpochAndRound = 0;\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":55,"estimatedTokens":335}}342{"id":"stack-70650915","source":"stackoverflow","questionId":70650915,"title":"How to delete an image saved in IPFS blockchain?","tags":["blockchain","ethereum","solidity","smartcontracts","ipfs"],"text":"Title: How to delete an image saved in IPFS blockchain?\nTags: blockchain, ethereum, solidity, smartcontracts, ipfs\nSource: Stack Overflow\n\nQuestion:\nI am working on a blockcahin based image sharing website in ethereum\n\n```\nfunction uploadImage(string memory _imgHASH,string memory _description ) public{\n //making sure image ipfs hash exist\n require(bytes(_imgHASH).length > 0);\n //making sure that the image description exist\n require(bytes(_description).length > 0);\n\n require(msg.sender != address(0));\n\n //increment image id\n imageCount ++;\n\n //add image to contract\n images[imageCount] = Image(imageCount,_imgHASH,_description,0,msg.sender);\n\n //trigger an image\n emit ImageCreated(imageCount, _imgHASH, _description, 0, msg.sender);\n}\n```\n\nThis is how you upload images but now I want user to delete images created by them how do i do it?\n\n========================================\n\nCode:\n```text\nfunction uploadImage(string memory _imgHASH,string memory _description ) public{\n //making sure image ipfs hash exist\n require(bytes(_imgHASH).length > 0);\n  //making sure that the image description exist\n  require(bytes(_description).length > 0);\n\n  require(msg.sender != address(0));\n\n  //increment image id\n  imageCount ++;\n\n  //add image to contract\n  images[imageCount] = Image(imageCount,_imgHASH,_description,0,msg.sender);\n\n\n  //trigger an image\n  emit ImageCreated(imageCount, _imgHASH, _description, 0, msg.sender);\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":52,"estimatedTokens":359}}343{"id":"stack-63457638","source":"stackoverflow","questionId":63457638,"title":"sending signTransaction with web3.js. but I can't confirm this transaction in ganache","tags":["ethereum","solidity","truffle","web3js","ganache"],"text":"Title: sending signTransaction with web3.js. but I can't confirm this transaction in ganache\nTags: ethereum, solidity, truffle, web3js, ganache\nSource: Stack Overflow\n\nQuestion:\nI want to put data in rawTransaction and send it to the smart contact of the ganache local node.\nBy the way, the raw transaction I made with the data was created, but I can't see the transaction on ganache. Why did you do that?\n\n```\nconst Web3 = require('web3');\nlet web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:7545/'));\nconst Accounts = require('web3-eth-accounts');\n\nlet user_addr = \"dummy addr\"\nlet user_cash = \"dummy cash\"\nlet userInfo = [user_addr, user_cash];\nlet payment_user = web3.utils.toHex(userInfo);\nconsole.log(payment_user);\n\nweb3.eth.accounts.signTransaction({\n from: \"0xa22b061113adf71a54E9a12F7480256D8C342d8F\",\n to: '0xEf938B9eCC089D47BAA7B4582Cdb69C526bfD827',\n value: '10000',\n gas: 200000,\n data: payment_user\n}, '052607c87473b31777d0f208021da7b68949f0b02b09bcecb0248198dbed765d');\n```\n\nResult:\n\n```\nmessageHash: '0x4a2dbabb5a7a8e16102fef48f5f1e2154c266c14c3095033d5b3c496bc179e13',\n v: '0x0a95',\n r: '0xc01ea799c002a1eac82bd0aa1856ae5f86f6a74c6985ac74695fedcf55a755c3',\n s: '0x200fdb3e4f6013e9dcc9ed47ae28e0b95a7837498c9e173734312b616629a827',\n rawTransaction: '0xf884158504a817c80083030d4094ef938b9ecc089d47baa7b4582cdb69c526bfd8278227109b5b2264756d6d792061646472222c2264756d6d792063617368225d820a95a0c01ea799c002a1eac82bd0aa1856ae5f86f6a74c6985ac74695fedcf55a755c3a0200fdb3e4f6013e9dcc9ed47ae28e0b95a7837498c9e173734312b616629a827',\n transactionHash: '0xa71361fed8d1cb69cc67e801aa118a151ec50bcf3f1b95053af7258265e151c5'\n```\n\nganache (These transactions are based on smart contract deploy) :\n\nenter image description here\n\n========================================\n\nTop Answer:\nYou need send this raw transaction to network.\nlet signed = await web3.eth.accounts.signTransaction(...)\n\nlet tx = web3.eth.sendSignedTransaction(signed.rawTransaction);\n\nconsole.log('tx:', tx);\n\n========================================\n\nCode:\n```text\nconst Web3 = require('web3');\nlet web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:7545/'));\nconst Accounts = require('web3-eth-accounts');\n\nlet user_addr = \"dummy addr\"\nlet user_cash = \"dummy cash\"\nlet userInfo = [user_addr, user_cash];\nlet payment_user = web3.utils.toHex(userInfo);\nconsole.log(payment_user);\n\n\nweb3.eth.accounts.signTransaction({\n    from: \"0xa22b061113adf71a54E9a12F7480256D8C342d8F\",\n    to: '0xEf938B9eCC089D47BAA7B4582Cdb69C526bfD827',\n    value: '10000',\n    gas: 200000,\n    data: payment_user\n}, '052607c87473b31777d0f208021da7b68949f0b02b09bcecb0248198dbed765d');\n```\n\n```text\nmessageHash: '0x4a2dbabb5a7a8e16102fef48f5f1e2154c266c14c3095033d5b3c496bc179e13',\n  v: '0x0a95',\n  r: '0xc01ea799c002a1eac82bd0aa1856ae5f86f6a74c6985ac74695fedcf55a755c3',\n  s: '0x200fdb3e4f6013e9dcc9ed47ae28e0b95a7837498c9e173734312b616629a827',\n  rawTransaction: '0xf884158504a817c80083030d4094ef938b9ecc089d47baa7b4582cdb69c526bfd8278227109b5b2264756d6d792061646472222c2264756d6d792063617368225d820a95a0c01ea799c002a1eac82bd0aa1856ae5f86f6a74c6985ac74695fedcf55a755c3a0200fdb3e4f6013e9dcc9ed47ae28e0b95a7837498c9e173734312b616629a827',\n  transactionHash: '0xa71361fed8d1cb69cc67e801aa118a151ec50bcf3f1b95053af7258265e151c5'\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":85,"estimatedTokens":827}}344{"id":"stack-70282826","source":"stackoverflow","questionId":70282826,"title":"Smart Contract Withdrawal from contract owner","tags":["solidity"],"text":"Title: Smart Contract Withdrawal from contract owner\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nFor example I don't want to store ETH on Smart Contract but to the contract owner. Then how to implement withdrawal from the contract owner?\n\n```\npragma solidity ^0.8.7;\n\n contract WDfromContractOwner {\n \n address public owner;\n \n constructor() {\n owner=msg.sender;\n }\n \n function deposit() external payable returns (bool) { \n payable(owner).transfer(msg.value);\n return true;\n }\n \n function withdrawal() external returns (bool) { \n \n // Witdrawal from owner address....???\n\n return true;\n }\n \n }\n```\n\n========================================\n\nTop Answer:\nIf you are already are transferring the funds to the owner each time an user deposit it should not be necessary, but if you want you could do it anyway, you have different options like passing the amount as a parameter, have a default or a minimum amount, etc, but for simplicity to withdraw all the funds just add this two lines in the function\n\n```\n(bool result,)= payable(owner).call{value: address(this).balance }(\"\");\nreturn result\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.8.7;\n\n    contract WDfromContractOwner {\n    \n       address public owner;\n    \n        constructor() {\n         owner=msg.sender;\n        }\n    \n        function deposit() external payable returns (bool) {     \n        payable(owner).transfer(msg.value);\n        return true;\n        }\n    \n        function withdrawal() external returns (bool) {     \n         \n          // Witdrawal from owner address....???\n\n        return true;\n        }\n    \n    }\n```\n\n```text\npragma solidity ^0.8;\n\ninterface IERC20 {\n    function transferFrom(address, address, uint256) external returns (bool);\n}\n\ncontract WDfromContractOwner {\n    address public owner;\n\n    function withdrawToken() external {\n        // Only reachable from the mainnet.\n        // Transfers from other networks (such as Remix VM) will fail.\n        address mainnetUSDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;\n        address receiver = msg.sender; // address of the user executing the `withdrawToken()`\n        uint256 amount = 5 * 1e6; // 5 USDT, 6 decimals\n        require(\n            // the `owner` needs to execute `approve()` on the token contract directly from the `owner` address\n            // so that the `WDfromContractOwner` contract can spend their tokens\n            IERC20(mainnetUSDT).transferFrom(owner, receiver, amount)\n        );\n    }\n}\n```\n\n```text\nconst USDTAddress = \"0xdAC17F958D2ee523a2206206994597C13D831ec7\";\nconst ownerAddress = \"0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF\";\n\n// just the `balanceOf()` is sufficient in this case\nconst ABI = [\n    {\"constant\":true,\"inputs\":[{\"name\":\"who\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}\n];\n\nconst USDTContract = new web3.eth.Contract(ABI, USDTAddress);\nconst approved = await USDTContract.methods.balanceOf(ownerAddress).call();\nconsole.log(approved);\n```\n\n```text\nowner\n```\n\n```text\nowner\n```\n\n```text\napprove()\n```\n\n```text\ntransferFrom()\n```\n\n```text\n(bool result,)= payable(owner).call{value: address(this).balance }(\"\");\nreturn result\n```\n\n========================================\n\nComments:\n- Very perfect. But just for additional, can we show to the users or via web3 front end how much amount that the owner has currently approved? So user can see WD process is enable or disabled at the time he wants to WD.\n- @cempaka Sure, I updated my answer with a JS snippet to check the approved value. Note that the `approved` value is an unsigned integer including decimal places (USDT has 6 decimal places), so `1` USDT is actually going to be returned as `1000000`.","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":137,"estimatedTokens":945}}345{"id":"stack-67415698","source":"stackoverflow","questionId":67415698,"title":"Solidity Uniswap: get token price","tags":["solidity"],"text":"Title: Solidity Uniswap: get token price\nTags: solidity\nSource: Stack Overflow\n\nQuestion:\nI am trying to get the price of a pair on UniswapV2:\nThis is my code:\n\n```\npragma solidity ^0.5.1;\n\nimport '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';\nimport './IERC20.sol';\n\ncontract Uniswap {\n\n // calculate price based on pair reserves\n function getTokenPrice(address pairAddress, uint amount) public view returns(uint)\n {\n IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);\n IERC20 token1 = IERC20(pair.token1);\n (uint Res0, uint Res1,) = pair.getReserves();\n\n // decimals\n uint res0 = Res0*(10**token1.decimals());\n return((amount*res0)/Res1); // return amount of token0 needed to buy token1\n }\n \n}\n```\n\nI manually imported the openzeppelin IERC20 interface and put as compiler version 0.5.1, because the current version of uniswap v2 periphery is 0.5.1\n\nBut I have the following error for the line `IERC20 token1 = IERC20(pair.token1);`:\n\n```\nExplicit type conversion not allowed from \"function () view external returns (address)\" to \"contract IERC20\". IERC20 token1 = IERC20(pair.token1); ^-----------------^\n```\n\nAny idea on how to solve that? thanks!\n\n========================================\n\nTop Answer:\nThe IUniswapV2Pair interface defines a `token1()` function - not `token1` property.\n\nTheir contract then uses the fact, that signature of the property is the same as signature of the function, so that it doesn't need to implement the function (as long as it has the public property with the same name).\n\nBut when an external contract (such as yours) uses the interface to call functions, it needs to it exactly.\n\nSo you can simply replace\n\n```\nIERC20 token1 = IERC20(pair.token1); // original code\n```\n\nto\n\n```\nIERC20 token1 = IERC20(pair.token1()); // function `token1()`\n```\n\n========================================\n\nCode:\n```text\npragma solidity ^0.5.1;\n\nimport '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';\nimport './IERC20.sol';\n\n\ncontract Uniswap {\n\n   // calculate price based on pair reserves\n   function getTokenPrice(address pairAddress, uint amount) public view returns(uint)\n   {\n    IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);\n    IERC20 token1 = IERC20(pair.token1);\n    (uint Res0, uint Res1,) = pair.getReserves();\n\n    // decimals\n    uint res0 = Res0*(10**token1.decimals());\n    return((amount*res0)/Res1); // return amount of token0 needed to buy token1\n   }\n    \n}\n```\n\n```text\nExplicit type conversion not allowed from \"function () view external returns (address)\" to \"contract IERC20\". IERC20 token1 = IERC20(pair.token1); ^-----------------^\n```\n\n```text\nIERC20 token1 = IERC20(pair.token1);\n```\n\n```text\nIERC20 token1 = IERC20(pair.token1); // original code\n```\n\n```text\nIERC20 token1 = IERC20(pair.token1()); // function `token1()`\n```\n\n```text\ntoken1()\n```\n\n```text\ntoken1\n```\n\n========================================\n\nComments:\n- That fixed it but now getting the error: TypeErrorL Member \"decimals\" not found or not visible after argument\n- @user2324723 This doesn't seem like it's related to the original question or to this answer. Please post a separate question with steps to reproduce your issue... Based on the error message, I'm just guessing that you're trying to call the `decimals()` function on an `address` type instead of on the `IERC20` or `IUniswapV2Pair` instance.\n- Actually using `pair.decimals()` is wrong because that is the decimal of the pair and has nothing to do with your calculation , this calculation will work only if all the tokens involved have 18 decimals , the error the op is facing is that he is using pair.token1 which is a function as a property so he should use `IERC20 token1 = IERC20(pair.token1);`","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":119,"estimatedTokens":928}}346{"id":"stack-50070638","source":"stackoverflow","questionId":50070638,"title":"Truffle migrate fails due to missing function, but it exists in node_modules","tags":["ethereum","solidity","smartcontracts","truffle","ether"],"text":"Title: Truffle migrate fails due to missing function, but it exists in node_modules\nTags: ethereum, solidity, smartcontracts, truffle, ether\nSource: Stack Overflow\n\nQuestion:\nWhile attempting to run a truffle migration, I get the following error: \n\n```\nUsing network 'development'.\n\nRunning migration: 1_initial_migration.js\n Replacing Migrations...\n ... 0x1e30a241296f07f9e4e702f5066031ba128e163fd7858cfd09311ddff14bebf8\n Migrations: 0xe1b914764eeed3cceee23a6b8b43365318b219a9\nSaving successful migration to network...\n ... 0x74086dea1bf5aab373d9091512fea7f84188c05f6c2c071eae45a7eb3f5abc5d\nSaving artifacts...\nRunning migration: 1524796297_will_contract.js\nError encountered, bailing. Network state unknown. Review successful transactions manually.\nTypeError: contract.detectNetwork is not a function\n at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-deployer/src/actions/deploy.js:6:1\n at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-deployer/src/deferredchain.js:20:1\n```\n\nIt compiles fine but when the migration is run it claims that contract.detectNetwork is not found. This is weird because I can locate the method. It's in node_modules/truffle-contract/contract.js\n\n```\ndetectNetwork: function() {\n var self = this;\n\n return new Promise(function(accept, reject) {\n // Try to detect the network we have artifacts for.\n if (self.network_id) {\n // We have a network id and a configuration, let's go with it.\n if (self.networks[self.network_id] != null) {\n return accept(self.network_id);\n }\n }\n\n self.web3.version.getNetwork(function(err, result) {\n if (err) return reject(err);\n\n var network_id = result.toString();\n\n // If we found the network via a number, let's use that.\n if (self.hasNetwork(network_id)) {\n self.setNetwork(network_id);\n return accept();\n }\n\n // Otherwise, go through all the networks that are listed as\n // blockchain uris and see if they match.\n var uris = Object.keys(self._json.networks).filter(function(network) {\n return network.indexOf(\"blockchain://\") == 0;\n });\n\n var matches = uris.map(function(uri) {\n return BlockchainUtils.matches.bind(BlockchainUtils, uri, self.web3.currentProvider);\n });\n\n Utils.parallel(matches, function(err, results) {\n if (err) return reject(err);\n\n for (var i = 0; i My migration file is here: \n\n```\nvar Will = artifacts.require(\"./Will.sol\");\n\nmodule.exports = function(deployer, accounts) {\n var password1 = \"who\";\n var password2 = \"dat\";\n var deadline = 10;\n deployer.deploy(password1, password2, deadline, {value: 100, from: accounts[0]}); \n};\n```\n\nthe constructor function for the Will.sol file: \n\n```\n//Constructor function that initializes passwords, deadline, and defines destination account\n function Will(bytes32 password1, bytes32 password2, uint _deadline) payable {\n deadline = _deadline;\n pass1 = password1;\n pass2 = password2;\n owner = msg.sender;\n }\n```\n\ntruffle.js: \n\n```\nmodule.exports = {\n networks: {\n development: {\n host: \"127.0.0.1\",\n port: 8545,\n network_id: \"*\" // Match any network id\n }\n }\n };\n```\n\n========================================\n\nCode:\n```text\nUsing network 'development'.\n\nRunning migration: 1_initial_migration.js\n  Replacing Migrations...\n  ... 0x1e30a241296f07f9e4e702f5066031ba128e163fd7858cfd09311ddff14bebf8\n  Migrations: 0xe1b914764eeed3cceee23a6b8b43365318b219a9\nSaving successful migration to network...\n  ... 0x74086dea1bf5aab373d9091512fea7f84188c05f6c2c071eae45a7eb3f5abc5d\nSaving artifacts...\nRunning migration: 1524796297_will_contract.js\nError encountered, bailing. Network state unknown. Review successful transactions manually.\nTypeError: contract.detectNetwork is not a function\n    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-deployer/src/actions/deploy.js:6:1\n    at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-deployer/src/deferredchain.js:20:1\n```\n\n```text\ndetectNetwork: function() {\n      var self = this;\n\n      return new Promise(function(accept, reject) {\n        // Try to detect the network we have artifacts for.\n        if (self.network_id) {\n          // We have a network id and a configuration, let's go with it.\n          if (self.networks[self.network_id] != null) {\n            return accept(self.network_id);\n          }\n        }\n\n        self.web3.version.getNetwork(function(err, result) {\n          if (err) return reject(err);\n\n          var network_id = result.toString();\n\n          // If we found the network via a number, let's use that.\n          if (self.hasNetwork(network_id)) {\n            self.setNetwork(network_id);\n            return accept();\n          }\n\n          // Otherwise, go through all the networks that are listed as\n          // blockchain uris and see if they match.\n          var uris = Object.keys(self._json.networks).filter(function(network) {\n            return network.indexOf(\"blockchain://\") == 0;\n          });\n\n          var matches = uris.map(function(uri) {\n            return BlockchainUtils.matches.bind(BlockchainUtils, uri, self.web3.currentProvider);\n          });\n\n          Utils.parallel(matches, function(err, results) {\n            if (err) return reject(err);\n\n            for (var i = 0; i < results.length; i++) {\n              if (results[i]) {\n                self.setNetwork(uris[i]);\n                return accept();\n              }\n            }\n\n            // We found nothing. Set the network id to whatever the provider states.\n            self.setNetwork(network_id);\n\n            accept();\n          });\n\n        });\n      });\n    }\n```\n\n```text\nvar Will = artifacts.require(\"./Will.sol\");\n\nmodule.exports = function(deployer, accounts) {\n var password1 = \"who\";\n var  password2 = \"dat\";\n var  deadline = 10;\n deployer.deploy(password1, password2, deadline, {value: 100, from: accounts[0]}); \n};\n```\n\n```text\n//Constructor function that initializes passwords, deadline, and defines destination account\n    function Will(bytes32 password1, bytes32 password2, uint _deadline) payable {\n        deadline = _deadline;\n        pass1 = password1;\n        pass2 = password2;\n        owner = msg.sender;\n    }\n```\n\n```text\nmodule.exports = {\n      networks: {\n        development: {\n          host: \"127.0.0.1\",\n          port: 8545,\n          network_id: \"*\" // Match any network id\n        }\n      }\n    };\n```\n\n```text\ndeployer.deploy(password1, password2, deadline, {value: 100, from: accounts[0]});\n```\n\n```text\ndeployer.deploy(will, password1, password2, deadline, {value: 100, from: accounts[0]});\n```\n\n========================================\n\nComments:\n- Can you add your `truffle.js` config? Is there a difference if you run `truffle migrate --reset`?\n- updated, i have been running `truffle migrate --reset` consistently\n- Oh...I missed it the first time. Your deployer is wrong. It should be `deployer.deploy(Will, password1, password2, deadline, {value: 100, from: accounts[0]});`","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":224,"estimatedTokens":1716}}347{"id":"stack-67031948","source":"stackoverflow","questionId":67031948,"title":"Function to mint ERC-token with every nth-number of like","tags":["solidity","ipfs"],"text":"Title: Function to mint ERC-token with every nth-number of like\nTags: solidity, ipfs\nSource: Stack Overflow\n\nQuestion:\nI need help with a function to reward user with erc777-token as soon as his content (Ipfs-Hash, see the program below) hit n-number of likes (lets say every 100th like), i.e., whenever the 'netLike' counter hits 100, it automatically mints one token to the respective user's address.\n\nAnd because there's a dislike function as well, the user should not be rewarded the token every time the likeCounter hits 100, (for example - if a user hits 100th like for the first time, its rewarded with one erc token, and once it hits that milestone, in order to earn 2nd token, it must hit the milestone of 200 likes, and likewise every multiple of 100 can only generate one token 'one-time')\n\nI've added nonce for this purpose, but couldn't really figure out the exact logic!! (brainfog 😊) The logic and the _mint() fn is inside the like function.\n\nThanks!!\n\n```\nContent[] public contents;\n \n // A mapping of Content Hashes to their respective Owners\n mapping(bytes32 => address) public contentHashToAuthor;\n \n \n //Contains all the indices of content uploaded by the author\n mapping(address => uint256[]) public authorToContentIndices;\n \n \n //A mapping of contentHash to contentIndex\n mapping(bytes32 => uint256) contentIndex;\n \n \n \n //the struct that contains the content-Info\n struct Content{\n bytes32 hash;\n string[] tags;\n address author;\n uint256 likes;\n uint256 dislikes;\n int256 netLikes;\n uint256 nonce;\n uint64 timeStamp;\n }\n \n \nfunction addContent(bytes32[] memory _hash, string[][] memory _tags) public {\n \n for(uint256 i = 0; i bool) usersLiked;\n mapping(address => bool) usersDisliked;\n timeStamp: uint64(now)\n });\n \n uint256 contentIndex = contents.push(_content) - 1;\n authorToContentIndices[msg.sender].push(contentIndex);\n contentHashToAuthor[_hash[i]] = msg.sender;\n contentIndices[_hash[i]] = contentIndex;\n \n } else {\n revert(\"Content already Exist!\")\n }\n \n }\n\n \n}\n\nfunction like(bytes32 _hash) public {\n uint256 cId = contentIndex[_hash];\n Content storage c = contents[cId];\n if(c.usersLiked[msg.sender] != true){\n c.usersLiked[msg.sender] = true;\n if(c.usersDisliked[msg.sender] == true){\n c.usersDisliked[msg.sender] == false;\n c.dislikes--;\n }\n c.likes++;\n c.netLikes++;\n //logic for rewarding ERC777 for every 100th netLike. \n //todo\n if(c.netLikes == 100){\n //mint function to hit with every 100th netLike\n _mint(c.author, 1, \"\", \"\");\n }\n \n } else {\n revert(\"Already liked!\")\n }\n \n }\n\n function dislike(bytes32 _hash) public {\n uint256 cId = contentIndex[_hash];\n Content storage c = contents[cId];\n if(c.usersDisliked[msg.sender] != true){\n c.usersDisliked[msg.sender] = true;\n if(c.usersLiked == true){\n c.usersLiked == false;\n c.likes--;\n c.netLikes--;\n }\n c.dislikes++;\n c.netLikes--;\n } else {\n revert(\"Already disliked!\")\n }\n \n }\n```\n\n========================================\n\nCode:\n```text\nContent[] public contents;\n    \n    // A mapping of Content Hashes to their respective Owners\n    mapping(bytes32 => address) public contentHashToAuthor;\n    \n  \n    //Contains all the indices of content uploaded by the author\n    mapping(address => uint256[]) public authorToContentIndices;\n    \n    \n    //A mapping of contentHash to contentIndex\n    mapping(bytes32 => uint256) contentIndex;\n    \n    \n \n    //the struct that contains the content-Info\n    struct Content{\n        bytes32 hash;\n        string[] tags;\n        address author;\n        uint256 likes;\n        uint256 dislikes;\n        int256 netLikes;\n        uint256 nonce;\n        uint64 timeStamp;\n    }\n    \n  \nfunction addContent(bytes32[] memory _hash, string[][] memory _tags) public {\n    \n    for(uint256 i = 0; i < _hash.length; i++ ){\n        \n        if(contentHashToAuthor[_hash[i]] == 0) {\n            \n            Content memory _content = new Content({\n                hash: _hash[i],\n                tags: _tags[i][],\n                author: msg.sender\n                like: 0,\n                dislikes: 0,\n                netLikes: 0,\n                nonce: 0,\n                mapping(address => bool) usersLiked;\n                mapping(address => bool) usersDisliked;\n                timeStamp: uint64(now)\n            });\n            \n            uint256 contentIndex = contents.push(_content) - 1;\n            authorToContentIndices[msg.sender].push(contentIndex);\n            contentHashToAuthor[_hash[i]] = msg.sender;\n            contentIndices[_hash[i]] = contentIndex;\n        \n        } else {\n            revert(\"Content already Exist!\")\n        }\n        \n    }\n\n    \n}\n\n\n\nfunction like(bytes32 _hash) public {\n            uint256 cId = contentIndex[_hash];\n            Content storage c = contents[cId];\n            if(c.usersLiked[msg.sender] != true){\n                c.usersLiked[msg.sender] = true;\n                if(c.usersDisliked[msg.sender] == true){\n                    c.usersDisliked[msg.sender] == false;\n                    c.dislikes--;\n                }\n                c.likes++;\n                c.netLikes++;\n                //logic for rewarding ERC777 for every 100th netLike. \n                //todo\n                if(c.netLikes == 100){\n                      //mint function to hit with every 100th netLike\n                     _mint(c.author, 1, \"\", \"\");\n                }\n                \n            } else {\n                revert(\"Already liked!\")\n            }\n            \n    }\n\n  function dislike(bytes32 _hash) public {\n            uint256 cId = contentIndex[_hash];\n            Content storage c = contents[cId];\n            if(c.usersDisliked[msg.sender] != true){\n                c.usersDisliked[msg.sender] = true;\n                if(c.usersLiked == true){\n                    c.usersLiked == false;\n                    c.likes--;\n                    c.netLikes--;\n                }\n                c.dislikes++;\n                c.netLikes--;\n            } else {\n                revert(\"Already disliked!\")\n            }\n            \n    }\n```\n\n```text\nstruct Content{\n    // ... rest of your code\n    uint8 rewards; // Max value of uint8 is 255, which represents 25.5k netLikes. If that's not sufficient, use uint16.\n}\n```\n\n```text\nif(c.netLikes % 100 == 0 && c.netLikes / 100 == c.rewards + 1){\n      //mint function to hit with every 100th netLike\n     _mint(c.author, 1, \"\", \"\")\n     c.rewards++;\n}\n```\n\n```text\nrewards\n```\n\n```text\nstruct Content\n```\n\n```text\nif(c.netLikes == 100)\n```\n\n```text\nc.netLikes % 100 == 0\n```\n\n```text\nnetLikes\n```\n\n```text\nc.netLikes / 100 == c.rewards + 1\n```\n\n```text\nnetLikes\n```\n\n```text\nlikes\n```\n\n```text\ndislikes\n```\n\n```text\nrewards\n```\n\n```text\nlikes\n```\n\n```text\nnetLikes\n```\n\n```text\nc.netLikes % 100 == 0\n```\n\n```text\n100 % 100 == 0\n```\n\n```text\nc.netLikes / 100 == c.rewards + 1\n```\n\n```text\n100 / 100 == 0 + 1\n```\n\n```text\n_mint()\n```\n\n```text\nrewards\n```\n\n```text\nnetLikes\n```\n\n```text\nlikes\n```\n\n```text\ndislikes\n```\n\n```text\nrewards\n```\n\n```text\ndislikes\n```\n\n```text\nnetLikes\n```\n\n```text\nnetLikes\n```\n\n```text\nlikes\n```\n\n```text\ndislikes\n```\n\n```text\nrewards\n```\n\n```text\nlikes\n```\n\n```text\nnetLikes\n```\n\n```text\nc.netLikes % 100 == 0\n```\n\n```text\n100 % 100 == 0\n```\n\n```text\nc.netLikes / 100 == c.rewards + 1\n```\n\n```text\n100 / 100 == 1 + 1\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":37,"totalLines":366,"estimatedTokens":1817}}348{"id":"stack-65780594","source":"stackoverflow","questionId":65780594,"title":"TypeError: Cannot read property 'compile' of undefined","tags":["javascript","compilation","ethereum","solidity"],"text":"Title: TypeError: Cannot read property 'compile' of undefined\nTags: javascript, compilation, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI'm currently trying to this tutorial for Ethereum Solidity coding, and for the following code:\n\n```\nconst path = require('path');\nconst fs = require('fs'); // File system module\nconst solc = require('solc').default; // Solidity Compiler module\n\n// Note that phrase resolving a link means to substitute the actual location in the file system for the symbolic link\n// If we assume that logFile is a symbolic link to dir/logs/HomeLogFile, then resolving it yields dir/logs/HomeLogFile\n\n// Generates a path that points directly to the inbox file. __dirname will be the root direction\n// inboxPath = desktop/inbox/contracts/inbox.sol\nconst inboxPath = path.resolve(__dirname, 'contracts', 'inbox.sol');\n\n// The next step is to actually read the contents of the source file now\n// utf8 is the encoding to read the file's content\nconst source = fs.readFileSync(inboxPath, 'utf8');\n\n// Call solc.compile and pass in our source code, with only 1 contract \n// console.log() means put the output in the console\nconsole.log(solc.compile(source, 1));\n```\n\nI get the following error when I hover over `const solc = require('solc').default`:\n\n```\nCould not find a declaration file for module 'solc'. 'c:/Users/Hana PC/Desktop/inbox/node_modules/solc/index.js' implicitly has an 'any' type.\n Try `npm i --save-dev @types/solc` if it exists or add a new declaration (.d.ts) file containing `declare module 'solc';`ts(7016)\n```\n\nWhen I try `node compile.js`, I get:\n\n```\nC:\\Users\\Hana PC\\Desktop\\inbox\\compile.js:18\nconsole.log(solc.compile(source, 1));\n ^\n\nTypeError: Cannot read property 'compile' of undefined\n at Object. (C:\\Users\\Hana PC\\Desktop\\inbox\\compile.js:18:18)\n[90m at Module._compile (internal/modules/cjs/loader.js:1063:30)[39m\n[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)[39m\n[90m at Module.load (internal/modules/cjs/loader.js:928:32)[39m\n[90m at Function.Module._load (internal/modules/cjs/loader.js:769:14)[39m\n[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)[39m\n[90m at internal/main/run_main_module.js:17:47[39m\n```\n\nI've never used/interacted with TypeScript or JavaScript or anything of the sorts, so I honestly don't even know what this error means. I've already tried uninstalling and reinstalling solc multiple times, all to no avail.\n\nMy node.js version is:\n\n```\n6.14.8\n```\n\nI tried doing some searching online for what the `implicitly has an 'any' type.` means or how it could be fixed, but I honestly didn't get any of it. If it helps, my `package.json` looks like this:\n\n```\n{\n\n\"name\": \"inbox\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"compile.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"solc\": \"^0.8.0\"\n }\n}\n```\n\nAny help is appreciated!\n\n**** Update:**\n\nTried it with uninstall solc and a fresh install (without using version 0.4.17), and got an Assertion Error:\n\n```\nassert.js:383\n throw err;\n ^\n\nAssertionError [ERR_ASSERTION]: Invalid callback object specified.\n at runWithCallbacks (C:\\Users\\Hana PC\\Desktop\\inbox\\node_modules\\[4msolc[24m\\wrapper.js:97:7)\n at compileStandard (C:\\Users\\Hana PC\\Desktop\\inbox\\node_modules\\[4msolc[24m\\wrapper.js:207:14)\n at Object.compileStandardWrapper [as compile] (C:\\Users\\Hana PC\\Desktop\\inbox\\node_modules\\[4msolc[24m\\wrapper.js:214:14)\n```\n\nWish I knew what was goin on\n\n========================================\n\nCode:\n```text\nconst path = require('path');\nconst fs =  require('fs');        // File system module\nconst solc = require('solc').default;    // Solidity Compiler module\n\n// Note that phrase resolving a link means to substitute the actual location in the file system for the symbolic link\n// If we assume that logFile is a symbolic link to dir/logs/HomeLogFile, then resolving it yields dir/logs/HomeLogFile\n\n// Generates a path that points directly to the inbox file. __dirname will be the root direction\n// inboxPath = desktop/inbox/contracts/inbox.sol\nconst inboxPath = path.resolve(__dirname, 'contracts', 'inbox.sol');\n\n// The next step is to actually read the contents of the source file now\n// utf8 is the encoding to read the file's content\nconst source = fs.readFileSync(inboxPath, 'utf8');\n\n// Call solc.compile and pass in our source code, with only 1 contract \n// console.log() means put the output in the console\nconsole.log(solc.compile(source, 1));\n```\n\n```text\nCould not find a declaration file for module 'solc'. 'c:/Users/Hana PC/Desktop/inbox/node_modules/solc/index.js' implicitly has an 'any' type.\n  Try `npm i --save-dev @types/solc` if it exists or add a new declaration (.d.ts) file containing `declare module 'solc';`ts(7016)\n```\n\n```text\nC:\\Users\\Hana PC\\Desktop\\inbox\\compile.js:18\nconsole.log(solc.compile(source, 1));\n                 ^\n\nTypeError: Cannot read property 'compile' of undefined\n    at Object.<anonymous> (C:\\Users\\Hana PC\\Desktop\\inbox\\compile.js:18:18)\n[90m    at Module._compile (internal/modules/cjs/loader.js:1063:30)[39m\n[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)[39m\n[90m    at Module.load (internal/modules/cjs/loader.js:928:32)[39m\n[90m    at Function.Module._load (internal/modules/cjs/loader.js:769:14)[39m\n[90m    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)[39m\n[90m    at internal/main/run_main_module.js:17:47[39m\n```\n\n```text\n6.14.8\n```\n\n```text\n{\n\n\"name\": \"inbox\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"compile.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"solc\": \"^0.8.0\"\n  }\n}\n```\n\n```text\nassert.js:383\n    throw err;\n    ^\n\nAssertionError [ERR_ASSERTION]: Invalid callback object specified.\n    at runWithCallbacks (C:\\Users\\Hana PC\\Desktop\\inbox\\node_modules\\[4msolc[24m\\wrapper.js:97:7)\n    at compileStandard (C:\\Users\\Hana PC\\Desktop\\inbox\\node_modules\\[4msolc[24m\\wrapper.js:207:14)\n    at Object.compileStandardWrapper [as compile] (C:\\Users\\Hana PC\\Desktop\\inbox\\node_modules\\[4msolc[24m\\wrapper.js:214:14)\n```\n\n```text\nconst solc = require('solc').default\n```\n\n```text\nnode compile.js\n```\n\n```text\nimplicitly has an 'any' type.\n```\n\n```text\npackage.json\n```\n\n```text\nv0.4.17\n```\n\n```text\nsolc\n```\n\n```text\nv0.4.17\n```\n\n```text\nconst solc = require(\"solc\");\n```\n\n```text\nconst solc = require(\"solc\").default;\n```\n\n```text\nsolc\n```\n\n```text\npackage-lock.json\n```\n\n```text\nnode_modules/\n```\n\n```text\npackage.json\n```\n\n```text\n\"solc\": \"0.4.17\"\n```\n\n```text\n\"^0.4.17\"\n```\n\n```text\nnpm install\n```\n\n========================================\n\nComments:\n- You should check the documentation\n- Thing is, I did see that, I just didn't understand anything, so I was hoping someone could help somehow.\n- Your npm install you have used version `0.4.17`, but your package.json says `\"solc\": \"^0.8.0\"`. It's possible the older version does not have the `compile` function. Maybe run `npm uninstall solc` and the just do a full `npm install` on your project to get all non-installed packages.\n- Did that! Now I got an AssertionError: assert.js:383 throw err; ^ AssertionError [ERR_ASSERTION]: Invalid callback object specified. at runWithCallbacks (C:\\Users\\Hana PC\\Desktop\\inbox\\node_modules&#91;4msolc[24m\\wrapper.js:97:7&zwnj;&#8203;) at compileStandard (C:\\Users\\Hana PC\\Desktop\\inbox\\node_modules&#91;4msolc[24m\\wrapper.js:207:&zwnj;&#8203;14) at Object.compileStandardWrapper [as compile] (C:\\Users\\Hana PC\\Desktop\\inbox\\node_modules&#91;4msolc[24m\\wrapper.js:214:&zwnj;&#8203;14)\n- Switch back to v0.8.0 and change the import on line #3 to`const solc = require('solc');` I could get Example usage without the import callback running without any issue but I am not so sure about the `.sol` files so you are on your own on that.\n- I see. If it's fine asking, do you think the issue is then in my .sol file?\n- I am not sure.. Could you provide me a valid sol file for me to try? Maybe from a tutorial site or the official guides or hosted somewhere on github. I am sorry but I am out of my comfort zone here and don't know anything about sol files to determine it's validity.\n- Here: pragma solidity ^0.4.17; contract inbox { string public message; function inbox(string initialMessage) public { message = initialMessage; } function setMessage(string newMessage) public { message = newMessage; } }\n- Since this solidity file is using v0.4.17, I had to switch the npm package version back to v0.4.17 instead of v0.8.0. And then it just worked with your js code only.. just remember to remove the `.default` on line #3.\n- It worked?? I tried it again, it didnt work :(\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":254,"estimatedTokens":2213}}349{"id":"stack-73510352","source":"stackoverflow","questionId":73510352,"title":"Solidity: Using mapping and code design for lottery contract address","tags":["struct","mapping","ethereum","solidity","smartcontracts"],"text":"Title: Solidity: Using mapping and code design for lottery contract address\nTags: struct, mapping, ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI'm writing the Lottery Contract. Since gas cost is high, I wanted to use mapping instead of an array and I defined id in struct. However, I could not get out of the code structure. How to determine the winner and how to empty the address book after the winner.\n\n```\n// SPDX-License-Identifier: MIT\n\n pragma solidity ^0.8.7;\n \n contract freeLottery {\n address public owner;\n uint public lotteryId;\n mapping (uint => address payable) public lotteryHistory;\n \n struct Players {\n bool isWinner;\n uint id;\n }\n \n mapping (address => Players) players;\n uint playersCount=0;\n \n constructor() {\n owner = msg.sender;\n lotteryId = 1;\n }\n \n function getWinner(uint lottery) public view returns (address payable) {\n return lotteryHistory[lottery];\n }\n \n function getBalance() public view returns (uint) {\n return address(this).balance;\n }\n \n function enter() public payable { \n players[msg.sender];\n playersCount++; \n } \n \n \n \n function contribute() public payable onlyowner{\n require(msg.value>0,\"Please send an amount greater than 0\");\n } \n \n function getRandomNumber() internal view returns (uint) {\n return uint(keccak256(abi.encodePacked(owner, block.timestamp)));\n }\n \n function pickWinner() public onlyowner {\n require(address(this).balance>0,\"Please upload balance\");\n uint index = getRandomNumber() % ???;\n ???\n \n ???\n \n lotteryHistory[lotteryId] = players[id];\n lotteryId++;\n \n // reset the state of the contract\n ???;\n }\n \n modifier onlyowner() {\n require(msg.sender == owner);\n _;\n }\n }\n```\n\n========================================\n\nCode:\n```text\n// SPDX-License-Identifier: MIT\n\n    pragma solidity ^0.8.7;\n    \n    contract freeLottery {\n        address public owner;\n        uint public lotteryId;\n        mapping (uint => address payable) public lotteryHistory;\n        \n       struct Players {\n            bool isWinner;\n            uint id;\n        }\n    \n        mapping (address => Players) players;\n        uint playersCount=0;\n        \n        constructor() {\n            owner = msg.sender;\n            lotteryId = 1;\n        }\n    \n        function getWinner(uint lottery) public view returns (address payable) {\n            return lotteryHistory[lottery];\n        }\n    \n        function getBalance() public view returns (uint) {\n            return address(this).balance;\n        }\n    \n        function enter() public payable {        \n            players[msg.sender];\n            playersCount++;    \n        }               \n    \n        \n    \n        function contribute() public payable onlyowner{\n            require(msg.value>0,\"Please send an amount greater than 0\");\n        }       \n    \n        function getRandomNumber() internal view returns (uint) {\n            return uint(keccak256(abi.encodePacked(owner, block.timestamp)));\n        }\n    \n        function pickWinner() public onlyowner {\n            require(address(this).balance>0,\"Please upload balance\");\n            uint index = getRandomNumber() % ???;\n            ???\n    \n            ???\n    \n            lotteryHistory[lotteryId] = players[id];\n            lotteryId++;\n    \n            // reset the state of the contract\n            ???;\n        }\n    \n        modifier onlyowner() {\n          require(msg.sender == owner);\n          _;\n        }\n    }\n```\n\n```text\n// this will take care of storing in mapping instead of array\n    mapping (uint => address) players;\n    uint playersCount=0;\n```\n\n```text\nfunction enter() public payable {    \n            // initially playersCount is 0. so increase it first  \n            playersCount++;\n            // payable vs normal address has different methods. for storing it wont matter  \n            players[playersCount]=payable(msg.sender);       \n        }\n```\n\n```text\nfunction pickWinner() public onlyowner returns (address payable) {\n            require(address(this).balance>0,\"Please upload balance\");\n            uint index = getRandomNumber() % playersCount;\n            address payable winner=payable(players[index]);\n            \n            lotteryHistory[lotteryId] = winner;\n            // since you inialized lotteryId=1 in constructor\n            lotteryId++;\n    \n            // for resetting, you have to do for loop\n            for (uint i=0; i< playersCount ; i++) {\n                 delete players[i];\n            }     \n            return winner   ;   \n        }\n```\n\n```text\nlotteryId => playersCount => address\n```\n\n```text\n1 => playersCount => address\n```\n\n```text\n2 => playersCount => address\n```\n\n```text\nfunction enter() public payable {    \n            // initially playersCount is 0. so increase it first  \n            playersCount++;\n            // payable vs normal address has different methods. for storing it wont matter  \n            players[lotteryId][playersCount]=msg.sender;       \n        }\n```\n\n```text\nPlayers\n```\n\n```text\nlotteryHistory\n```\n\n```text\nplayers\n```\n\n```text\nenter\n```\n\n```text\npickWinner\n```\n\n```text\nplayers\n```\n\n```text\nlotteryId\n```\n\n```text\npickWinner\n```\n\n```text\nlotteryId++\n```\n\n```text\nplayersCount=0\n```\n\n```text\nenter\n```\n\n========================================\n\nComments:\n- one correction: `address payable winner=payable(players[lotteryId][index])`;","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":246,"estimatedTokens":1331}}350{"id":"stack-69887774","source":"stackoverflow","questionId":69887774,"title":"TypeError: path.resolve is not a function","tags":["reactjs","next.js","ethereum","solidity","web3js"],"text":"Title: TypeError: path.resolve is not a function\nTags: reactjs, next.js, ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI finished up an Ethereum smart contract course on Udemy that used solc@^0.4.17, React and Next.js. I thought it would be a fun exercise to try and upgrade everything to the latest version and try to refactor. I have the following code in a file called `factory.js` being imported into my main index file:\n\n```\nimport web3 from './web3';\nconst path = require('path');\nconst fs = require('fs');\n\nconst abiPath = path.resolve('ethereum/build', 'CampaignFactory.abi');\nconsole.log(abiPath);\n\nconst abi = fs.readFileSync(abiPath, 'utf8');\nconsole.log(abi);\n\nconst factory = new web3.eth.Contract(\n JSON.parse(abi),\n '0x2d54559dCe0DA6C92378A916e9eE0422CEFFCD80'\n);\n\nexport default factory;\n```\n\nInside of my main index file I'm calling it like so:\n\n```\nimport factory from '../ethereum/factory';\n...\nclass CampaignIndex extends Component {\n static async getInitialProps() {\n const campaigns = await factory.methods.getDeployedCampaigns().call();\n\n return { campaigns };\n }\n...\n```\n\nHere's the console.log:\n\n```\nwait - compiling /...\n event - compiled successfully in 637 ms (1422 modules)\n /Users/sonnyparlin/Github/kickstart/ethereum/build/CampaignFactory.abi\n [\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"minimum\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"createCampaign\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"deployedCampaigns\",\n \"outputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [],\n \"name\": \"getDeployedCampaigns\",\n \"outputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"\",\n \"type\": \"address[]\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n }\n ]\n```\n\nThe console log confirms that `path.resolve()` is actually working, but when I go to the page via the web browser I see the following error:\n\nhttps://i.sstatic.net/m0xio.png\n\n```\nCall Stack\nModule../ethereum/factory.js\nfile:///Users/sonnyparlin/Github/kickstart/.next/static/chunks/pages/index.js (1148:1)\nModule.options.factory\n/_next/static/chunks/webpack.js (638:31)\n__webpack_require__\nfile:///Users/sonnyparlin/Github/kickstart/.next/static/chunks/webpack.js (37:33)\nfn\n/_next/static/chunks/webpack.js (307:21)\neval\nwebpack-internal:///./pages/index.js (9:75)\nModule../pages/index.js\nfile:///Users/sonnyparlin/Github/kickstart/.next/static/chunks/pages/index.js (1192:1)\nModule.options.factory\n/_next/static/chunks/webpack.js (638:31)\n__webpack_require__\nfile:///Users/sonnyparlin/Github/kickstart/.next/static/chunks/webpack.js (37:33)\nfn\n/_next/static/chunks/webpack.js (307:21)\neval\nnode_modules/next/dist/build/webpack/loaders/next-client-pages-loader.js?page=%2F&absolutePagePath=%2FUsers%2Fsonnyparlin%2FGithub%2Fkickstart%2Fpages%2Findex.js! (5:15)\neval\nnode_modules/next/dist/client/route-loader.js (236:50)\n```\n\nMy guess is that this is really some kind of versioning or dependency issue, so I'm also including my package.json file:\n\n```\n{\n \"name\": \"kickstart\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"mocha\",\n \"dev\": \"node server.js\"\n },\n \"author\": \"\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"@truffle/hdwallet-provider\": \"^1.0.37\",\n \"fs-extra\": \"^10.0.0\",\n \"ganache-cli\": \"^6.1.8\",\n \"mocha\": \"^9.1.3\",\n \"next\": \"^12.0.3\",\n \"next-routes\": \"^1.4.2\",\n \"react\": \"^17.0.2\",\n \"react-dom\": \"^17.0.2\",\n \"semantic-ui-css\": \"^2.4.1\",\n \"semantic-ui-react\": \"^2.0.4\",\n \"solc\": \"^0.8.9\",\n \"web3\": \"^1.6.0\"\n },\n \"browser\": {\n \"fs\": false,\n \"path\": false,\n \"os\": false\n }\n}\n```\n\nAnd a listing of my project files:\n\nhttps://i.sstatic.net/lS2Xy.png\n\n========================================\n\nCode:\n```text\nimport web3 from './web3';\nconst path = require('path');\nconst fs = require('fs');\n\nconst abiPath = path.resolve('ethereum/build', 'CampaignFactory.abi');\nconsole.log(abiPath);\n\nconst abi = fs.readFileSync(abiPath, 'utf8');\nconsole.log(abi);\n\nconst factory = new web3.eth.Contract(\n    JSON.parse(abi),\n    '0x2d54559dCe0DA6C92378A916e9eE0422CEFFCD80'\n);\n\nexport default factory;\n```\n\n```text\nimport factory from '../ethereum/factory';\n...\nclass CampaignIndex extends Component {\n    static async getInitialProps() {\n        const campaigns = await factory.methods.getDeployedCampaigns().call();\n\n        return { campaigns };\n    }\n...\n```\n\n```text\nwait  - compiling /...\n    event - compiled successfully in 637 ms (1422 modules)\n    /Users/sonnyparlin/Github/kickstart/ethereum/build/CampaignFactory.abi\n    [\n      {\n        \"inputs\": [\n          {\n            \"internalType\": \"uint256\",\n            \"name\": \"minimum\",\n            \"type\": \"uint256\"\n          }\n        ],\n        \"name\": \"createCampaign\",\n        \"outputs\": [],\n        \"stateMutability\": \"nonpayable\",\n        \"type\": \"function\"\n      },\n      {\n        \"inputs\": [\n          {\n            \"internalType\": \"uint256\",\n            \"name\": \"\",\n            \"type\": \"uint256\"\n          }\n        ],\n        \"name\": \"deployedCampaigns\",\n        \"outputs\": [\n          {\n            \"internalType\": \"address\",\n            \"name\": \"\",\n            \"type\": \"address\"\n          }\n        ],\n        \"stateMutability\": \"view\",\n        \"type\": \"function\"\n      },\n      {\n        \"inputs\": [],\n        \"name\": \"getDeployedCampaigns\",\n        \"outputs\": [\n          {\n            \"internalType\": \"address[]\",\n            \"name\": \"\",\n            \"type\": \"address[]\"\n          }\n        ],\n        \"stateMutability\": \"view\",\n        \"type\": \"function\"\n      }\n    ]\n```\n\n```text\nCall Stack\nModule../ethereum/factory.js\nfile:///Users/sonnyparlin/Github/kickstart/.next/static/chunks/pages/index.js (1148:1)\nModule.options.factory\n/_next/static/chunks/webpack.js (638:31)\n__webpack_require__\nfile:///Users/sonnyparlin/Github/kickstart/.next/static/chunks/webpack.js (37:33)\nfn\n/_next/static/chunks/webpack.js (307:21)\neval\nwebpack-internal:///./pages/index.js (9:75)\nModule../pages/index.js\nfile:///Users/sonnyparlin/Github/kickstart/.next/static/chunks/pages/index.js (1192:1)\nModule.options.factory\n/_next/static/chunks/webpack.js (638:31)\n__webpack_require__\nfile:///Users/sonnyparlin/Github/kickstart/.next/static/chunks/webpack.js (37:33)\nfn\n/_next/static/chunks/webpack.js (307:21)\neval\nnode_modules/next/dist/build/webpack/loaders/next-client-pages-loader.js?page=%2F&absolutePagePath=%2FUsers%2Fsonnyparlin%2FGithub%2Fkickstart%2Fpages%2Findex.js! (5:15)\neval\nnode_modules/next/dist/client/route-loader.js (236:50)\n```\n\n```text\n{\n  \"name\": \"kickstart\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"mocha\",\n    \"dev\": \"node server.js\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"@truffle/hdwallet-provider\": \"^1.0.37\",\n    \"fs-extra\": \"^10.0.0\",\n    \"ganache-cli\": \"^6.1.8\",\n    \"mocha\": \"^9.1.3\",\n    \"next\": \"^12.0.3\",\n    \"next-routes\": \"^1.4.2\",\n    \"react\": \"^17.0.2\",\n    \"react-dom\": \"^17.0.2\",\n    \"semantic-ui-css\": \"^2.4.1\",\n    \"semantic-ui-react\": \"^2.0.4\",\n    \"solc\": \"^0.8.9\",\n    \"web3\": \"^1.6.0\"\n  },\n  \"browser\": {\n    \"fs\": false,\n    \"path\": false,\n    \"os\": false\n  }\n}\n```\n\n```text\nfactory.js\n```\n\n```text\npath.resolve()\n```\n\n```text\nnode fileName.js\n```\n\n```text\nimport abi from \"directory/file.json\"\n\nconst factory = new web3.eth.Contract(\n    // pass the abi\n    JSON.parse(abi),\n    '0x2d54559dCe0DA6C92378A916e9eE0422CEFFCD80'\n);\n```\n\n```text\npath\n```\n\n```text\nfs\n```\n\n```text\nsolc\n```\n\n========================================\n\nComments:\n- Where exactly in your `index.js` file are you using `factory`? That will break if you use it in client-side code as it's using Node.js APIs (`path` & `fs`).\n- It's only being used in getInitialProps(), which I understand is legal.\n- Not quite. `getInitialProps` runs both on the server (first page load) and on the client (client-side page navigation).","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":352,"estimatedTokens":2010}}351{"id":"stack-49339297","source":"stackoverflow","questionId":49339297,"title":"Calling External Contract throws error : VM Exception while processing transaction: revert","tags":["ethereum","solidity","smartcontracts","truffle"],"text":"Title: Calling External Contract throws error : VM Exception while processing transaction: revert\nTags: ethereum, solidity, smartcontracts, truffle\nSource: Stack Overflow\n\nQuestion:\nI've deployed the ScoreStore contract to test RPC, and it works fine. This is ScoreStore contract:\n\n```\npragma solidity ^0.4.4;\ncontract ScoreStore \n{\n mapping(string => int) PersonScores;\n\n function SetScore(string name, int score) {\n if(PersonScores[name]>0){\n throw;\n }\n else{\n PersonScores[name] = score;\n }\n }\n\n function GetScore(string name) returns (int){\n return PersonScores[name];\n }\n}\n```\n\nNow I want to use this contract on another contract named MyGame, the contract code is as follows:\n\n```\npragma solidity ^0.4.4;\ncontract IScoreStore{\n function GetScore(string name) returns (int);\n}\ncontract MyGame{\n function ShowScore(string name) returns (int){\n // Interface takes an address of the existing contract as parameter\n IScoreStore ss = IScoreStore(0x6c38cfb90e8fb1922e61ea4fbe09d29c7751bf82); \n return ss.GetScore(name);\n }\n}\n```\n\nWhen I give this command on truffle console, `mg.ShowScore.call(\"Anna\")`\nit thorws this: \n\n```\nError: VM Exception while processing transaction: revert\n at XMLHttpRequest._onHttpResponseEnd (C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\xhr2\\lib\\xhr2.js:509:1)\n at XMLHttpRequest._setReadyState (C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\xhr2\\lib\\xhr2.js:354:1)\n at XMLHttpRequestEventTarget.dispatchEvent (C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\xhr2\\lib\\xhr2.js:64:1)\n at XMLHttpRequest.request.onreadystatechange (C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\web3\\lib\\web3\\httpprovider.\n at C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\truffle-provider\\wrapper.js:134:1\n at C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\web3\\lib\\web3\\requestmanager.js:86:1\n at Object.InvalidResponse (C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\web3\\lib\\web3\\errors.js:38:1)\n```\n\nAny idea, what i am doing wrong? \nAny help is appreciated, P.S: testrpc is already running.\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.4;\ncontract ScoreStore \n{\n    mapping(string => int) PersonScores;\n\n    function SetScore(string name, int score) {\n        if(PersonScores[name]>0){\n            throw;\n        }\n        else{\n            PersonScores[name] = score;\n        }\n    }\n\n    function GetScore(string name) returns (int){\n        return PersonScores[name];\n    }\n}\n```\n\n```text\npragma solidity ^0.4.4;\ncontract IScoreStore{\n    function GetScore(string name) returns (int);\n}\ncontract MyGame{\n    function ShowScore(string name) returns (int){\n        // Interface takes an address of the existing contract as parameter\n        IScoreStore ss = IScoreStore(0x6c38cfb90e8fb1922e61ea4fbe09d29c7751bf82); \n        return ss.GetScore(name);\n    }\n}\n```\n\n```text\nError: VM Exception while processing transaction: revert\n    at XMLHttpRequest._onHttpResponseEnd (C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\xhr2\\lib\\xhr2.js:509:1)\n    at XMLHttpRequest._setReadyState (C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\xhr2\\lib\\xhr2.js:354:1)\n    at XMLHttpRequestEventTarget.dispatchEvent (C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\xhr2\\lib\\xhr2.js:64:1)\n    at XMLHttpRequest.request.onreadystatechange (C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\web3\\lib\\web3\\httpprovider.\n    at C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\truffle-provider\\wrapper.js:134:1\n    at C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\web3\\lib\\web3\\requestmanager.js:86:1\n    at Object.InvalidResponse (C:\\Users\\Fariha.Abbasi\\AppData\\Roaming\\npm\\node_modules\\truffle\\build\\webpack:\\~\\web3\\lib\\web3\\errors.js:38:1)\n```\n\n```text\nmg.ShowScore.call(\"Anna\")\n```\n\n========================================\n\nComments:\n- Thanks I re-tested it on remix and it work fine. To my surprise, I re-deployed it again on testrpc as well and run via truffle and it works fine. Thanks, anyway.","metadata":{"transformedAt":"2026-08-18T18:33:36.141Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":118,"estimatedTokens":1092}}352{"id":"stack-70886680","source":"stackoverflow","questionId":70886680,"title":"Displaying the transaction value of a custom ERC20 function in MetaMask","tags":["javascript","solidity","erc20"],"text":"Title: Displaying the transaction value of a custom ERC20 function in MetaMask\nTags: javascript, solidity, erc20\nSource: Stack Overflow\n\nQuestion:\nI have created a new contract on Polygon based on ERC20 with a couple of extra public functions. And am having trouble with communicating what the user is doing to MetaMask.\n\nWhen I perform a normal ERC20 transfer() transaction, the signature popup correctly showing the value, in myNewToken, of the transaction plus MATIC gas. BUT if I use my new commissionTransfer() transaction, which, on the contract, sends a portion of the payment to the payee and a portion to \"the house\" as commission, the signature popup doesn't show the value of the transaction, just the gas fee.\n\nIf the user signs the transaction it goes through OK, with the right number of tokens going to the right addresses, but I really need the user to be able to have visibility of what they are signing. It shows if I add a \"value: amount\" to the transaction but that turns the transaction into a MATIC transfer, not my token.\n\nThis is how I execute a commissionTransfer().\n\n```\nconst tx = {\n from: userAddress,\n to: contractAddress,\n data: contract.methods.commissionTransfer(payeeAddress, \n totalTransactionValue).encodeABI()\n}\nconst sentTx = await web3.eth.sendTransaction(tx)\n```\n\nSo. My question is, where does MetaMask get the transaction value it displays from? Is it from the transaction object? Is it from the Transfer event in the contract (so does the fact I have two calls to _transfer() in my transaction cause problems)? Is there a way of instructing MetaMask which value needs to be displayed to the user?\n\nIn case it's helpful, here is the smart contract method. The commission value (in tenths of a percent) is global and set by another method.\n\n```\nfunction commissionTransfer(address recipient, uint256 amount) public virtual returns (bool) {\n address sender = _msgSender();\n uint256 senderBalance = balanceOf(sender);\n require(senderBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n uint256 payAmount = (amount / 1000) * (1000 - commission);\n uint256 comAmount = amount - payAmount;\n _transfer(sender, recipient, payAmount);\n _transfer(sender, theHouse, comAmount);\n return true;\n}\n```\n\nSolution used:\n\nFollowing the response from NuMa below it seems that MetaMask uses the signature of the transfer() function to determine whether it is being used. That is derived from the name (\"transfer\") and argument types (address, unit256) so any attempt to change the arguments failed to display on MetaMask.\n\nOne method that got around this was to remove 1 wei from the amount within my app and have the contract apply commission to transaction values if (amount % 100000) == 99999. This worked absolutely fine but was confusing for the user to see all those 9s when signing off the transaction.\n\nThe method I will probably go with is to create a new contract whose only job is to interface with my token and call the commissionTransfer() function from a transfer() function of its own. That way, in my app, I can control whether commission is applied by which contract is called. The code for the commission contract is:\n\n```\ninterface IToken {\n function commissionTransfer(address, address, uint256) external returns (bool);\n}\n\ncontract tokenCommission {\n address tokenAddress=0xetc;\n\n function transfer(address recipient, uint256 amount) public returns (bool) {\n return IToken(tokenAddress).commissionTransfer(msg.sender, recipient, amount);\n }\n\n function decimals() public view virtual returns (uint8) {\n return 18;\n }\n}\n```\n\nI also had to change my commissionTransfer() function to include the sender address and validate that the msg.sender is the new commission contract.\n\nThe decimals() function appears to be used by MetaMask to show the correct order of token so that was required as well. Once that is done, MetaMask recognises the transfer() function as if it were from an ERC20 contract.\n\nIf more elegant solutions are found that would be great.\n\n========================================\n\nCode:\n```text\nconst tx = {\n   from: userAddress,\n   to: contractAddress,\n   data: contract.methods.commissionTransfer(payeeAddress, \n         totalTransactionValue).encodeABI()\n}\nconst sentTx = await web3.eth.sendTransaction(tx)\n```\n\n```text\nfunction commissionTransfer(address recipient, uint256 amount) public virtual returns (bool) {\n    address sender = _msgSender();\n    uint256 senderBalance = balanceOf(sender);\n    require(senderBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n    uint256 payAmount = (amount / 1000) * (1000 - commission);\n    uint256 comAmount = amount - payAmount;\n    _transfer(sender, recipient, payAmount);\n    _transfer(sender, theHouse, comAmount);\n    return true;\n}\n```\n\n```text\ninterface IToken {\n    function commissionTransfer(address, address, uint256) external returns (bool);\n}\n\ncontract tokenCommission {\n    address tokenAddress=0xetc;\n\n    function transfer(address recipient, uint256 amount) public returns (bool) {\n        return IToken(tokenAddress).commissionTransfer(msg.sender, recipient, amount);\n    }\n\n    function decimals() public view virtual returns (uint8) {\n        return 18;\n    }\n}\n```\n\n========================================\n\nComments:\n- By way of a workaround I've put a brief explanation of what to expect and an ugly alert() showing the value before MetaMask pops up but, as a user, I think I would balk at not seeing the value in Metamask when I'm confirming. So I guess my users will too.\n- Thank you so much. That makes sense. I also need a standard, commissionless transfer function so can't replace it completely but hopefully adding a new takeCommission boolean argument to that won't prevent MetaMask from recognising it.\n- You could make it in a way that It only takes a fee if (for ex.) the sender or receiver are not excluded.\n- Adding a boolean argument didn't work since it seems that MetaMask only considers a transfer() to be a transfer if it has the normal recipient and amount arguments. Now I know how it's working, I'll have a think about how I can get it to run in two different ways.\n- I will have control over the amount in my dapp so perhaps take off a wei from the transaction value and apply commission if the amount ends in 99999.","metadata":{"transformedAt":"2026-08-18T18:33:36.142Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":124,"estimatedTokens":1571}}353{"id":"stack-61719400","source":"stackoverflow","questionId":61719400,"title":"How to get deeper in the JSON body of a chainlink req.add(\"path\") request? Add 2+ paths","tags":["blockchain","ethereum","solidity"],"text":"Title: How to get deeper in the JSON body of a chainlink req.add(\"path\") request? Add 2+ paths\nTags: blockchain, ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI can get the results of the `chainlink` path with `req.add(\"path\", \"chainlink\")` \n\nHowever, I want to return the price value, of `\"chainlink\", \"USD\"`. The output json has two paths, how do I reach the second path to get the price value? \n\n```\nfunction requestLINKPrice() \n public\n onlyOwner\n {\n Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);\n req.add(\"get\", \"https://api.coingecko.com/api/v3/simple/price?ids=chainlink&vs_currencies=usd\");\n req.add(\"path\", \"chainlinkUSD\");\n req.addInt(\"times\", 100);\n sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);\n }\n```\n\nHere is the JSON response of the API\n\n```\n{\n chainlink: {\n usd: 3.78\n }\n}\n```\n\n========================================\n\nCode:\n```text\nfunction requestLINKPrice() \n    public\n    onlyOwner\n  {\n    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);\n    req.add(\"get\", \"https://api.coingecko.com/api/v3/simple/price?ids=chainlink&vs_currencies=usd\");\n    req.add(\"path\", \"chainlinkUSD\");\n    req.addInt(\"times\", 100);\n    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);\n  }\n```\n\n```text\n{\n  chainlink: {\n    usd: 3.78\n  }\n}\n```\n\n```text\nchainlink\n```\n\n```text\nreq.add(\"path\", \"chainlink\")\n```\n\n```text\n\"chainlink\", \"USD\"\n```\n\n```text\nstring[] memory copyPath = new string[](2);\ncopyPath[0] = \"chainlink\";\ncopyPath[1] = \"USD\";\nreq.addStringArray(\"copyPath\", copyPath);\n```\n\n```text\nfunction requestLINKPrice() \n    public\n    onlyOwner\n  {\n    Chainlink.Request memory req = buildChainlinkRequest(JOB, address(this), this.fulfill.selector);\n    req.add(\"get\", \"https://api.coingecko.com/api/v3/simple/price?ids=chainlink&vs_currencies=usd\");\n    string[] memory copyPath = new string[](2);\n    copyPath[0] = \"chainlink\";\n    copyPath[1] = \"USD\";\n    req.addStringArray(\"copyPath\", copyPath);\n    req.addInt(\"times\", 100);\n    sendChainlinkRequestTo(ORACLE, req, ORACLE_PAYMENT);\n  }\n```\n\n```text\ncopyPath\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.142Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":94,"estimatedTokens":534}}354{"id":"stack-57770312","source":"stackoverflow","questionId":57770312,"title":"Require() function is not working properly in below code","tags":["solidity","smartcontracts"],"text":"Title: Require() function is not working properly in below code\nTags: solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nDeployed this contract on Remix IDE on InjectedWeb3 environment on Rinkeyby test network.\n\nI tried removing the error msg statement in require, then it is not throwing error but still not working properly i.e the function is getting executed irrespective of any require condition.\n\n```\npragma solidity >=0.4.22 address) owner;\n uint count;\n bool idExists;\n}\n mapping(uint => land) lands;\n function Register(uint id,uint area, string memory location, uint \n floorsAllowed) public\n {\n require(\n !lands[id].idExists,\n \"ID already exists\"\n );\n lands[id] = land(area, location, floorsAllowed,0,true);\n lands[id].owner[lands[id].count] = msg.sender;\n }\n function ViewLand(uint id) public view returns(address currentOwner, \n uint \n landArea, string memory landLocation, uint landFloors )\n {\n require(lands[id].idExists,\n \"Id doesn't exist.\");\n currentOwner = lands[id].owner[lands[id].count];\n landArea = lands[id].area;\n landLocation = lands[id].location;\n landFloors = lands[id].floorsAllowed;\n } \n}\n```\n\nerror: \n\n Failed to decode output: Error: overflow (operation=\"setValue\",\n fault=\"overflow\", details=\"Number can only safely store up to 53\n bits\", version=4.0.32)\n\n========================================\n\nCode:\n```text\npragma solidity >=0.4.22 <0.7.0;\ncontract RegisterLand{\n\nstruct land{\n     uint area;\n     string location;\n     uint floorsAllowed;\n     mapping(uint => address) owner;\n     uint count;\n     bool idExists;\n}\n mapping(uint => land) lands;\n function Register(uint id,uint area, string memory location, uint \n floorsAllowed) public\n {\n    require(\n            !lands[id].idExists,\n            \"ID already exists\"\n             );\n  lands[id] = land(area, location, floorsAllowed,0,true);\n  lands[id].owner[lands[id].count] = msg.sender;\n }\n function ViewLand(uint id) public view returns(address currentOwner, \n uint \n landArea, string memory landLocation, uint landFloors )\n {\n  require(lands[id].idExists,\n         \"Id doesn't exist.\");\n  currentOwner = lands[id].owner[lands[id].count];\n  landArea = lands[id].area;\n  landLocation = lands[id].location;\n  landFloors = lands[id].floorsAllowed;\n } \n}\n```\n\n```text\nViewLand\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- Thanks. Is there any alternative that I may use here?\n- Your dapp needs to work around this issue unfortunately.","metadata":{"transformedAt":"2026-08-18T18:33:36.142Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":98,"estimatedTokens":615}}355{"id":"stack-52375369","source":"stackoverflow","questionId":52375369,"title":"Transaction is never mined, using web3.py","tags":["django","solidity","web3py"],"text":"Title: Transaction is never mined, using web3.py\nTags: django, solidity, web3py\nSource: Stack Overflow\n\nQuestion:\nI'm developing a website using python 3.6, Django 2.1.1, Solidity and web3.py v4.\nI want to add the transaction to ropsten testnet but the transactions are never getting confirmed. Here is the code:\n\n```\namount_in_wei = w3.to_wei(questionEtherValue,'ether')\nnonce=w3.eth.getTransactionCount(w3.toChecksumAddress(questionairAddress))+1\n\ntxn_dict = {\n 'to': contractAddress,\n 'value': amount_in_wei,\n 'gas': 2000000,\n 'gasPrice': w3.toWei('70', 'gwei'),\n 'nonce': nonce,\n 'chainId': 3\n}\nsigned_txn = account.signTransaction(txn_dict)\ntxn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)\n\ntry:\n txn_receipt = w3.eth.waitForTransactionReceipt(txn_hash, timeout=300)\nexcept Exception:\n return {'status': 'failed', 'error': 'timeout'}\nelse:\n return {'status': 'success', 'receipt': txn_receipt}\n```\n\n========================================\n\nCode:\n```text\namount_in_wei = w3.to_wei(questionEtherValue,'ether')\nnonce=w3.eth.getTransactionCount(w3.toChecksumAddress(questionairAddress))+1\n\ntxn_dict = {\n     'to': contractAddress,\n     'value': amount_in_wei,\n     'gas': 2000000,\n     'gasPrice': w3.toWei('70', 'gwei'),\n     'nonce': nonce,\n     'chainId': 3\n}\nsigned_txn = account.signTransaction(txn_dict)\ntxn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction)\n\ntry:\n    txn_receipt = w3.eth.waitForTransactionReceipt(txn_hash, timeout=300)\nexcept Exception:\n    return {'status': 'failed', 'error': 'timeout'}\nelse:\n    return {'status': 'success', 'receipt': txn_receipt}\n```\n\n```text\n# original:\nnonce = w3.eth.getTransactionCount(w3.toChecksumAddress(questionairAddress)) + 1\n\n# should be:\nnonce = w3.eth.getTransactionCount(w3.toChecksumAddress(questionairAddress))\n```\n\n```text\nnonce\n```\n\n```text\nnonce\n```\n\n```text\nnonce\n```\n\n========================================\n\nComments:\n- 2M gas is a lot, about a quarter of a block currently. Do you actually need all that gas? If not, you might have more luck getting transactions included with a lower gas limit.\n- I reduced gas limit to 30K but tx_receipt is still None!\n- Is `questionairAddress == w3.eth.account.privateKeyToAccount(wallet_private_key).addre&zwnj;&#8203;ss`?\n- It is a 20 byte MetaMask wallet address\n- I suspect you are calculating the nonce with the wrong account\n- I removed +1 in nonce calculation, it works!\n- The last edit to the question made the code invalid. `account` is no longer set up for the line `account.signTransaction`. FWIW, the code leaves more open questions, like what is `questionairAddress` and how do we know that it's the same address as the account that's signing the transaction? I think the code is much clearer if you revert the full 3rd edit: stackoverflow.com/posts/52375369/revisions","metadata":{"transformedAt":"2026-08-18T18:33:36.142Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":87,"estimatedTokens":704}}356{"id":"stack-49209759","source":"stackoverflow","questionId":49209759,"title":"What is the difference between web3.js and web3-light.js?","tags":["ethereum","solidity","web3js"],"text":"Title: What is the difference between web3.js and web3-light.js?\nTags: ethereum, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\neveryone!\nWhat is the difference between web3.js and web3-light.js files from the web3.js library?\n\n========================================\n\nCode:\n```text\ngulp.task('light', ['clean'], function () {\n    return browserify(browserifyOptions)\n        .require('./' + src + '.js', {expose: 'web3'})\n        .ignore('bignumber.js')\n        .require('./lib/utils/browser-bn.js', {expose: 'bignumber.js'}) // fake bignumber.js\n        .add('./' + src + '.js')\n        .bundle()\n});\n```\n\n```text\nweb3.js\n```\n\n```text\nweb3-light.js\n```\n\n```text\nweb3.js\n```\n\n```text\nWeb3\n```\n\n```text\nlight\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.142Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":41,"estimatedTokens":180}}357{"id":"stack-49532454","source":"stackoverflow","questionId":49532454,"title":"How to generate sh3_keccak256 for integer values as generated by Solidity?","tags":["python-3.x","solidity","sha-3","remix"],"text":"Title: How to generate sh3_keccak256 for integer values as generated by Solidity?\nTags: python-3.x, solidity, sha-3, remix\nSource: Stack Overflow\n\nQuestion:\nI am trying to generate the same sha3.keccak_256 of integer values in Python that is generated by Solidity.\n\nHere is what Solidity does:\n\n```\npragma solidity ^0.4.18;\n\ncontract GenerateHash{\n function generateHashVal(int id, int date) pure public returns (bytes32){\n //Using values - (123,1522228250);\n return keccak256(id,date);\n }\n}\n```\n\nThe hash generated by this is 0xdf4ccab87521641ffc0a552aea55be3a0c583544dc761541784ec656668f4c5a\n\nIn Python3 though, I can't generate the same for integer values. If I type cast it to string then I am able to get some value but that does not match that of Solidity:\n\n```\n>>> s=sha3.keccak_256(repr(data).encode('utf-8')).hexdigest()\n>>> print(s)\n37aafdecdf8b7e9da212361dfbb20d96826ae5cc912ac972f315228c0cdc51c5\n>>> print(data)\n1231522228250\n```\n\nAny help is appreciated.\n\n========================================\n\nTop Answer:\n### Solution\n\nCheck out the `web3` python library, which has a number of helpful functions*. In this case, we can use `Web3.soliditySha3()`. You pass in the types and data, and it produces the hash for you, like so:\n\n```\nfrom web3 import Web3\n\nresult = Web3.soliditySha3(['uint256', 'uint256'], [123, 1522228250])\n\nassert result == \"0xdf4ccab87521641ffc0a552aea55be3a0c583544dc761541784ec656668f4c5a\"\n```\n\n### Web3 v4 Note\n\nv4 is coming out very soon. It has switched from hex strings to `bytes` in many places, including this function. So if you install with `pip install --pre web3` (and I recommend you do, until v4 goes stable), there is a slight modification to the above:\n\n```\nassert Web3.toHex(result) == \"0xdf4ccab87521641ffc0a552aea55be3a0c583544dc761541784ec656668f4c5a\"\n```\n\n### Other Resources\n\nThe Ethereum StackExchange is a very active site for Ethereum-specific questions. You may get faster responses, and find more already-asked questions. For example, a similar question was asked here: Python and Solidity keccak256 function gives different results.\n\n* Disclaimer: I am a contributor to the web3.py repo.\n\n========================================\n\nCode:\n```text\npragma solidity ^0.4.18;\n\ncontract GenerateHash{\n    function generateHashVal(int id, int date) pure public returns (bytes32){\n        //Using values - (123,1522228250);\n        return keccak256(id,date);\n    }\n}\n```\n\n```text\n>>> s=sha3.keccak_256(repr(data).encode('utf-8')).hexdigest()\n>>> print(s)\n37aafdecdf8b7e9da212361dfbb20d96826ae5cc912ac972f315228c0cdc51c5\n>>> print(data)\n1231522228250\n```\n\n```text\nsha3.keccak_256(binascii.unhexlify('{:064x}{:064x}'.format(123, 1522228250))).hexdigest()\n\n# output: 'df4ccab87521641ffc0a552aea55be3a0c583544dc761541784ec656668f4c5a'\n```\n\n```text\nbinascii.unhexlify\n```\n\n```text\nfrom web3 import Web3\n\nresult = Web3.soliditySha3(['uint256', 'uint256'], [123, 1522228250])\n\nassert result == \"0xdf4ccab87521641ffc0a552aea55be3a0c583544dc761541784ec656668f4c5a\"\n```\n\n```text\nassert Web3.toHex(result) == \"0xdf4ccab87521641ffc0a552aea55be3a0c583544dc761541784ec656668f4c5a\"\n```\n\n```text\nweb3\n```\n\n```text\nWeb3.soliditySha3()\n```\n\n```text\nbytes\n```\n\n```text\npip install --pre web3\n```\n\n========================================\n\nComments:\n- I am using web3.py only for my project, it just didn't click to check out its library for this task. Thanks for the info.","metadata":{"transformedAt":"2026-08-18T18:33:36.142Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":127,"estimatedTokens":851}}358{"id":"stack-56351190","source":"stackoverflow","questionId":56351190,"title":"Truffle Test - How To Show Errors Only","tags":["solidity","truffle"],"text":"Title: Truffle Test - How To Show Errors Only\nTags: solidity, truffle\nSource: Stack Overflow\n\nQuestion:\nHow does one suppress all compilation warnings (not errors) when running **truffle test**? Using the `--quiet` parameter does not seem to work.\n\n```\nTruffle v5.0.0 (core: 5.0.0)\nNode v10.15.3\n```\n\n========================================\n\nCode:\n```text\nTruffle v5.0.0 (core: 5.0.0)\nNode v10.15.3\n```\n\n```text\n--quiet\n```\n\n```text\n~/your_project_dir$ truffle test | grep 'Error'\n```\n\n========================================\n\nComments:\n- Do you need to see errors so that's why you want to suppress warnings?\n- It's less about seeing test errors and failures and more about seeing compilation and syntax errors that tend to get lost in the sea of warnings. These warnings result from 3rd party libraries that I don't want to touch.\n- See my answer @trajan . If you want to see compilation errors use `truffle compile | grep 'Error'` instead.","metadata":{"transformedAt":"2026-08-18T18:33:36.142Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":34,"estimatedTokens":236}}359{"id":"stack-49872713","source":"stackoverflow","questionId":49872713,"title":"Initialize a big fixed length array in Solidity","tags":["ethereum","solidity","smartcontracts"],"text":"Title: Initialize a big fixed length array in Solidity\nTags: ethereum, solidity, smartcontracts\nSource: Stack Overflow\n\nQuestion:\nI'm building a game on ethereum as my first project and I'm facing with the storage and gas limits. I would like to store a storage smart contract on the blockchain to be queried after the deployment. I really need to initialize a fixed length array with constant values I insert manually. My situation is the following:\n\n```\ncontract A {\n\n...some states variables/modifiers and events......\n\nuint[] public vector = new uint[](162);\n\nvector = [.......1, 2, 3,......];\n\nfunction A () {\n\n....some code....\n\nContractB contract = new ContractB(vector);\n\n}\n\n....functions....\n\n}\n```\n\nThis code doesn't deploy. Apparently I exceed gas limits on remix. I tried the following:\n\n- I split the vector in 10 different vectors and then pass just one of them to the constructor. With this the deploy works.\n\nI really need to have just one single vector because it represents the edges set of a graph where ContractB is the data structure to build a graph. Vectors elements are ordered like this:\n\n```\nvector = [edge1From, edge1To, edge2From, edge2To,.......]\n```\n\nand I got 81 edges (162 entries in the vector). \n\nI tought I can create a setData function that push the values in the vector one by one calling this function after the deployment but this is not my case because I need to have the vector filled before the call \n\n```\nContractB contract = new ContractB(vector);\n```\n\nNow I can see I have two doubts:\n\n1) Am I wrong trying to pass a vector as parameter in a function call inside the A constructor ?\n\n2) I can see that I can create a double mapping for the edges. Something like\n\n```\nmapping (bool => mapping(uint => uint))\n```\n\nbut then I will need multi-key valued mappings (more edges starting from the same point) and I will have the problem to initialize all the mappings at once like I do with the vector?\n\n========================================\n\nTop Answer:\nIf the range of values for you array are small enough, you can save on gas consumption by using a more appropriate size for your `uints`. Ethereum stores values into 32-bytes slots and you pay 20,000 gas for every slot used. If you are able to use a smaller sized `uint` (remember, `uint` is the same as `uint256`), you'll be able to save on gas usage.\n\nFor example, consider the following contract:\n\n```\npragma solidity ^0.4.19;\n\ncontract Test {\n uint256[100] big;\n uint128[100] small;\n\n function addBig(uint8 index, uint256 num) public {\n big[index] = num;\n }\n\n function addSmall(uint8 index, uint128 num1, uint128 num2) public {\n small[index] = num1;\n small[index + 1] = num2;\n }\n}\n```\n\nCalling `addBig()` each time with a previously unused index will have an execution cost of a little over 20,000 gas and results in one value being added to an array. Calling `addSmall()` each time will cost about 26,000, but you're adding 2 elements to the array. Both only use 1 slot of storage. You can get even better results if you can go smaller than `uint128`.\n\nAnother option (depending on if you need to manipulate the array data) is to store your `vector` off chain. You can use an oracle to retrieve data or store your data in IPFS.\n\nIf neither of those options work for your use case, then you'll have to change your data structure and/or use multiple transactions to initialize your array.\n\n========================================\n\nCode:\n```text\ncontract A {\n\n...some states variables/modifiers and events......\n\nuint[] public vector = new uint[](162);\n\nvector = [.......1, 2, 3,......];\n\nfunction A () {\n\n....some code....\n\nContractB contract = new ContractB(vector);\n\n}\n\n....functions....\n\n}\n```\n\n```text\nvector = [edge1From, edge1To, edge2From, edge2To,.......]\n```\n\n```text\nContractB contract = new ContractB(vector);\n```\n\n```text\nmapping (bool => mapping(uint => uint))\n```\n\n```text\npragma solidity ^0.4.2;\n\ncontract Graph {\n    address owner;\n\n    struct GraphEdge {\n        uint128 from;\n        uint128 to;\n    }\n\n    GraphEdge[] public graph;\n    bool public initialized = false;\n\n    constructor() public {\n        owner = msg.sender;\n    }\n\n    function addEdge(uint128 edgeFrom, uint128 edgeTo) public {\n        require(!initialized);\n        graph.push(GraphEdge({\n            from: edgeFrom,\n            to: edgeTo\n        }));\n    }\n\n    function finalize() public {\n        require(msg.sender == owner);\n        initialized = true;\n    }\n}\n\ncontract ContractB {\n    Graph graph;\n\n    constructor(address graphAddress) public {\n        Graph _graph = Graph(graphAddress);\n        require(_graph.initialized());\n        graph = _graph;\n    }\n}\n```\n\n```text\npragma solidity ^0.4.19;\n\ncontract Test {\n    uint256[100] big;\n    uint128[100] small;\n\n    function addBig(uint8 index, uint256 num) public {\n        big[index] = num;\n    }\n\n    function addSmall(uint8 index, uint128 num1, uint128 num2) public {\n        small[index] = num1;\n        small[index + 1] = num2;\n    }\n}\n```\n\n```text\nuints\n```\n\n```text\nuint\n```\n\n```text\nuint\n```\n\n```text\nuint256\n```\n\n```text\naddBig()\n```\n\n```text\naddSmall()\n```\n\n```text\nuint128\n```\n\n```text\nvector\n```\n\n========================================\n\nComments:\n- You might also be interested in ethereum.stackexchange.com/questions/23945/&hellip;\n- My idea was to create a contract GraphEditor where you push all the data and then pass the vector data to a function initializing a specific base model contract Graph with the informations about the order and the edges of the graph just in one call from GraphEditor. Then having the address of the deployed specific Graph than I can query it from other contracts. Starting from a GraphEditor will let every user create their own graph using the base contract Graph with the informations pushed in GraphEditor\n- I commented my post answering to why I need it to be initialized at construction time. Also I have a question. If you deploy a graph contract in the contractB constructor passing the specific address of the specific graph you created, this produce a local copy of that specific instance retrieving all the data ? or it's just pointing to that contract without the need of recreating a copy to interact with ?","metadata":{"transformedAt":"2026-08-18T18:33:36.142Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":226,"estimatedTokens":1554}}360{"id":"stack-51354762","source":"stackoverflow","questionId":51354762,"title":"Ethereum keeps showing token value as 0","tags":["ethereum","solidity"],"text":"Title: Ethereum keeps showing token value as 0\nTags: ethereum, solidity\nSource: Stack Overflow\n\nQuestion:\nI am in the initial phase of learning ethereum. I am testing smart contract using Ropsten Testnet. When I transfer my coin to some other it shows that token value is 0. Is there any way to set the token price?\n\nIt was showing like this \n\n```\nValue: 0 Ether ($0.00)\n```\n\nhttps://i.sstatic.net/Se6Tq.png\n\nAny help/suggestion would be appreciated.\n\n========================================\n\nCode:\n```text\nValue: 0 Ether ($0.00)\n```\n\n```text\nvalue\n```\n\n========================================\n\nComments:\n- Thank you very much @carver for such detailed explanation.\n- Do you have any idea how to control the price of our token? I mean how can I set the price of my token? through sdk or smart contract?","metadata":{"transformedAt":"2026-08-18T18:33:36.142Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":33,"estimatedTokens":201}}361{"id":"stack-56616396","source":"stackoverflow","questionId":56616396,"title":"Unit test error with mocha: Timeout of 20000ms exceeded","tags":["mocha.js","blockchain","ethereum","solidity","ganache"],"text":"Title: Unit test error with mocha: Timeout of 20000ms exceeded\nTags: mocha.js, blockchain, ethereum, solidity, ganache\nSource: Stack Overflow\n\nQuestion:\nI'm getting a timeout error when I try to send the contract to Ganache. My code is as follows,\n\n```\nconst assert = require('assert');\nconst ganache = require('ganache-cli');\nconst Web3 = require('web3');\nconst web3 = new Web3(ganache.provider());\nconst {interface,bytecode} = require('../compile');\n\nlet accounts;\nlet inbox;\n\nbeforeEach(async() => {\naccounts = await web3.eth.getAccounts();\ninbox = await new web3.eth.Contract(JSON.parse(interface))\n .deploy({data: bytecode,arguments:['Hi There !'] })\n .send({from: accounts[0], gas:'1000000'});\n});\n\ndescribe(\"inbox\", () => {\nit('deploys a contract', () => {\n console.log(inbox);\n })\n})\n```\n\nWhen I comment out the send method (provided below), the program runs without any issues. However, adding it back introduces the timeout error. No matter howmuch time I assign for mocha timeout, I still get the same error.\n\n .send({from: accounts[0], gas:'1000000'});\n\nThere are similar posts regarding timeout such as listed below,\nError: Timeout of 2000ms exceeded. For async tests and hooks. Unit test with mocha and chai\n\nUnit test error with mocha and chai Timeout of 2000ms exceeded. For async tests and hooks\n\nMocha testing with promises: Error: Timeout of 2000ms exceeded\n\nMocha exceeding 2000ms timeout when returning a promise\n\nNone of the above solutions worked for me (mostly talking about increasing the timeout). Additionally, I downgraded web3 library as proposed in a different forum. However, it didn't work either. \n\nYou can find the exact issue posted by someone else at a different forum. Apparently, that question has not received any potential answers as well.\n\n========================================\n\nCode:\n```text\nconst assert = require('assert');\nconst ganache = require('ganache-cli');\nconst Web3 = require('web3');\nconst web3 = new Web3(ganache.provider());\nconst {interface,bytecode} = require('../compile');\n\nlet accounts;\nlet inbox;\n\nbeforeEach(async() => {\naccounts = await web3.eth.getAccounts();\ninbox = await new web3.eth.Contract(JSON.parse(interface))\n  .deploy({data: bytecode,arguments:['Hi There !'] })\n  .send({from: accounts[0], gas:'1000000'});\n});\n\ndescribe(\"inbox\", () => {\nit('deploys a contract', () => {\n    console.log(inbox);\n })\n})\n```\n\n========================================\n\nComments:\n- try removing the gas property and check\n- @SanjaySB It returns an error when the gas limit is removed (the error: base fee exceeds gas limit).\n- what are the solc, web3 versions\n- @SanjaySB solc: 0.4.26 and web3: 1.0.0-beta.55. However, as mentioned in the post, I downgraded the versions and recompiled. None of them worked.\n- did you try the solc version 0.4.25?\n- @SanjaySB Yes. But, didn't work.","metadata":{"transformedAt":"2026-08-18T18:33:36.142Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":84,"estimatedTokens":710}}362{"id":"stack-68031529","source":"stackoverflow","questionId":68031529,"title":"How to call Solidity Function to return Ether from Smart Contract?","tags":["reactjs","solidity","web3js"],"text":"Title: How to call Solidity Function to return Ether from Smart Contract?\nTags: reactjs, solidity, web3js\nSource: Stack Overflow\n\nQuestion:\nI have deployed a smart contract on a local truffle project and I am trying to interact with it in a React project using web3. The following solidity function should send Ether what was previously deposited in the contract to a user address on a boolean condition:\n\n```\nfunction Payout() public{\n\n require( voteEndTime positiveVotes){\n require(!sender.option, \"Wrong Vote. Stake is distributed among winners\");\n payable(address(msg.sender)).transfer((stakes*sender.amount) / negativeStakes);\n }\n\n else if (positiveVotes > negativeVotes){\n require(sender.option, \"Wrong Vote. Stake is distributed among winners\");\n payable(address(msg.sender)).transfer((stakes*sender.amount) / positiveStakes);\n }\n\n else{\n payable(address(msg.sender)).transfer((stakes*sender.amount) / stakes);\n }\n }\n```\n\nThe contract is definitely able to read the user's address using `msg.sender` because it has worked in the other functions I have. Every other function in the contract is also working fine. I can interact with it and I am able to send Ether to it. The problem occurs when I am trying to return the Ether stored in the contract to an account. I am trying to call my `Payout()` function using the following web3 call in React on button click:\n\n```\nvar response = await BallotContract.methods.Payout().send({ from: account, gas: 310000 })\n```\n\nI have specified a higher gas limit, because the contract runs out of gas if I try to use the gas estimation seen below. The function this call is present in looks like this:\n\n```\nconst giveMeMoney = async (e) => {\n const web3 = await new Web3(window.ethereum);\n await window.ethereum.enable();\n \n var Accounts = await web3.eth.getAccounts() \n account = Accounts[0]\n console.log(account)\n \n const gas = await BallotContract.methods.Payout().estimateGas();\n console.log(gas)\n \n var response = await BallotContract.methods.Payout().send({ from: account, gas: 310000 })\n\n \n }\n```\n\nI am able to access the function from the frontend and it is returning the correct string if a \"require\" condition is not met. My problem is that the contract does not return any Ether if the conditions are met and this line:\n\n```\npayable(address(msg.sender)).transfer((stakes*sender.amount) / positiveStakes);\n```\n\n...is accessed. I am getting the following error:\n\n```\nUncaught (in promise) Error: Returned error: VM Exception while processing transaction: revert\n at Object.ErrorResponse (errors.js:30)\n at onJsonrpcResult (index.js:162)\n at XMLHttpRequest.request.onreadystatechange (index.js:123)\n ErrorResponse @ errors.js:30\n```\n\nNow I am unsure what could be the problem, because the contract is running perfectly fine if I test it in Remix. Does anybody see the problem or have a workaround for this kind of problem?\n\n========================================\n\nCode:\n```js\nfunction Payout() public{\n\n            require( voteEndTime< block.timestamp, \"Voting Time is not up. Please come back later\" );\n            Voter storage sender = voters[msg.sender];\n\n                if (negativeVotes > positiveVotes){\n                    require(!sender.option, \"Wrong Vote. Stake is distributed among winners\");\n                    payable(address(msg.sender)).transfer((stakes*sender.amount) / negativeStakes);\n                    }\n\n                else if (positiveVotes > negativeVotes){\n                    require(sender.option, \"Wrong Vote. Stake is distributed among winners\");\n                    payable(address(msg.sender)).transfer((stakes*sender.amount) / positiveStakes);\n                }\n\n                else{\n                    payable(address(msg.sender)).transfer((stakes*sender.amount) / stakes);\n                }\n            }\n```\n\n```js\nvar response = await BallotContract.methods.Payout().send({ from: account, gas: 310000 })\n```\n\n```js\nconst giveMeMoney = async (e) => {\n        const web3 = await new Web3(window.ethereum);\n        await window.ethereum.enable();\n        \n        var Accounts = await web3.eth.getAccounts() \n            account = Accounts[0]\n            console.log(account)\n    \n          const gas = await BallotContract.methods.Payout().estimateGas();\n          console.log(gas)\n          \n          var response = await BallotContract.methods.Payout().send({ from: account, gas: 310000 })\n\n    \n      }\n```\n\n```js\npayable(address(msg.sender)).transfer((stakes*sender.amount) / positiveStakes);\n```\n\n```text\nUncaught (in promise) Error: Returned error: VM Exception while processing transaction: revert\n        at Object.ErrorResponse (errors.js:30)\n        at onJsonrpcResult (index.js:162)\n        at XMLHttpRequest.request.onreadystatechange (index.js:123)\n    ErrorResponse   @   errors.js:30\n```\n\n```text\nmsg.sender\n```\n\n```text\nPayout()\n```\n\n```text\ntransfer\n```\n\n```text\ncall\n```\n\n```text\nVoter\n```\n\n```text\nfalse\n```","metadata":{"transformedAt":"2026-08-18T18:33:36.142Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":152,"estimatedTokens":1231}}363