UNPKG

ethstorage-sdk

Version:
83 lines (70 loc) 2.89 kB
import { ethers } from "ethers"; import { ContentLike, BufferLike, FileLike, TxCost } from "../param"; export const stringToHex = (s: string): string => ethers.hexlify(ethers.toUtf8Bytes(s)); export async function getChainId(rpc: string): Promise<number> { const provider = new ethers.JsonRpcProvider(rpc); const network = await provider.getNetwork(); return Number(network.chainId); } export async function getContentChunk(content: ContentLike, start: number, end: number) { if (isBuffer(content)) { return content.slice(start, Math.min(end, content.length)); } else { const slice = content.slice(start, Math.min(end, content.size)); const data = await slice.arrayBuffer(); return new Uint8Array(data); } } export function isBuffer(content: ContentLike): content is BufferLike { return content instanceof Uint8Array; } export function isFile(content: ContentLike): content is FileLike { if (isNodejs()) { return content && typeof content === 'object' && typeof (content as any).isNodeJs === 'boolean' && (content as any).isNodeJs; } else { return content instanceof File; } } export function isNodejs(): boolean { return typeof process !== 'undefined' && !!process.versions && !!process.versions.node; } export function computeVersionedCommitmentHash(commitment: Uint8Array): Uint8Array { const computedVersionedHash = new Uint8Array(32); computedVersionedHash.set([0x01], 0); const hash = ethers.getBytes(ethers.sha256(commitment)); computedVersionedHash.set(hash.subarray(1), 1); return computedVersionedHash; } export function convertToEthStorageHash(commitment: Uint8Array): string { const localHash = computeVersionedCommitmentHash(commitment); const hash = new Uint8Array(32); hash.set(localHash.subarray(0, 32 - 8)); return ethers.hexlify(hash); } export function convertToEthStorageHashes(commitments: Uint8Array[]): string[] { return commitments.map(commitment => convertToEthStorageHash(commitment)); } export function copy(des: Uint8Array, desOff: number, src: Uint8Array, srcOff: number): number { const srcLength = src.length - srcOff; const desLength = des.length - desOff; const length = Math.min(srcLength, desLength); des.set(src.subarray(srcOff, srcOff + length), desOff); return length; } export function calcTxCost(receipt: ethers.TransactionReceipt | null): TxCost { if (!receipt) { return { normalGasCost: 0n, blobGasCost: 0n }; } // gas cost const normalGasCost: bigint = receipt.gasUsed * receipt.gasPrice; // blob gas cost const blobGasCost: bigint = receipt.blobGasUsed && receipt.blobGasPrice ? BigInt(receipt.blobGasUsed) * BigInt(receipt.blobGasPrice) : 0n; return { normalGasCost, blobGasCost, }; }