Skip to content

Commit

Permalink
🎉Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
GitBolt committed Jan 7, 2022
0 parents commit 5c56d55
Show file tree
Hide file tree
Showing 15 changed files with 637 additions and 0 deletions.
9 changes: 9 additions & 0 deletions .deepsource.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
version = 1

[[analyzers]]
name = "python"
enabled = true

[analyzers.meta]
runtime_version = "3.x.x"
max_line_length = 79
20 changes: 20 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
.idea/
__pycache__/
__pypackages__/
mypy_cache/
dist/
.env
.venv
env/
venv/
env3/
.ipynb_checkpoints









19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2022 GitBolt

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<p align="center">
<a href="#">
<img
alt="Solathon logo"
src="https://media.discordapp.net/attachments/807140294764003350/929017682836193410/logo.png"
width="140"
/>
</a>
</p>


<p align="center">
<a href="https://pypi.org/project/solathon/" target="_blank"><img src="https://badge.fury.io/py/solathon.svg" alt="PyPI version"></a>
<a href="https://deepsource.io/gh/GitBolt/solathon/?ref=repository-badge}" target="_blank"><img src="https://deepsource.io/gh/GitBolt/solathon.svg/?label=active+issues&show_trend=true&token=O-2BAnF5y1x-YJyaIe-p4hsK" alt="DeepSource" /></a>
<a href="https://github.com/GitBolt/solathon/blob/master/LICENSE" target="_blank"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="MIT License"></a>
<br>
</p>

<h1 align="center">Solathon</h1>

Solathon is an high performance, easy to use and feature-rich Solana SDK for Python. Easy for beginners, powerful for real world applications.

|🧪| The project is in beta phase|
|---|-----------------------------|

# ✨ Getting started
## Installation
```
pip install solathon
```
## Client example
```python
from solathon import Client

client = Client("https://api.devnet.solana.com")
```
## Basic usage example
```python
# Basic example on generating a random public key and fetching it's balance
from solathon import Client, PublicKey

client = Client("https://api.devnet.solana.com")
public_key = PublicKey(1) # Creating a random public key

balance = client.get_balance(public_key)
print(balance)
```

# 🗃️ Contribution
Just drop a pull request lol
291 changes: 291 additions & 0 deletions poetry.lock

Large diffs are not rendered by default.

33 changes: 33 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
[tool.poetry]
name = "solathon"
version = "0.0.1"
description = "High performance, easy to use and feature-rich Solana SDK for Python."
license = "MIT"
authors = ["GitBolt"]
readme = "README.md"
repository = "https://github.com/GitBolt/solathon"
keywords = ["solana", "web3"]
classifiers = [
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"License :: OSI Approved :: MIT License",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
]


[tool.poetry.dependencies]
python = "^3.10"
httpx = "^0.21.2"
PyNaCl = "^1.4.0"
base58 = "^2.1.1"


