Skip to content

Commit

Permalink
Merge pull request #324 from planetarium/feature/manual-actions
Browse files Browse the repository at this point in the history
Add manual actions
  • Loading branch information
U-lis authored Oct 25, 2024
2 parents 9878654 + 21fbf3b commit 5659517
Show file tree
Hide file tree
Showing 6 changed files with 219 additions and 3 deletions.
25 changes: 25 additions & 0 deletions common/lib9c/actions/burn_asset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from typing import Optional

from lib9c.actions import ActionBase
from lib9c.models.address import Address
from lib9c.models.fungible_asset_value import FungibleAssetValue


class BurnAsset(ActionBase):
TYPE_ID: str = "burn_asset"

def __init__(self, *, owner: Address, amount: FungibleAssetValue, memo: str,
_id: Optional[str] = None):
super().__init__(self.TYPE_ID, _id)
self._owner = owner
self._amount = amount
self._memo = memo

@property
def _plain_value(self):
return [
bytes.fromhex(self._owner.short_format),
self._amount.plain_value,
self._memo
]

39 changes: 39 additions & 0 deletions common/lib9c/actions/issue_token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from typing import List, Optional

from common.lib9c.actions import ActionBase
from common.lib9c.models.address import Address
from lib9c.models.fungible_asset_value import FungibleAssetValue


class ItemSpec:
def __init__(self, item_id: int, amount: int, tradable: bool):
self._item_id = item_id
self._amount = amount
self._tradable = tradable

@property
def plain_value(self):
return [
self._item_id,
self._amount,
self._tradable
]


class IssueToken(ActionBase):
TYPE_ID: str = "issue_token"

def __init__(self, *, avatar_addr: Address, fav_list: List[FungibleAssetValue], item_list: List[ItemSpec],
_id: Optional[str] = None):
super().__init__(self.TYPE_ID, _id)
self._avatar_addr = avatar_addr
self._fav_list = fav_list
self._item_list = item_list

@property
def _plain_value(self):
return {
"a": bytes.fromhex(self._avatar_addr.short_format),
"f": [x.plain_value for x in self._fav_list],
"i": [x.plain_value for x in self._item_list]
}
56 changes: 56 additions & 0 deletions worker/worker/manual/burn_asset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# NOTE: Use this lambda function by executing manually in AWS console.
import os
from datetime import timedelta, datetime

from common import logger
from common._crypto import Account
from common._graphql import GQL
from common.utils.aws import fetch_parameter, fetch_kms_key_id
from common.utils.receipt import PlanetID
from common.utils.transaction import create_unsigned_tx, append_signature_to_unsigned_tx
from lib9c.actions.burn_asset import BurnAsset
from lib9c.models.fungible_asset_value import FungibleAssetValue

# NOTE: Set these values by manual from here
PLANET_ID = PlanetID.XXX
GQL_URL = "https://example.com/graphql" # Use GQL host of desired chain
USE_ADHOC = True
# to here

HEADLESS_GQL_JWT_SECRET = fetch_parameter(
os.environ.get("REGION_NAME"),
f"{os.environ.get('STAGE')}_9c_IAP_HEADLESS_GQL_JWT_SECRET",
True
)["Value"]

DICT_HEADER = ["nonce", "owner", "amount", "memo"]
"""
--- Valid sample of event data
[
3,
"0xDbF4c6d0D7C74D390fADae680f2144D885c878df",
["SOULSTONE_1001", 0, 100],
"Burn by transfer to heimdall"
]
"""


def burn_asset(event, context):
gql = GQL(GQL_URL, HEADLESS_GQL_JWT_SECRET)
account = Account(fetch_kms_key_id(os.environ.get("STAGE"), os.environ.get("REGION_NAME"), adhoc=USE_ADHOC))
data = dict(zip(DICT_HEADER, event))

nonce = data["nonce"]
amt = data["amount"]
amount = FungibleAssetValue.from_raw_data(ticker=amt[0], decimal_places=amt[1], amount=amt[2])
action = BurnAsset(owner=data["owner"], amount=amount, memo=data["memo"])
utx = create_unsigned_tx(planet_id=PLANET_ID, public_key=account.pubkey.hex(), address=account.address, nonce=nonce,
plain_value=action.plain_value, timestamp=datetime.utcnow() + timedelta(days=1)
)
signature = account.sign_tx(utx)
signed_tx = append_signature_to_unsigned_tx(utx, signature)
success, message, tx_id = gql.stage(signed_tx)

logger.info(f"{success}::'{message}'::{tx_id} with nonce {nonce}")
logger.debug(signed_tx.hex())
return success, message, tx_id, nonce, signed_tx.hex()
66 changes: 66 additions & 0 deletions worker/worker/manual/issue_token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# NOTE: Use this lambda function by executing manually in AWS console.
import os
from datetime import timedelta, datetime

