Skip to content

Commit

Permalink
Merge pull request #292 from moonstream-to/garden-v2
Browse files Browse the repository at this point in the history
Implementing path predicates and rewards
  • Loading branch information
zomglings authored Aug 8, 2023
2 parents 247bb78 + 11a7584 commit 643f269
Show file tree
Hide file tree
Showing 8 changed files with 2,610 additions and 201 deletions.
368 changes: 368 additions & 0 deletions cli/web3cli/GOFPFacet.py

Large diffs are not rendered by default.

269 changes: 269 additions & 0 deletions cli/web3cli/GOFPPredicates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,269 @@
# Code generated by moonworm : https://github.com/bugout-dev/moonworm
# Moonworm version : 0.5.3

import argparse
import json
import os
from pathlib import Path
from typing import Any, Dict, List, Optional, Union

from brownie import Contract, network, project
from brownie.network.contract import ContractContainer
from eth_typing.evm import ChecksumAddress


PROJECT_DIRECTORY = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
BUILD_DIRECTORY = os.path.join(PROJECT_DIRECTORY, "build", "contracts")


def boolean_argument_type(raw_value: str) -> bool:
TRUE_VALUES = ["1", "t", "y", "true", "yes"]
FALSE_VALUES = ["0", "f", "n", "false", "no"]

if raw_value.lower() in TRUE_VALUES:
return True
elif raw_value.lower() in FALSE_VALUES:
return False

raise ValueError(
f"Invalid boolean argument: {raw_value}. Value must be one of: {','.join(TRUE_VALUES + FALSE_VALUES)}"
)


def bytes_argument_type(raw_value: str) -> str:
return raw_value


def get_abi_json(abi_name: str) -> List[Dict[str, Any]]:
abi_full_path = os.path.join(BUILD_DIRECTORY, f"{abi_name}.json")
if not os.path.isfile(abi_full_path):
raise IOError(
f"File does not exist: {abi_full_path}. Maybe you have to compile the smart contracts?"
)

with open(abi_full_path, "r") as ifp:
build = json.load(ifp)

abi_json = build.get("abi")
if abi_json is None:
raise ValueError(f"Could not find ABI definition in: {abi_full_path}")

return abi_json


def contract_from_build(abi_name: str) -> ContractContainer:
# This is workaround because brownie currently doesn't support loading the same project multiple
# times. This causes problems when using multiple contracts from the same project in the same
# python project.
PROJECT = project.main.Project("moonworm", Path(PROJECT_DIRECTORY))

abi_full_path = os.path.join(BUILD_DIRECTORY, f"{abi_name}.json")
if not os.path.isfile(abi_full_path):
raise IOError(
f"File does not exist: {abi_full_path}. Maybe you have to compile the smart contracts?"
)

with open(abi_full_path, "r") as ifp:
build = json.load(ifp)

return ContractContainer(PROJECT, build)


class GOFPPredicates:
def __init__(self, contract_address: Optional[ChecksumAddress]):
self.contract_name = "GOFPPredicates"
self.address = contract_address
self.contract = None
self.abi = get_abi_json("GOFPPredicates")
if self.address is not None:
self.contract: Optional[Contract] = Contract.from_abi(
self.contract_name, self.address, self.abi
)

def deploy(self, transaction_config):
contract_class = contract_from_build(self.contract_name)
deployed_contract = contract_class.deploy(transaction_config)
self.address = deployed_contract.address
self.contract = deployed_contract
return deployed_contract.tx

def assert_contract_is_instantiated(self) -> None:
if self.contract is None:
raise Exception("contract has not been instantiated")

def verify_contract(self):
self.assert_contract_is_instantiated()
contract_class = contract_from_build(self.contract_name)
contract_class.publish_source(self.contract)

def does_not_exceed_max_tokens_in_session(
self,
max_stakable: int,
gofp_address: ChecksumAddress,
session_id: int,
player: ChecksumAddress,
nft_address: ChecksumAddress,
token_id: int,
block_number: Optional[Union[str, int]] = "latest",
) -> Any:
self.assert_contract_is_instantiated()
return self.contract.doesNotExceedMaxTokensInSession.call(
max_stakable,
gofp_address,
session_id,
player,
nft_address,
token_id,
block_identifier=block_number,
)


def get_transaction_config(args: argparse.Namespace) -> Dict[str, Any]:
signer = network.accounts.load(args.sender, args.password)
transaction_config: Dict[str, Any] = {"from": signer}
if args.gas_price is not None:
transaction_config["gas_price"] = args.gas_price
if args.max_fee_per_gas is not None:
transaction_config["max_fee"] = args.max_fee_per_gas
if args.max_priority_fee_per_gas is not None:
transaction_config["priority_fee"] = args.max_priority_fee_per_gas
if args.confirmations is not None:
transaction_config["required_confs"] = args.confirmations
if args.nonce is not None:
transaction_config["nonce"] = args.nonce
return transaction_config


