There's no such thing as "existence" in a Solidity mapping.

Every key maps to something. If no value has been set yet, then the value is 0.

For your use case, hashstructs[n].fhash > 0 is probably sufficient. If you want to be explicit, add a bool exists to your struct and set it to true when you add something. Then use hashstructs[n].exists to check for existence.

Answer from user94559 on Stack Overflow
Top answer
1 of 1
1

there are my lastest methods used to check if a contract has a function:

import _ from 'lodash';
import { Abi, Address, BaseError, ContractFunctionRevertedError, PublicClient } from 'viem';
import Web3 from 'web3';


/**
 * @description unable to penetrate proxy contracts
 * @param method The param need the format:```transferFrom(address,address,uint256)```
 */
export const isMethodExistA = async (web3: Web3, contractAddress: Address, method: string): Promise<boolean> => {
  try {
    const code = await web3.eth.getCode(contractAddress);
    const methodSignature = web3.eth.abi.encodeFunctionSignature(method);

    return code.indexOf(methodSignature.slice(2, methodSignature.length)) > 0;
  } catch (e: any) {
    return false;
  }
};


/**
 * @description unable to penetrate proxy contracts
 * @param method The param need the format:```{
    inputs: [],
    name: 'getOwners',
    outputs: [{ internalType: 'address[]', name: '', type: 'address[]' }],
    stateMutability: 'view',
    type: 'function'
  }```
 */
export const isMethodExistB = async (web3: Web3, contractAddress: Address, method: any): Promise<boolean> => {
  try {
    const code = await web3.eth.getCode(contractAddress);
    const methodSignature = web3.eth.abi.encodeFunctionSignature(method);

    return code.indexOf(methodSignature.slice(2, methodSignature.length)) > 0;
  } catch (e: any) {
    return false;
  }
};


/**
 * @description can penetrate proxy contracts
 * @param methodABI The param need the format:```[{
    inputs: [],
    name: 'getOwners',
    outputs: [{ internalType: 'address[]', name: '', type: 'address[]' }],
    stateMutability: 'view',
    type: 'function'
  }]```, and perform const assertion, that is ```const [] as const```
 */
export const isMethodExistC = async (
  publicClient: PublicClient,
  contractAddress: Address,
  methodABI: Abi,
  functionName: string,
  args?: any[]
) => {
  try {
    const ret = await publicClient.simulateContract({
      address: contractAddress,
      abi: methodABI,
      functionName: functionName,
      args: args,
    });
    return true;
  } catch (e: any) {
    if (e instanceof BaseError) {
      if (e.cause instanceof ContractFunctionRevertedError) {
        return true;
      }
    }
    return false;
  }
};

There are some examples using the above methods:

import { createPublicClient, http } from 'viem';
import { mainnet } from 'viem/chains';
import Web3 from 'web3';

const web3 = new Web3('https://eth-mainnet.g.alchemy.com/v2/...');
const publicClient = createPublicClient({
  chain: mainnet,
  transport: http('https://eth-mainnet.g.alchemy.com/v2/...'),
});

isMethodExistA(
  web3,
  '0x791250f047ae1de09f2a9ab98eec91caa9bf0a2d',
  'execTransaction(address,uint256,bytes,uint8,uint256,uint256,uint256,address,address,bytes)'
).then((ret) => console.log('ret:', ret));

isMethodExistB(web3, '0xd9db270c1b5e3bd161e8c8503c55ceabee709552', {
  inputs: [
    { internalType: 'address', name: 'to', type: 'address' },
    { internalType: 'uint256', name: 'value', type: 'uint256' },
    { internalType: 'bytes', name: 'data', type: 'bytes' },
    {
      internalType: 'enum Enum.Operation',
      name: 'operation',
      type: 'uint8',
    },
    { internalType: 'uint256', name: 'safeTxGas', type: 'uint256' },
    { internalType: 'uint256', name: 'baseGas', type: 'uint256' },
    { internalType: 'uint256', name: 'gasPrice', type: 'uint256' },
    { internalType: 'address', name: 'gasToken', type: 'address' },
    {
      internalType: 'address payable',
      name: 'refundReceiver',
      type: 'address',
    },
    { internalType: 'bytes', name: 'signatures', type: 'bytes' },
  ],
  name: 'execTransaction',
  outputs: [{ internalType: 'bool', name: 'success', type: 'bool' }],
  stateMutability: 'payable',
  type: 'function',
}).then((ret) => console.log('ret:', ret));

