Skip to content

Utils

solana.utils special

Utility functions for solanaweb3.

cluster

Tools for getting RPC cluster information.

ClusterUrls

A collection of urls for each cluster.

Source code in solana/utils/cluster.py
class ClusterUrls(NamedTuple):
    """A collection of urls for each cluster."""

    devnet: str
    testnet: str
    mainnet_beta: str

Endpoint

Container for http and https cluster urls.

Source code in solana/utils/cluster.py
class Endpoint(NamedTuple):
    """Container for http and https cluster urls."""

    http: ClusterUrls
    https: ClusterUrls

cluster_api_url(cluster=None, tls=True)

Retrieve the RPC API URL for the specified cluster.

:param cluster: The name of the cluster to use. :param tls: If True, use https. Defaults to True.

Source code in solana/utils/cluster.py
def cluster_api_url(cluster: Optional[Cluster] = None, tls: bool = True) -> str:
    """Retrieve the RPC API URL for the specified cluster.

    :param cluster: The name of the cluster to use.
    :param tls: If True, use https. Defaults to True.
    """
    urls = ENDPOINT.https if tls else ENDPOINT.http
    if cluster is None:
        return urls.devnet
    return getattr(urls, cluster)

security_txt

Utils for security.txt.

FOOTER

Footer of the security.txt.

HEADER

Header of the security.txt.

NoSecurityTxtFoundError

Raise when security text is not found.

Source code in solana/utils/security_txt.py
class NoSecurityTxtFoundError(Exception):
    """Raise when security text is not found."""

SecurityTxt dataclass

Security txt data.

Source code in solana/utils/security_txt.py
@dataclass
class SecurityTxt:
    """Security txt data."""

    # pylint: disable=too-many-instance-attributes
    name: str
    project_url: str
    contacts: str
    policy: str
    preferred_languages: Optional[str] = None
    source_code: Optional[str] = None
    encryption: Optional[str] = None
    auditors: Optional[str] = None
    acknowledgements: Optional[str] = None
    expiry: Optional[str] = None

parse_security_txt(data)

Parse and extract security.txt section from the data section of the compiled program.

Parameters:

Name Type Description Default
data bytes

Program data in bytes from the ProgramAccount.

required

Returns:

Type Description
SecurityTxt

The Security Txt.

Source code in solana/utils/security_txt.py
def parse_security_txt(data: bytes) -> SecurityTxt:
    """Parse and extract security.txt section from the data section of the compiled program.

    Args:
        data: Program data in bytes from the ProgramAccount.

    Returns:
        The Security Txt.
    """
    if not isinstance(data, bytes):
        raise TypeError(f"data provided in parse(data) must be bytes, found: {type(data)}")

    s_idx = data.find(bytes(HEADER, "utf-8"))
    e_idx = data.find(bytes(FOOTER, "utf-8"))

    if s_idx == -1:
        raise NoSecurityTxtFoundError("Program doesn't have security.txt section")

    content_arr = data[s_idx + len(HEADER) : e_idx]
    content_da: List[Any] = [[]]

    for char in content_arr:
        if char == 0:
            content_da.append([])
        else:
            content_da[len(content_da) - 1].append(chr(char))

    content_da.pop()

    content_dict = {}

    for idx, content in enumerate(content_da):
        content_da[idx] = "".join(content)

    for iidx, idata in enumerate(content_da):
        if any(idata == x.name for x in fields(SecurityTxt)):
            next_key = iidx + 1
            content_dict.update({str(idata): content_da[next_key]})

    try:
        security_txt = SecurityTxt(**content_dict)
    except TypeError as err:
        raise err
    return security_txt

validate

Validation utilities.

validate_instruction_keys(instruction, expected)

Verify length of AccountMeta list of a transaction instruction is at least the expected length.

Parameters:

Name Type Description Default
instruction Instruction

A Instruction object.

required
expected int

The expected length.

required
Source code in solana/utils/validate.py
def validate_instruction_keys(instruction: Instruction, expected: int) -> None:
    """Verify length of AccountMeta list of a transaction instruction is at least the expected length.

    Args:
        instruction: A Instruction object.
        expected: The expected length.
    """
    if len(instruction.accounts) < expected:
        raise ValueError(f"invalid instruction: found {len(instruction.accounts)} keys, expected at least {expected}")

validate_instruction_type(parsed_data, expected_type)

Check that the instruction type of the parsed data matches the expected instruction type.

Parameters:

Name Type Description Default
parsed_data Any

Parsed instruction data object with instruction_type field.

required
expected_type IntEnum

The expected instruction type.

required
Source code in solana/utils/validate.py
def validate_instruction_type(parsed_data: Any, expected_type: IntEnum) -> None:
    """Check that the instruction type of the parsed data matches the expected instruction type.

    Args:
        parsed_data: Parsed instruction data object with `instruction_type` field.
        expected_type: The expected instruction type.
    """
    if parsed_data.instruction_type != expected_type:
        raise ValueError(
            f"invalid instruction; instruction index mismatch {parsed_data.instruction_type} != {expected_type}"
        )