import { type HexToBytesErrorType, hexToBytes } from '../encoding/toBytes.js' import { type BytesToHexErrorType, bytesToHex } from '../encoding/toHex.js' import type { ErrorType } from '../errors/utils.js' import type { Bytes, Hex } from '../types/data.js' import type { Kzg } from '../types/kzg.js' type To = 'hex' | 'bytes' export type BlobsToProofsParameters< blobs extends readonly Bytes[] | readonly Hex[], commitments extends readonly Bytes[] | readonly Hex[], to extends To = | (blobs extends readonly Hex[] ? 'hex' : never) | (blobs extends readonly Bytes[] ? 'bytes' : never), /// _blobsType = | (blobs extends readonly Hex[] ? readonly Hex[] : never) | (blobs extends readonly Bytes[] ? readonly Bytes[] : never), > = { /** Blobs to transform into proofs. */ blobs: blobs /** Commitments for the blobs. */ commitments: commitments & (commitments extends _blobsType ? {} : `commitments must be the same type as blobs`) /** KZG implementation. */ kzg: Pick /** Return type. */ to?: to | To | undefined } export type BlobsToProofsReturnType = | (to extends 'bytes' ? Bytes[] : never) | (to extends 'hex' ? Hex[] : never) export type BlobsToProofsErrorType = | BytesToHexErrorType | HexToBytesErrorType | ErrorType /** * Compute the proofs for a list of blobs and their commitments. * * @example * ```ts * import { Blobs } from 'viem' * import { kzg } from './kzg' * * const blobs = Blobs.from({ data: '0x1234' }) * const commitments = Blobs.toCommitments({ blobs, kzg }) * const proofs = Blobs.toProofs({ blobs, commitments, kzg }) * ``` */ export function blobsToProofs< const blobs extends readonly Bytes[] | readonly Hex[], const commitments extends readonly Bytes[] | readonly Hex[], to extends To = | (blobs extends readonly Hex[] ? 'hex' : never) | (blobs extends readonly Bytes[] ? 'bytes' : never), >( parameters: BlobsToProofsParameters, ): BlobsToProofsReturnType { const { kzg } = parameters const to = parameters.to ?? (typeof parameters.blobs[0] === 'string' ? 'hex' : 'bytes') const blobs = ( typeof parameters.blobs[0] === 'string' ? parameters.blobs.map((x) => hexToBytes(x as any)) : parameters.blobs ) as Bytes[] const commitments = ( typeof parameters.commitments[0] === 'string' ? parameters.commitments.map((x) => hexToBytes(x as any)) : parameters.commitments ) as Bytes[] const proofs: Bytes[] = [] for (let i = 0; i < blobs.length; i++) { const blob = blobs[i] const commitment = commitments[i] proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment))) } return (to === 'bytes' ? proofs : proofs.map((x) => bytesToHex(x))) as {} as BlobsToProofsReturnType }