Skip to content

Commit

Permalink
add app call note parser
Browse files Browse the repository at this point in the history
  • Loading branch information
gokselcoban committed Dec 29, 2022
1 parent 1f4e369 commit 745b4dc
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
22 changes: 22 additions & 0 deletions tests/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from base64 import b64encode
from unittest import TestCase

from tinyman.utils import generate_app_call_note, parse_app_call_note


class BaseTestCase(TestCase):
maxDiff = None

def test_app_call_note(self):
txn_note = generate_app_call_note(
version="v2", client_name="unit-test", extra_data={"extra": "some text"}
)

# The representation of indexer and node responses
raw_base64_note = b64encode(txn_note.encode()).decode()

result = parse_app_call_note(raw_base64_note)
self.assertDictEqual(
result,
{"version": "v2", "data": {"extra": "some text", "origin": "unit-test"}},
)
29 changes: 27 additions & 2 deletions tinyman/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import json
import re
import warnings
from base64 import b64decode, b64encode
from datetime import datetime
from json import JSONDecodeError
from typing import Optional

from algosdk.error import AlgodHTTPError
Expand Down Expand Up @@ -129,7 +131,7 @@ def get_version(tinyman_app_id: int) -> str:

def generate_app_call_note(
version: str, client_name: Optional[str] = None, extra_data: Optional[dict] = None
):
) -> str:
# https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0002.md
# <dapp-name>:<data-format><data>
note_template = "{dapp_name}/{dapp_version}:{data_format}{data}"
Expand All @@ -145,14 +147,37 @@ def generate_app_call_note(
)

# spaces are removed from separators, default is (', ', ': ')
serialized_data = json.dumps(data, separators=(",", ":"))
serialized_data = json.dumps(data, separators=(",", ":"), sort_keys=True)

note = note_template.format(
dapp_name="tinyman", dapp_version=version, data_format="j", data=serialized_data
)
return note


def parse_app_call_note(
base64_note: str, raise_exception: bool = False
) -> Optional[dict]:
note = b64decode(base64_note).decode()

pattern = r"tinyman/(?P<version>v[1-2]):j(?P<raw_data>.*)$"
match = re.match(pattern, note)

if not match:
return None

try:
data = json.loads(match.group("raw_data"))
except JSONDecodeError as e:
if raise_exception:
raise e
return None

# Result
result = {"version": match.group("version"), "data": data}
return result


class TransactionGroup:
def __init__(self, transactions):
# Clear previously assigned group ids
Expand Down

0 comments on commit 745b4dc

Please sign in to comment.