def add_default_arguments(parser: argparse.ArgumentParser, transact: bool) -> None:
parser.add_argument(
"--network", required=True, help="Name of brownie network to connect to"
)
parser.add_argument(
"--address", required=False, help="Address of deployed contract to connect to"
)
if not transact:
parser.add_argument(
"--block-number",
required=False,
type=int,
help="Call at the given block number, defaults to latest",
)
return
parser.add_argument(
"--sender", required=True, help="Path to keystore file for transaction sender"
)
parser.add_argument(
"--password",
required=False,
help="Password to keystore file (if you do not provide it, you will be prompted for it)",
)
parser.add_argument(
"--gas-price", default=None, help="Gas price at which to submit transaction"
)
parser.add_argument(
"--max-fee-per-gas",
default=None,
help="Max fee per gas for EIP1559 transactions",
)
parser.add_argument(
"--max-priority-fee-per-gas",
default=None,
help="Max priority fee per gas for EIP1559 transactions",
)
parser.add_argument(
"--confirmations",
type=int,
default=None,
help="Number of confirmations to await before considering a transaction completed",
)
parser.add_argument(
"--nonce", type=int, default=None, help="Nonce for the transaction (optional)"
)
parser.add_argument(
"--value", default=None, help="Value of the transaction in wei(optional)"
)
parser.add_argument("--verbose", action="store_true", help="Print verbose output")


def handle_deploy(args: argparse.Namespace) -> None:
network.connect(args.network)
transaction_config = get_transaction_config(args)
contract = GOFPPredicates(None)
result = contract.deploy(transaction_config=transaction_config)
print(result)
if args.verbose:
print(result.info())


def handle_verify_contract(args: argparse.Namespace) -> None:
network.connect(args.network)
contract = GOFPPredicates(args.address)
result = contract.verify_contract()
print(result)


def handle_does_not_exceed_max_tokens_in_session(args: argparse.Namespace) -> None:
network.connect(args.network)
contract = GOFPPredicates(args.address)
result = contract.does_not_exceed_max_tokens_in_session(
max_stakable=args.max_stakable,
gofp_address=args.gofp_address,
session_id=args.session_id,
player=args.player,
nft_address=args.nft_address,
token_id=args.token_id,
block_number=args.block_number,
)
print(result)


def generate_cli() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="CLI for GOFPPredicates")
parser.set_defaults(func=lambda _: parser.print_help())
subcommands = parser.add_subparsers()

deploy_parser = subcommands.add_parser("deploy")
add_default_arguments(deploy_parser, True)
deploy_parser.set_defaults(func=handle_deploy)

verify_contract_parser = subcommands.add_parser("verify-contract")
add_default_arguments(verify_contract_parser, False)
verify_contract_parser.set_defaults(func=handle_verify_contract)

does_not_exceed_max_tokens_in_session_parser = subcommands.add_parser(
"does-not-exceed-max-tokens-in-session"
)
add_default_arguments(does_not_exceed_max_tokens_in_session_parser, False)
does_not_exceed_max_tokens_in_session_parser.add_argument(
"--max-stakable", required=True, help="Type: uint256", type=int
)
does_not_exceed_max_tokens_in_session_parser.add_argument(
"--gofp-address", required=True, help="Type: address"
)
does_not_exceed_max_tokens_in_session_parser.add_argument(
"--session-id", required=True, help="Type: uint256", type=int
)
does_not_exceed_max_tokens_in_session_parser.add_argument(
"--player", required=True, help="Type: address"
)
does_not_exceed_max_tokens_in_session_parser.add_argument(
"--nft-address", required=True, help="Type: address"
)
does_not_exceed_max_tokens_in_session_parser.add_argument(
"--token-id", required=True, help="Type: uint256", type=int
)
does_not_exceed_max_tokens_in_session_parser.set_defaults(
func=handle_does_not_exceed_max_tokens_in_session
)

return parser


def main() -> None:
parser = generate_cli()
args = parser.parse_args()
args.func(args)


if __name__ == "__main__":
main()
13 changes: 12 additions & 1 deletion cli/web3cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
setup_drop,
CraftingFacet,
GOFPFacet,
GOFPPredicates,
InventoryFacet,
)

Expand All @@ -25,7 +26,6 @@


def main() -> None:

parser = argparse.ArgumentParser(
description="dao: The command line interface to Moonstream DAO"
)
Expand Down Expand Up @@ -68,6 +68,17 @@ def main() -> None:
setup_drop_parser = setup_drop.generate_cli()
subparsers.add_parser("setup-drop", parents=[setup_drop_parser], add_help=False)

predicates_usage = "Predicates for use with Moonstream game mechanics"
predicates_parser = subparsers.add_parser(
"predicates", help=predicates_usage, description=predicates_usage
)
predicates_parser.set_defaults(func=lambda _: predicates_parser.print_help())
predicates_subparsers = predicates_parser.add_subparsers()

gofp_predicates_parser = GOFPPredicates.generate_cli()
predicates_subparsers.add_parser(
"gofp", parents=[gofp_predicates_parser], add_help=False
)
inventory_parser = InventoryFacet.generate_cli()
subparsers.add_parser("inventory", parents=[inventory_parser], add_help=False)

Expand Down
Loading

0 comments on commit 643f269

Please sign in to comment.