Utility functions

A Collection of useful functions

.lamport_to_sol

Converts lamports into SOL. JSON RPC accepts and returns amounts in lamports so this can come in handy to convert RPC response lamports into SOL amounts.

def lamport_to_sol(lamports: int)
copy

.sol_to_lamport

Opposite of the previous function. This converts SOL amounts into lamports, useful when sending amounts to JSON RPC (send_transaction for example).

def sol_to_lamport(sols: float | int)
copy

.verify_signature

Verifies that the signature is signed by the public key, useful when implementing Web3 authorization and checking the signed message from browser wallets using the signature array. The message argument is optional, when not provided the public key itself is used as the message to verify the signature.

def verify_signature(
public_key: PublicKey | str,
signature: List[int],
message: str | bytes | None = None
)
copy

Basic authentication example:

from typing import Any
from solathon.utils import verify_signature
from nacl.exceptions import BadSignatureError
# Getting the public key and the signature array
public_key: str = request.headers.get("public_key")
signature_array: List[int] = request.headers.get("signature")
try:
verify_signature(public_key, signature_array)
except BadSignatureError:
return JSONResponse(content={"error": "Unauthorized", "status_code": 401})
copy

.clean_response

Cleans JSON RPC response and returns the actual main data

def clean_response(response: RPCResponse)
copy

Example:

from solathon import Client, PublicKey
from solathon.utils import clean_response
client = Client("https://api.devnet.solana.com")
public_key = PublicKey("B3BhJ1nvPvEhx3hq3nfK8hx4WYcKZdbhavSobZEA44ai")
balance = client.get_balance(public_key)
print(clean_response(balance))
copy

Instead of:

{
'jsonrpc': '2.0',
'result': {
'context': {
'slot': 114409418
},
'value': 46464827004
},
'id': 1
}

This would just return the value, which is:

46464827004

in this case, this is amount in lamports which can be later converted into sol using lamport_to_sol function