import { Binary } from 'polkadot-api';
import { mapObject } from 'polkadot-api/utils';
import { firstValueFrom } from 'rxjs';
import { getParams, respond, errorResponse } from './rpc_utils.js';

const dev_newBlock = async (con, req, { newBlock }) => {
  const { params } = getParams(req, ["params"]);
  try {
    const hash = await newBlock(
      params ? {
        ...params,
        storage: params.storage && mapObject(
          params.storage,
          (v) => v == null ? null : Binary.fromHex(v)
        ),
        transactions: params.transactions?.map(Binary.fromHex)
      } : {}
    );
    con.send(respond(req, hash));
  } catch (ex) {
    con.send(
      errorResponse(req, {
        code: -1,
        message: ex.message
      })
    );
  }
};
const dev_setStorage = async (con, req, { chain }) => {
  const { storageValues, blockHash } = getParams(req, [
    "storageValues",
    "blockHash"
  ]);
  try {
    const targetHash = blockHash ?? await firstValueFrom(chain.best$);
    chain.setStorage(
      targetHash,
      Object.fromEntries(
        storageValues.map(([key, value]) => [
          key,
          value ? Binary.fromHex(value) : null
        ])
      )
    );
    con.send(respond(req, targetHash));
  } catch (ex) {
    con.send(
      errorResponse(req, {
        code: -1,
        message: ex.message
      })
    );
  }
};

export { dev_newBlock, dev_setStorage };
//# sourceMappingURL=dev.js.map
