|
| 1 | +import { getAddress, keccak256, encodePacked } from "viem"; |
| 2 | +import { VmType } from "../utils"; |
| 3 | + |
| 4 | +export interface TokenIdComponents { |
| 5 | + family: VmType; |
| 6 | + chainId: bigint; |
| 7 | + address: string; |
| 8 | +} |
| 9 | + |
| 10 | +export interface VirtualAddressComponents { |
| 11 | + family: VmType; |
| 12 | + chainId: bigint; |
| 13 | + address: string; |
| 14 | +} |
| 15 | + |
| 16 | +export type TokenId = bigint; |
| 17 | +export type VirtualAddress = `0x${string}`; |
| 18 | + |
| 19 | +export const getCheckSummedAddress = (family: string, address: string) => { |
| 20 | + const checksummedAddress = |
| 21 | + family === "ethereum-vm" ? getAddress(address) : address; |
| 22 | + return checksummedAddress; |
| 23 | +}; |
| 24 | + |
| 25 | +/** |
| 26 | + * Generates a virtual Ethereum address from token components |
| 27 | + * @param components The token components (family, chainId, address) |
| 28 | + * @returns A checksummed Ethereum address derived from the token ID |
| 29 | + * @remarks This function first generates a token ID using the components, |
| 30 | + * then converts the last 20 bytes of the hash to an Ethereum address. |
| 31 | + * This is equivalent to the Solidity: address(uint160(uint256(addressHash))) |
| 32 | + */ |
| 33 | + |
| 34 | +export function generateAddress( |
| 35 | + components: VirtualAddressComponents |
| 36 | +): VirtualAddress { |
| 37 | + const { chainId, address, family } = components; |
| 38 | + const addressHash = keccak256( |
| 39 | + encodePacked( |
| 40 | + ["string", "uint256", family === "ethereum-vm" ? "address" : "string"], |
| 41 | + [family, chainId, getCheckSummedAddress(family, address)] |
| 42 | + ) |
| 43 | + ); |
| 44 | + const addressBytes = addressHash.slice(2).slice(-40); |
| 45 | + return getAddress("0x" + addressBytes) as `0x${string}`; |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Generates a token ID based on the chain type, chain ID, and address |
| 50 | + * @param components The token components (family, chainId, address) |
| 51 | + * @returns The keccak256 hash of the token components |
| 52 | + */ |
| 53 | +export function generateTokenId(components: TokenIdComponents): TokenId { |
| 54 | + const { family, chainId, address } = components; |
| 55 | + const packedData = encodePacked( |
| 56 | + ["string", "uint256", family === "ethereum-vm" ? "address" : "string"], |
| 57 | + [family, chainId, getCheckSummedAddress(family, address)] |
| 58 | + ); |
| 59 | + return BigInt(keccak256(packedData)); |
| 60 | +} |
0 commit comments