const execTransactionABI = [
  {
    inputs: [
      { internalType: 'address', name: 'to', type: 'address' },
      { internalType: 'uint256', name: 'value', type: 'uint256' },
      { internalType: 'bytes', name: 'data', type: 'bytes' },
      {
        internalType: 'enum Enum.Operation',
        name: 'operation',
        type: 'uint8',
      },
      { internalType: 'uint256', name: 'safeTxGas', type: 'uint256' },
      { internalType: 'uint256', name: 'baseGas', type: 'uint256' },
      { internalType: 'uint256', name: 'gasPrice', type: 'uint256' },
      { internalType: 'address', name: 'gasToken', type: 'address' },
      {
        internalType: 'address payable',
        name: 'refundReceiver',
        type: 'address',
      },
      { internalType: 'bytes', name: 'signatures', type: 'bytes' },
    ],
    name: 'execTransaction',
    outputs: [{ internalType: 'bool', name: 'success', type: 'bool' }],
    stateMutability: 'payable',
    type: 'function',
  },
] as const;

isMethodExistC(publicClient, '0x29469395eaf6f95920e59f858042f0e28d98a20b', execTransactionABI, 'execTransaction', [
  '0xfec7443780F800601118288dEd58D339Fd06dAC4',
  33,
  '0x4444',
  0,
  33,
  33,
  33,
  '0xfec7443780F800601118288dEd58D339Fd06dAC4',
  '0xfec7443780F800601118288dEd58D339Fd06dAC4',
  '0x233',
])
  .then((exist) => console.log('execTransaction exist:', exist))
  .catch((e) => console.log('execTransaction err:', e.message));
Discussions

How can you figure out if a certain key exists in a mapping (in Solidity)?

The entire storage space is virtually initialized to 0. There is no undefined. So you have to compare the value to the 0-value for your type. For example mapping[key] == address(0x0) or mapping[key] = bytes4(0x0).

More on reddit.com
🌐 r/ethereum
9
6
September 1, 2015
smartcontracts - Undeclared Identifier Error for _exists() Function in Solidity Contract Using OpenZeppelin - Stack Overflow
Question Body: I'm developing an ERC721 contract using OpenZeppelin libraries, and I'm encountering an error when calling _exists() in my Solidity contract. The error message is: DeclarationError: More on stackoverflow.com
🌐 stackoverflow.com
blockchain - solidity mapping check if element already exists - Stack Overflow
I am creating an Election website using blockChain. And I want a mapping of voters for all voters. All voter are updated when a new voter is added but currently the everytime a new voter is added i... More on stackoverflow.com
🌐 stackoverflow.com
remix - Check if user exists using mapping in solidity - Ethereum Stack Exchange
I use solidity to store users information so before that i want to check if the user id already exist or no, Can any one help me with this code ? i see some solution using array or require all More on ethereum.stackexchange.com
🌐 ethereum.stackexchange.com
May 14, 2020
🌐
O'Reilly
oreilly.com › library › view › mastering-blockchain-programming › 9781839218262 › 98ba6eb8-c80a-4d68-b4ed-d58d6a1dbeb9.xhtml
The _exists internal function - Mastering Blockchain Programming with Solidity [Book]
August 2, 2019 - Content preview from Mastering Blockchain Programming with Solidity · _exists() is an internal function that is used to check that the given tokenId exists in the contract.
Author   Jitendra Chittoda
Published   2019
Pages   486
🌐
Cloudhadoop
cloudhadoop.com › home
How to check value or object exists in Solidity mapping?
March 10, 2024 - To check if an object exists, use the expression mapping[key] == address(0x0000000000000000). Here is an example code to check if an object is null or not in Solidity
🌐
Solidity
docs.soliditylang.org › en › latest › contracts.html
Contracts — Solidity 0.8.36-develop documentation
Contracts in Solidity are similar to classes in object-oriented languages. They contain persistent data in state variables, and functions that can modify these variables. Calling a function on a different contract (instance) will perform an EVM function call and thus switch the context such that state variables in the calling contract are inaccessible.
🌐
Reddit
reddit.com › r/ethereum › how can you figure out if a certain key exists in a mapping (in solidity)?
r/ethereum on Reddit: How can you figure out if a certain key exists in a mapping (in Solidity)?
September 1, 2015 -

In Javascript, we might check for the existence of an object member like this:

if (object[key]) {
  // do something
} else {
  // do something else
}

I tried if(mapping[key]) { ... } in Solidity but that didn't work...

