|
| 1 | +from magic_admin.resources.base import ResourceComponent |
| 2 | +from magic_admin.error import DIDTokenMalformed, DIDTokenExpired |
| 3 | +from magic_admin.error import ExpectedBearerStringError |
| 4 | +from web3 import Web3 |
| 5 | +import json |
| 6 | + |
| 7 | + |
| 8 | +class Utils(ResourceComponent): |
| 9 | + """ |
| 10 | + Utility methods for Magic Admin SDK. |
| 11 | + """ |
| 12 | + |
| 13 | + def parse_authorization_header(self, header: str) -> str: |
| 14 | + """ |
| 15 | + Parse a raw DID Token from the given Authorization header. |
| 16 | +
|
| 17 | + Args: |
| 18 | + header (str): The Authorization header string |
| 19 | +
|
| 20 | + Raises: |
| 21 | + ExpectedBearerStringError: If header is not in 'Bearer {token}' format |
| 22 | +
|
| 23 | + Returns: |
| 24 | + str: The DID token extracted from the header |
| 25 | + """ |
| 26 | + if not header.lower().startswith("bearer "): |
| 27 | + raise ExpectedBearerStringError( |
| 28 | + message="Expected argument to be a string in the `Bearer {token}` format." |
| 29 | + ) |
| 30 | + |
| 31 | + return header[7:] # Remove 'Bearer ' prefix |
| 32 | + |
| 33 | + def validate_token_ownership( |
| 34 | + self, |
| 35 | + did_token: str, |
| 36 | + contract_address: str, |
| 37 | + contract_type: str, |
| 38 | + rpc_url: str, |
| 39 | + token_id: str = None, |
| 40 | + ) -> dict: |
| 41 | + """ |
| 42 | + Token Gating function validates user ownership of wallet + NFT. |
| 43 | +
|
| 44 | + Args: |
| 45 | + did_token (str): The DID token to validate |
| 46 | + contract_address (str): The smart contract address |
| 47 | + contract_type (str): Either 'ERC721' or 'ERC1155' |
| 48 | + rpc_url (str): The RPC endpoint URL |
| 49 | + token_id (str, optional): Required for ERC1155 contracts |
| 50 | +
|
| 51 | + Raises: |
| 52 | + ValueError: If ERC1155 is specified without token_id |
| 53 | + Exception: If DID token validation fails |
| 54 | +
|
| 55 | + Returns: |
| 56 | + dict: Response with validation result |
| 57 | + { |
| 58 | + 'valid': bool, |
| 59 | + 'error_code': str, |
| 60 | + 'message': str |
| 61 | + } |
| 62 | + """ |
| 63 | + # Make sure if ERC1155 has a tokenId |
| 64 | + if contract_type == "ERC1155" and not token_id: |
| 65 | + raise ValueError("ERC1155 requires a tokenId") |
| 66 | + |
| 67 | + # Validate DID token |
| 68 | + try: |
| 69 | + self.Token.validate(did_token) |
| 70 | + wallet_address = self.Token.get_public_address(did_token) |
| 71 | + except DIDTokenMalformed: |
| 72 | + return { |
| 73 | + "valid": False, |
| 74 | + "error_code": "UNAUTHORIZED", |
| 75 | + "message": "Invalid DID token: ERROR_MALFORMED_TOKEN", |
| 76 | + } |
| 77 | + except DIDTokenExpired: |
| 78 | + return { |
| 79 | + "valid": False, |
| 80 | + "error_code": "UNAUTHORIZED", |
| 81 | + "message": "Invalid DID token: ERROR_DIDT_EXPIRED", |
| 82 | + } |
| 83 | + except Exception as e: |
| 84 | + raise Exception(str(e)) |
| 85 | + |
| 86 | + # Check on-chain if user owns NFT by calling contract with web3 |
| 87 | + w3 = Web3(Web3.HTTPProvider(rpc_url)) |
| 88 | + |
| 89 | + if contract_type == "ERC721": |
| 90 | + # ERC721 ABI for balanceOf function |
| 91 | + abi = json.loads( |
| 92 | + '[{"constant":true,"inputs":[{"name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"type":"function"}]' |
| 93 | + ) |
| 94 | + contract = w3.eth.contract(address=contract_address, abi=abi) |
| 95 | + balance = contract.functions.balanceOf(wallet_address).call() |
| 96 | + else: # ERC1155 |
| 97 | + # ERC1155 ABI for balanceOf function |
| 98 | + abi = json.loads( |
| 99 | + '[{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"id","type":"uint256"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"type":"function"}]' |
| 100 | + ) |
| 101 | + contract = w3.eth.contract(address=contract_address, abi=abi) |
| 102 | + balance = contract.functions.balanceOf(wallet_address, int(token_id)).call() |
| 103 | + |
| 104 | + if balance > 0: |
| 105 | + return {"valid": True, "error_code": "", "message": ""} |
| 106 | + |
| 107 | + return { |
| 108 | + "valid": False, |
| 109 | + "error_code": "NO_OWNERSHIP", |
| 110 | + "message": "User does not own this token.", |
| 111 | + } |
0 commit comments