from common import logger
from common._crypto import Account
from common._graphql import GQL
from common.utils.aws import fetch_parameter, fetch_kms_key_id
from common.utils.receipt import PlanetID
from common.utils.transaction import create_unsigned_tx, append_signature_to_unsigned_tx
from lib9c.actions.issue_token import IssueToken, ItemSpec
from lib9c.models.fungible_asset_value import FungibleAssetValue

# NOTE: Set these values by manual from here
PLANET_ID = PlanetID.XXX
GQL_URL = "https://example.com/graphql" # Use GQL host of desired chain
USE_ADHOC = True
# to here

HEADLESS_GQL_JWT_SECRET = fetch_parameter(
os.environ.get("REGION_NAME"),
f"{os.environ.get('STAGE')}_9c_IAP_HEADLESS_GQL_JWT_SECRET",
True
)["Value"]

DICT_HEADER = ["nonce", "avatar_addr", "fav_list", "item_list"]
"""
--- Valid sample of event data
[
3,
"0xDbF4c6d0D7C74D390fADae680f2144D885c878df",
[
["SOULSTONE_1001", 0, 100],
["CRYSTAL", 18, 100]
],
[
[500000, 100, false],
[600201, 100, true]
]
]
"""


def issue_token(event, context):
gql = GQL(GQL_URL, HEADLESS_GQL_JWT_SECRET)
account = Account(fetch_kms_key_id(os.environ.get("STAGE"), os.environ.get("REGION_NAME"), adhoc=USE_ADHOC))
data = dict(zip(DICT_HEADER, event))

nonce = data["nonce"]
fav_list = []
for fav in data["fav_list"]:
fav_list.append(FungibleAssetValue.from_raw_data(ticker=fav[0], decimal_places=fav[1], amount=fav[2]))
item_list = []
for item in data["item_list"]:
item_list.append(ItemSpec(item_id=item[0], amount=item[1], tradable=item[2]))
action = IssueToken(avatar_addr=data["avatar_addr"], fav_list=fav_list, item_list=item_list)
utx = create_unsigned_tx(planet_id=PLANET_ID, public_key=account.pubkey.hex(), address=account.address, nonce=nonce,
plain_value=action.plain_value, timestamp=datetime.utcnow() + timedelta(days=1)
)
signature = account.sign_tx(utx)
signed_tx = append_signature_to_unsigned_tx(utx, signature)
success, message, tx_id = gql.stage(signed_tx)

logger.info(f"{success}::'{message}'::{tx_id} with nonce {nonce}")
logger.debug(signed_tx.hex())
return success, message, tx_id, nonce, signed_tx.hex()
File renamed without changes.
36 changes: 33 additions & 3 deletions worker/worker_cdk_stack.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,12 +292,42 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
)

token_issuer = _lambda.Function(
self, f"{config.stage}-9c-iap-token-issue-function",
function_name=f"{config.stage}-9c-iap-issue-token",
self, f"{config.stage}-9c-iap-issue-tokens-from-garage-function",
function_name=f"{config.stage}-9c-iap-issue-tokens-from-garage",
runtime=_lambda.Runtime.PYTHON_3_10,
description=f"Execute IssueTokensFromGarage action",
code=_lambda.AssetCode("worker/worker", exclude=exclude_list),
handler="issue_tokens.issue",
handler="manual.issue_tokens_from_garage.issue",
layers=[layer],
role=role,
vpc=shared_stack.vpc,
timeout=cdk_core.Duration.seconds(300), # 5min
environment=env,
memory_size=256,
)

burn_asset = _lambda.Function(
self, f"{config.stage}-9c-iap-burn-asset-function",
function_name=f"{config.stage}-9c-iap-burn-asset",
runtime=_lambda.Runtime.PYTHON_3_10,
description=f"Execute BurnAsset action",
code=_lambda.AssetCode("worker/worker", exclude=exclude_list),
handler="manual.burn_asset.burn_asset",
layers=[layer],
role=role,
vpc=shared_stack.vpc,
timeout=cdk_core.Duration.seconds(300), # 5min
environment=env,
memory_size=256,
)

issue_token = _lambda.Function(
self, f"{config.stage}-9c-iap-issue-token-function",
function_name=f"{config.stage}-9c-iap-issue-token",
runtime=_lambda.Runtime.PYTHON_3_10,
description=f"Execute IssueToken action",
code=_lambda.AssetCode("worker/worker", exclude=exclude_list),
handler="manual.issue_token.issue_token",
layers=[layer],
role=role,
vpc=shared_stack.vpc,
Expand Down

0 comments on commit 5659517

Please sign in to comment.