@polkadot/types/types#AnyJson TypeScript Examples

The following examples show how to use @polkadot/types/types#AnyJson. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: getContractAbi.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export default function getContractAbi (address: string | null): Abi | null {
  if (!address) {
    return null;
  }

  let abi: Abi | undefined;
  const meta = getAddressMeta(address, 'contract');

  try {
    const data = meta.contract && JSON.parse(meta.contract.abi) as AnyJson;

    abi = new Abi(data, api.registry.getChainProperties());
  } catch (error) {
    console.error(error);
  }

  return abi || null;
}
Example #2
Source File: useReadState.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
// TODO: are payload and state AnyJson? to disable useEffect deps or to memoize payload? should we handle loading on useMetadata?
function useReadState(programId: ProgramId, metaBuffer: Buffer | undefined, payload?: AnyJson) {
  const [state, setState] = useState<AnyJson>();
  const { api } = useApi();
  const { enableLoading, disableLoading, refresh } = useLoading();

  useEffect(() => {
    if (metaBuffer && payload) {
      enableLoading();

      api.programState
        .read(programId, metaBuffer, payload)
        .then((codecState) => codecState.toHuman())
        .then(setState)
        .finally(() => disableLoading());
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [metaBuffer, payload, refresh]);

  return state;
}
Example #3
Source File: useReadState.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
function useReadState(programId: ProgramId, metaSourceOrBuffer: string | Buffer | undefined, payload?: AnyJson) {
  const [state, setState] = useState<AnyJson>();
  const { api } = useContext(ApiContext); // сircular dependency fix
  const metaBuffer = useConditionalMetaBuffer(metaSourceOrBuffer);

  useEffect(() => {
    if (metaBuffer && payload) {
      api.programState
        .read(programId, metaBuffer, payload)
        .then((codecState) => codecState.toHuman())
        .then(setState);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [metaBuffer, payload]);

  return state;
}
Example #4
Source File: Extrinsic.tsx    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
Extrinsic = ({ extrinsic, className }: Props) => {
  const { method, section, meta, args } = extrinsic.method;
  const { docs, args: metaArgs } = meta;

  const caption = `${section}.${method}`;
  const description = docs[0].toHuman();

  const data = metaArgs.reduce((dataObject: { [name: string]: AnyJson }, metaArg, index) => {
    const { name } = metaArg;
    const formattedName = name.toHuman();
    const formattedValue = args[index].toHuman();

    dataObject[formattedName] = formattedValue;

    return dataObject;
  }, {});

  return (
    <ExpansionPanel caption={caption} description={String(description)} className={className}>
      <Pre text={data} />
    </ExpansionPanel>
  );
}
Example #5
Source File: getContractAbi.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export default function getContractAbi(address: string | null): Abi | null {
  if (!address) {
    return null;
  }

  let abi: Abi | undefined;
  const meta = getAddressMeta(address, 'contract');

  try {
    const data = meta.contract && (JSON.parse(meta.contract.abi) as AnyJson);

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    abi = new Abi(data, api.registry.getChainProperties());
  } catch (error) {
    console.error(error);
  }

  return abi || null;
}
Example #6
Source File: useMessage.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
function useMessage(destination: Hex, metadata: Metadata | undefined) {
  const alert = useAlert();
  const { api } = useApi();
  const { account } = useAccount();
  const { enableLoading, disableLoading } = useLoading();

  const handleEventsStatus = (events: EventRecord[]) => {
    events.forEach(({ event: { method } }) => {
      if (method === 'DispatchMessageEnqueued') {
        alert.success('Send message: Finalized');
        // onSucessCallback();
      } else if (method === 'ExtrinsicFailed') {
        alert.error('Extrinsic failed');
      }
    });
  };

  const handleStatus = (result: ISubmittableResult) => {
    const { status, events } = result;
    const { isInBlock, isInvalid, isFinalized } = status;

    if (isInvalid) {
      alert.error('Transaction error. Status: isInvalid');
      disableLoading();
    } else if (isInBlock) {
      alert.success('Send message: In block');
    } else if (isFinalized) {
      handleEventsStatus(events);
      disableLoading();
    }
  };

  // TODO: eslint
  // eslint-disable-next-line consistent-return
  const sendMessage = async (payload: AnyJson, value: string | number = 0) => {
    if (account && metadata) {
      enableLoading();

      const { address, decodedAddress, meta } = account;
      const gasLimit = await api.program.gasSpent.handle(decodedAddress, destination, payload, value, metadata);

      const message = { destination, payload, gasLimit, value };
      api.message.submit(message, metadata);

      const { source } = meta;
      const { signer } = await web3FromSource(source);
      return api.message.signAndSend(address, { signer }, handleStatus);
    }
  };

  return sendMessage;
}
Example #7
Source File: marketplace.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
function useMarketplaceState(payload: AnyJson) {
  const { marketplaceMetaBuffer } = useMarketplaceMeta();
  const marketplaceState = useReadState(MARKETPLACE_CONTRACT_ADDRESS, marketplaceMetaBuffer, payload);

  return marketplaceState;
}
Example #8
Source File: useSendMessage.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
function useSendMessage(destination: Hex, metaSourceOrData: string | Metadata | undefined) {
  const { api } = useContext(ApiContext); // сircular dependency fix
  const { account } = useContext(AccountContext);
  const alert = useContext(AlertContext);

  const metadata = useConditionalMeta(metaSourceOrData);

  const title = 'gear.sendMessage';
  const loadingAlertId = useRef('');

  const handleEventsStatus = (events: EventRecord[]) => {
    events.forEach(({ event: { method, section } }) => {
      if (method === 'DispatchMessageEnqueued') {
        alert.success(`${section}.DispatchMessageEnqueued`);
        // onSucessCallback();
      } else if (method === 'ExtrinsicFailed') {
        alert.error('Extrinsic Failed', { title });
      }
    });
  };

  const handleStatus = (result: ISubmittableResult) => {
    const { status, events } = result;
    const { isReady, isInBlock, isInvalid, isFinalized } = status;

    if (isInvalid) {
      alert.update(loadingAlertId.current, 'Transaction error. Status: isInvalid', DEFAULT_ERROR_OPTIONS);
    } else if (isReady) {
      alert.update(loadingAlertId.current, 'Ready');
    } else if (isInBlock) {
      alert.update(loadingAlertId.current, 'In Block');
    } else if (isFinalized) {
      alert.update(loadingAlertId.current, 'Finalized', DEFAULT_SUCCESS_OPTIONS);
      handleEventsStatus(events);
    }
  };

  const sendMessage = async (payload: AnyJson, value: string | number = 0) => {
    if (account && metadata) {
      loadingAlertId.current = alert.loading('Sign In', { title });

      const { address, decodedAddress, meta } = account;
      const gasLimit = await api.program.gasSpent.handle(decodedAddress, destination, payload, value, metadata);

      const message = { destination, payload, gasLimit, value };
      api.message.submit(message, metadata);

      const { source } = meta;
      const { signer } = await web3FromSource(source);

      return api.message
        .signAndSend(address, { signer }, handleStatus)
        .catch(({ message }: Error) => alert.update(loadingAlertId.current, message, DEFAULT_ERROR_OPTIONS));
    }
  };

  return sendMessage;
}
Example #9
Source File: multisig.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
export function useMultisig(acc?: string) {
  const [multisigAccount, setMultisigAccount] = useState<KeyringAddress | null>(null);
  const { api, networkStatus, chain } = useApi();
  const { account } = useParams<{ account: string }>();
  const ss58Account = encodeAddress(account, Number(chain.ss58Format));

  const [inProgress, setInProgress] = useState<Entry[]>([]);
  const [loadingInProgress, setLoadingInProgress] = useState(false);
  const queryInProgress = useCallback(async () => {
    if (!api) {
      return;
    }

    setLoadingInProgress(true);

    const multisig = keyring.getAccount(acc ?? ss58Account);
    // Use different ss58 addresses
    (multisig?.meta.addressPair as KeyringJson[])?.forEach((key) => {
      key.address = convertToSS58(key.address, Number(chain.ss58Format));
    });

    const data = await api.query.multisig.multisigs.entries(multisig?.address);
    const result: Pick<Entry, 'when' | 'depositor' | 'approvals' | 'address' | 'callHash'>[] = data?.map((entry) => {
      const [address, callHash] = entry[0].toHuman() as string[];

      return {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        ...(entry[1] as unknown as any).toJSON(),
        address,
        callHash,
      };
    });

    const callInfos = await api?.query.multisig.calls.multi(result.map((item) => item.callHash || ''));
    // eslint-disable-next-line complexity
    const calls: Entry[] = callInfos?.map((callInfo, index) => {
      const call = callInfo.toJSON() as AnyJson[];

      if (!call) {
        return { ...result[index], callDataJson: {}, meta: {}, hash: result[index].callHash };
      }

      try {
        const callData = api.registry.createType('Call', call[0]);
        const { section, method } = api.registry.findMetaCall(callData.callIndex);
        const callDataJson = { ...callData.toJSON(), section, method };
        const hexCallData = call[0];
        const meta = api?.tx[callDataJson?.section][callDataJson.method].meta.toJSON();

        return { ...result[index], callDataJson, callData, meta, hash: result[index].callHash, hexCallData };
      } catch {
        return { ...result[index], callDataJson: {}, meta: {}, hash: result[index].callHash };
      }
    });

    setMultisigAccount(multisig || null);
    setInProgress(calls || []);
    setLoadingInProgress(false);
  }, [api, acc, ss58Account, chain]);

  useEffect(() => {
    if (networkStatus !== 'success') {
      return;
    }

    queryInProgress();
  }, [networkStatus, queryInProgress]);

  return {
    inProgress,
    multisigAccount,
    setMultisigAccount,
    queryInProgress,
    loadingInProgress,
  };
}