Skip to content

Instantly share code, notes, and snippets.

@h4l
Created April 22, 2024 15:35
Show Gist options
  • Save h4l/d7189faf6f076b3a6b43a6251af3074a to your computer and use it in GitHub Desktop.
Save h4l/d7189faf6f076b3a6b43a6251af3074a to your computer and use it in GitHub Desktop.
Extract the NFT contract address and token ID from a Reddit avatar URL.
import base64
import re
def decode_avatar_url(avatar_url: str) -> tuple[str, int]:
"""Extract the NFT contract address and token ID from an avatar URL.
>>> avatar_url = 'https://i.redd.it/snoovatar/avatars/nftv2_bmZ0X2VpcDE1NToxMzdfOWQ4NTQyZWYxMjM3OTMzYmFkYmU4NjcyOTFmNmMwNDM0YjhkMzE1Y18xNTY_rare_9c019f39-3606-43fa-b14e-7dfb2dc3c12a.png'
>>> decode_avatar_url(avatar_url)
('0x9d8542ef1237933badbe867291f6c0434b8d315c', 156)
"""
if not (match := re.search(r"/nftv2_([^_]+)_", avatar_url)):
raise ValueError(f"Avatar URL is not an NFT avatar: {avatar_url!r}")
base64_nft_info = match.group(1)
# the base64 data is not padded, but python base64 lib needs padding with =
pad = len(base64_nft_info) % 4 * "="
nft_info = base64.b64decode(f"{base64_nft_info}{pad}").decode()
# nft_info looks like 'nft_eip155:{CHAIN_ID}_{CONTRACT_ID}_{TOKEN_ID}'
if not (match := re.match(r"nft_eip155:\d+_([a-fA-F0-9]{40})_(\d+)", nft_info)):
raise ValueError(
f"Avatar URL's NFT info data is not structured as expected: {nft_info!r}"
)
return f"0x{match.group(1)}", int(match.group(2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment