Skip to content

Commit

Permalink
checkpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
fmhall committed Jan 9, 2024
1 parent a124ba4 commit 1a6c5c1
Show file tree
Hide file tree
Showing 7 changed files with 66 additions and 41 deletions.
51 changes: 18 additions & 33 deletions farcaster/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import canonicaljson
import requests
from eth_account.account import Account
from eth_account.datastructures import SignedMessage
from eth_account.messages import encode_defunct
from eth_account.signers.local import LocalAccount
Expand All @@ -17,6 +16,7 @@
from farcaster.config import *
from farcaster.models import *
from farcaster.utils.stream_generator import stream_generator
from farcaster.utils.wallet import get_wallet


class Warpcast:
Expand All @@ -42,13 +42,14 @@ def __init__(
**data: Any,
):
self.config = ConfigurationParams(**data)
print(self.config)
self.wallet = get_wallet(mnemonic, private_key)
self.access_token = access_token
self.expires_at = expires_at
self.rotation_duration = rotation_duration
self.session = requests.Session()
self.session.mount(
self.config.base_path,
self.get_base_path(),
HTTPAdapter(
max_retries=Retry(
total=2, backoff_factor=1, status_forcelist=[520, 413, 429, 503]
Expand All @@ -61,7 +62,13 @@ def __init__(
)
if not self.expires_at:
self.expires_at = 33228645430000 # 3000-01-01

elif self.config.neynar_api_key:
self.session.headers.update(
{
"api_key": self.config.neynar_api_key,
"accept": "application/json",
}
)
elif not self.wallet:
raise Exception("No wallet or access token provided")
else:
Expand All @@ -85,7 +92,7 @@ def _get(
self._check_auth_header()
logging.debug(f"GET {path} {params} {json} {headers}")
response: Dict[Any, Any] = self.session.get(
self.config.base_path + path, params=params, json=json, headers=headers
self.get_base_path() + path, params=params, json=json, headers=headers
).json()
if "errors" in response:
raise Exception(response["errors"]) # pragma: no cover
Expand All @@ -101,7 +108,7 @@ def _post(
self._check_auth_header()
logging.debug(f"POST {path} {params} {json} {headers}")
response: Dict[Any, Any] = self.session.post(
self.config.base_path + path, params=params, json=json, headers=headers
self.get_base_path() + path, params=params, json=json, headers=headers
).json()
if "errors" in response:
raise Exception(response["errors"]) # pragma: no cover
Expand All @@ -117,7 +124,7 @@ def _put(
self._check_auth_header()
logging.debug(f"PUT {path} {params} {json} {headers}")
response: Dict[Any, Any] = self.session.put(
self.config.base_path + path, params=params, json=json, headers=headers
self.get_base_path() + path, params=params, json=json, headers=headers
).json()
if "errors" in response:
raise Exception(response["errors"]) # pragma: no cover
Expand All @@ -133,16 +140,17 @@ def _delete(
self._check_auth_header()
logging.debug(f"DELETE {path} {params} {json} {headers}")
response: Dict[Any, Any] = self.session.delete(
self.config.base_path + path, params=params, json=json, headers=headers
self.get_base_path() + path, params=params, json=json, headers=headers
).json()
if "errors" in response:
raise Exception(response["errors"]) # pragma: no cover
return response

def _check_auth_header(self):
assert self.expires_at
if self.expires_at < now_ms() + 1000:
self.create_new_auth_token(expires_in=self.rotation_duration)
if not self.config.neynar_api_key:
assert self.expires_at, "No access token"
if self.expires_at < now_ms() + 1000:
self.create_new_auth_token(expires_in=self.rotation_duration)

def get_healthcheck(self) -> bool:
"""Check if API is up and running
Expand Down Expand Up @@ -1090,29 +1098,6 @@ def generate_custody_auth_header(self, params: AuthParams) -> str:
return f"Bearer eip191:{encoded}"


def get_wallet(
mnemonic: Optional[str] = None, private_key: Optional[str] = None
) -> Optional[LocalAccount]:
"""Get a wallet from mnemonic or private key
Args:
mnemonic (Optional[str]): mnemonic
private_key (Optional[str]): private key
Returns:
Optional[LocalAccount]: wallet
"""
Account.enable_unaudited_hdwallet_features()

if mnemonic:
account: LocalAccount = Account.from_mnemonic(mnemonic)
return account # pragma: no cover
elif private_key:
account = Account.from_key(private_key)
return account # pragma: no cover
return None


def now_ms() -> int:
"""Get the current time in milliseconds
Expand Down
2 changes: 1 addition & 1 deletion farcaster/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from farcaster.models import *

FARCASTER_API_BASE_URL = "https://api.warpcast.com/v2/"
NEYNAR_API_BASE_URL = "https://api.neynar.io/v2/farcaster/"
NEYNAR_API_BASE_URL = "https://api.neynar.com/v1/farcaster/"


class ConfigurationParams(BaseModel):
Expand Down
4 changes: 2 additions & 2 deletions farcaster/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@ class ApiOpenSeaNft(BaseModel):

class ApiPfp(BaseModel):
url: str
verified: bool
verified: Optional[bool] = None


class Bio(BaseModel):
text: str
mentions: List[str]
mentions: Optional[List[str]] = None


class ApiProfile(BaseModel):
Expand Down
25 changes: 25 additions & 0 deletions farcaster/utils/wallet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from typing import Optional

from eth_account.account import Account
from eth_account.signers.local import LocalAccount


def get_wallet(
mnemonic: Optional[str] = None, private_key: Optional[str] = None
) -> Optional[LocalAccount]:
"""Get a wallet from mnemonic or private key
Args:
mnemonic (Optional[str]): mnemonic
private_key (Optional[str]): private key
Returns:
Optional[LocalAccount]: wallet
"""
Account.enable_unaudited_hdwallet_features()

if mnemonic:
account: LocalAccount = Account.from_mnemonic(mnemonic)
return account # pragma: no cover
elif private_key:
account = Account.from_key(private_key)
return account # pragma: no cover
return None
9 changes: 6 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@
@pytest.fixture(scope="session", autouse=True)
def client() -> Warpcast:
load_dotenv()
access_token = os.getenv("AUTH")
assert access_token, "AUTH env var not set"
return Warpcast(access_token=access_token)
# access_token = os.getenv("AUTH")
# assert access_token, "AUTH env var not set"
NEYNAR_API_KEY = os.getenv("NEYNAR_API_KEY")
assert NEYNAR_API_KEY, "PKEY env var not set"
return Warpcast(neynar_api_key=NEYNAR_API_KEY)
# return Warpcast(access_token=access_token)


@pytest.fixture(scope="module")
Expand Down
14 changes: 13 additions & 1 deletion tests/integration_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,18 @@ def client_from_neynar() -> None:
# print(client.expires_at)
# print(client.access_token)
# assert client.expires_at == expiry
# import requests

# url = "https://api.neynar.com/v1/farcaster/user-by-username?username=mason"

client_from_neynar()
# headers = {
# "accept": "application/json",
# "api_key": "898E34EC-7630-4DDF-813D-4E28074AA454"
# }

# response = requests.get(url, headers=headers)

# print(response.text)


# client_from_neynar()
2 changes: 1 addition & 1 deletion tests/test_config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pytest

from farcaster import Warpcast
from farcaster.client import get_wallet
from farcaster.utils.wallet import get_wallet


def test_get_base_path(client: Warpcast) -> None:
Expand Down

0 comments on commit 1a6c5c1

Please sign in to comment.