1

I know polkadot{.js} has an API to access contract storage here:

How do I get the code hash via the account?

2 Answers 2

1

You can write something similar:

import { ApiPromise, WsProvider } from '@polkadot/api';

export const fetchCodeHash = async () => {
    // Canvas
    const wsCanvasProvider = new WsProvider('wss://rococo-canvas-rpc.polkadot.io');
    const canvasApi = await ApiPromise.create({ provider: wsCanvasProvider });
    const account = "0x2ce787b4b143ff878457c7dc9dc44e34a22e3fa9db5a8fad07bfb384b99c614b";
    console.log((await canvasApi.query.contracts.codeStorage(account)).toHuman());
}

If the account has a contract, you will get similar output:

{
  instructionWeightsVersion: '2',
  initial: '2',
  maximum: '16',
  code: '0x0061736d0100000001771260037f7f7f017f60027f7f017f60037f7f7f0060027f7f0060047f7f7f7f0060017f0060057f7f7f7f7f0060037e7e7f0060000060047f7f7e7e0060017f017e60047f7f7f7f017f60067f7f7f7f7f7f0060057f7f7f7e7e006000017f60057f7f7f7e7e017f60017f017f60077f7f7f7f7f7f7f017f02fb010b057365616c30127365616c5f6465'... 61548 more characters
}
0

The above doesn't work with the contract address decoded to u8 Array and then converted to Hex. Instead you can pass directly AccountId as contract address with the code below, and it should give you the correct codeHash.

export const fetchCodeHash = async (contractAddress: string) => {
  const providerApi = await initializeProviderApi(); // provider API is the same as in the first answer, just abstracted away

  if (!providerApi) return;

  const { codeHash } = await (await providerApi.query.contracts.contractInfoOf(contractAddress)).toHuman() as { codeHash: string };

  console.log(codeHash);
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.