[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
5 changes: 5 additions & 0 deletions solathon/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
__version__ = "0.1.0"

from .client import Client
from .publickey import PublicKey
from .keypair import Keypair
51 changes: 51 additions & 0 deletions solathon/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from typing import Union

from solathon.publickey import PublicKey
from .core.http import HTTPClient
from .core.types import RPCResponse

ENDPOINTS = (
"https://api.mainnet-beta.solana.com",
"https://api.devnet.solana.com",
"https://api.testnet.solana.com",
)


class Client:
def __init__(self, endpoint: str, local=False):
if not local and endpoint not in ENDPOINTS:
raise ValueError(
"Invalid cluster RPC endpoint provided"
" (Refer to https://docs.solana.com/cluster/rpc-endpoints)."
" Use the argument local to use a local development endpoint."
)
self.http = HTTPClient(endpoint)

def get_account_info(self, public_key: Union[PublicKey, str]
) -> RPCResponse:
data = self.http.build_data(
method="getAccountInfo", params=[public_key]
)
res = self.http.send(data)
return res

def get_balance(self, public_key: Union[PublicKey, str]) -> RPCResponse:
data = self.http.build_data(
method="getBalance", params=[public_key]
)
res = self.http.send(data)
return res

def get_block(self, slot: int) -> RPCResponse:
data = self.http.build_data(
method="getBlock", params=[slot]
)
res = self.http.send(data)
return res

def get_transaction(self, signature: str) -> RPCResponse:
data = self.http.build_data(
method="getTransaction", params=[signature]
)
res = self.http.send(data)
return res
1 change: 1 addition & 0 deletions solathon/core/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Solathon core"""
34 changes: 34 additions & 0 deletions solathon/core/http.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import sys
from typing import Tuple, Any, Dict
import httpx
from .. import __version__
from ..publickey import PublicKey


class HTTPClient:
"""HTTP Client to interact with Solana JSON RPC"""

def __init__(self, endpoint: str):
self.endpoint = endpoint
self.headers = {
"Content-Type": "application/json",
"User-Agent": (
"Solwarp (https://github.com/GitBolt/solwarp "
f"{__version__}) Python{sys.version_info[0]}"
),
}
self.request_id = 0

def send(self, data: str) -> Dict[str, Any]:
res = httpx.post(url=self.endpoint, headers=self.headers, json=data)
return res.json()

def build_data(self, method: str, params: Tuple[Any]) -> Dict[str, Any]:
self.request_id += 1
params = [str(i) if isinstance(i, PublicKey) else i for i in params]
return {
"jsonrpc": "2.0",
"id": self.request_id,
"method": method,
"params": params,
}
30 changes: 30 additions & 0 deletions solathon/core/instructions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from dataclasses import dataclass
from ..publickey import PublicKey

SYSTEM_ID: PublicKey = PublicKey("11111111111111111111111111111111")


@dataclass
class InstructionAccounts:
from_pubkey: PublicKey
to_pubkey: PublicKey
signer: PublicKey
lamports: int


@dataclass
class Instruction:
instruction_accounts: InstructionAccounts
program_id: PublicKey
data: bytes


def transfer(from_pubkey: str, to_pubkey: str, lamports: str) -> Instruction:
data = "placeholder"
return Instruction(
instruction_accounts=InstructionAccounts(
from_pubkey, to_pubkey, from_pubkey, lamports
),
program_id=SYSTEM_ID,
data=data
)
13 changes: 13 additions & 0 deletions solathon/core/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from typing import TypedDict, Literal, Any


class RPCError(TypedDict):
status_code: int
message: str


class RPCResponse(TypedDict):
jsonrpc: Literal["2.0"]
id: int
result: Any
error: RPCError
42 changes: 42 additions & 0 deletions solathon/keypair.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from typing import Optional, Union
from nacl.public import PrivateKey as NaclPrivateKey
from nacl.signing import SigningKey, SignedMessage, VerifyKey
from .publickey import PublicKey


class PrivateKey(PublicKey):
LENGTH = 64


class Keypair:
def __init__(self, value: Optional[NaclPrivateKey] = None):
if value is None:
self.key_pair = NaclPrivateKey.generate()
else:
self.key_pair = value
verify_key = VerifyKey(bytes(self.key_pair))
self._public_key = PublicKey(verify_key)
self._private_key = PrivateKey(
bytes(self.key_pair) + bytes(self._public_key)
)

def sign(self, message: Union[bytes, str]) -> SignedMessage:
if isinstance(message, str):
signing_key = SigningKey(bytes(self.key_pair))
return signing_key.sign(bytes(message, encoding="utf-8"))

if isinstance(message, bytes):
signing_key = SigningKey(bytes(self.key_pair))
return signing_key.sign(message)

raise ValueError(
"Message argument must be either string or bytes"
)

@property
def public_key(self) -> PublicKey:
return self._public_key

@property
def private_key(self) -> PrivateKey:
return self._private_key
37 changes: 37 additions & 0 deletions solathon/publickey.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from typing import List, Union
import base58


class PublicKey:
LENGTH = 32

def __init__(self, value: Union[bytearray, bytes, int, str, List[int]]):
if isinstance(value, str):
try:
self.public_key = base58.b58decode(value)
except ValueError:
raise ValueError("Invalid public key")
if len(self.public_key) != self.LENGTH:
raise ValueError("Invalid public key")
elif isinstance(value, int):
self.public_key = bytes([value])
else:
self.public_key = bytes(value)
if len(self.public_key) > self.LENGTH:
raise ValueError("Invalid public key")

def __bytes__(self) -> bytes:
return (
self.public_key
if len(self.public_key) == self.LENGTH
else self.public_key.rjust(self.LENGTH, b"\0")
)

def __repr__(self) -> str:
return str(self)

def __str__(self) -> str:
return self.to_base58().decode("utf-8")

def to_base58(self) -> bytes:
return base58.b58encode(bytes(self))
2 changes: 2 additions & 0 deletions solathon/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def lamport_to_sol(lamports: float) -> float:
return float(lamports / 1000000000)

0 comments on commit 5c56d55

Please sign in to comment.