"Note that there is no type conversion from non-boolean to boolean types as there is in C and JavaScript, so if (1) { ... } is not valid Solidity." (https://github.com/ethereum/wiki/wiki/Solidity-Tutorial#control-structures).

mapping[key] == 0 is not a valid expression, so... how do we check for the existence of a key in a mapping?

🌐
Solidity
docs.soliditylang.org › en › latest › control-structures.html
Expressions and Control Structures — Solidity 0.8.36-develop documentation
Due to the fact that the EVM considers a call to a non-existing contract to always succeed, Solidity uses the extcodesize opcode to check that the contract that is about to be called actually exists (it contains code) and causes an exception if it does not.
🌐
Solidity
docs.soliditylang.org › en › v0.8.17 › types.html
Types — Solidity 0.8.17 documentation
August 29, 2023 - Solidity provides several elementary types which can be combined to form complex types. In addition, types can interact with each other in expressions containing operators. For a quick reference of the various operators, see Order of Precedence of Operators. The concept of “undefined” or “null” values does not exist in Solidity, but newly declared variables always have a default value dependent on its type.
Find elsewhere
🌐
Wikipedia
en.wikipedia.org › wiki › Solidity
Solidity - Wikipedia
1 week ago - Solidity is a programming language for implementing smart contracts on various blockchain platforms, most notably Ethereum. Solidity is licensed under GNU General Public License v3.0. Solidity was designed by Gavin Wood and developed by Christian ...
🌐
Solidity
docs.soliditylang.org › en › latest › units-and-global-variables.html
Units and Globally Available Variables — Solidity 0.8.36-develop documentation
This ensures that the contract that is about to be called either actually exists (it contains code) or an exception is raised. The low-level calls which operate on addresses rather than contract instances (i.e. .call(), .delegatecall(), .staticcall(), .send() and .transfer()) do not include this check, which makes them cheaper in terms of gas but also less safe. ... Prior to version 0.5.0, Solidity allowed address members to be accessed by a contract instance, for example this.balance.
🌐
Stack Overflow
stackoverflow.com › questions › 76482714 › solidity-mapping-check-if-element-already-exists
blockchain - solidity mapping check if element already exists - Stack Overflow
I want to check if the voter already exist or not if not then add the voter to the mapping else reply voter already exists. ... // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Election { uint public candidatesCount; uint public votersCount; struct Candidate { uint id; string name; string party; uint voteCount; } mapping(uint=> Candidate) public candidates; mapping(address => bool) public voted; function addCandidate(string memory _name, string memory _party) public{ candidatesCount++; candidates[candidatesCount] = Candidate(candidatesCount, _name, _party, 0); } function addVoter() public { voted[msg.sender] = false; } function vote(uint _candidateId) public { require(!voted[msg.sender], "You have already voted"); require(candidates[_candidateId].id != 0, "Candidate does not exist"); voted[msg.sender]= true; candidates[_candidateId].voteCount++; } }
🌐
Whole Blogs
wholeblogs.com › home › how to check if value exists in array using solidity
How to Check If Value Exists In Array Using Solidity - Whole Blogs
January 11, 2022 - This is called a one-dimensional array. ArraySize must always be an integer greater than zero, and the type can be any valid Solidity data type.
🌐
Gitbooks
ethereumbuilders.gitbooks.io › guide › content › en › solidity_tutorials.html
Solidity Tutorials | Ethereum Builder's Guide
Solidity is a high-level language whose syntax is similar to that of JavaScript and it is designed to compile to code for the Ethereum Virtual Machine. This tutorial provides a basic introduction to Solidity and assumes some knowledge of the Ethereum Virtual Machine and programming in general.
🌐
Educative
educative.io › answers › getting-keys-of-solidity-mapping
Getting keys of Solidity mapping
Solidity is an object-oriented language designed for the Ethereum blockchain to facilitate smart contract development.
🌐
GitHub
github.com › OpenZeppelin › openzeppelin-contracts › issues › 1192
clarify that exists() is an extension to ERC-721 · Issue #1192 · OpenZeppelin/openzeppelin-contracts
August 12, 2018 - https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC721/ERC721BasicToken.sol#L69 · Please add a note that the exists function is an extension and is not part of the standard.
Author   OpenZeppelin
🌐
Finst
finst.com › en › learn › articles › what-is-solidity
What is Solidity and how does it work? | Crypto Academy
October 23, 2025 - Solidity is the programming language used to build smart applications (smart contracts) on the Ethereum network.
🌐
Stack Overflow
stackoverflow.com › questions › tagged › Solidity
Newest 'Solidity' Questions - Stack Overflow
I’m building a simple Voting DApp using Solidity and Hardhat. The contract deploys successfully, and I can start and end voting without issues.