From a6b00937f29380d00dcff9c946a8c3c286e389fa Mon Sep 17 00:00:00 2001 From: Sagar Shah Date: Wed, 9 Aug 2023 15:43:48 -0500 Subject: [PATCH 01/24] task: update ENS widget description text and add buffer time (#228) --- .../ens_registration_contract_workflow.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/ui_workflows/ens/contract_abi_integratrion/ens_registration_contract_workflow.py b/ui_workflows/ens/contract_abi_integratrion/ens_registration_contract_workflow.py index b2880101..376f34bb 100644 --- a/ui_workflows/ens/contract_abi_integratrion/ens_registration_contract_workflow.py +++ b/ui_workflows/ens/contract_abi_integratrion/ens_registration_contract_workflow.py @@ -13,6 +13,10 @@ from ..common import is_domain_registered, get_ens_registrar_controller_contract, ENS_PUBLIC_RESOLVER_ADDRESS ONE_MINUTE_REQUIRED_WAIT = 60 + +# Add a Buffer time to ENS 1min wait time to account for any clock drift between systems +BUFFER_TIME_SECS = 10 + ONE_YEAR_DURATION = 365 * 24 * 60 * 60 class ENSRegistrationContractWorkflow(BaseMultiStepContractWorkflow): @@ -22,8 +26,8 @@ def __init__(self, wallet_chain_id: int, wallet_address: str, chat_message_id: s self.domain = workflow_params['domain'] self.name_label = self.domain.split('.')[0] - step1 = RunnableStep("request_registration", WorkflowStepUserActionType.tx, f"ENS domain {self.domain} registration request. After confirming transaction, ENS will take ~1min to process next step", self.step_1_request_registration) - step2 = RunnableStep("confirm_registration", WorkflowStepUserActionType.tx, f"ENS domain {self.domain} confirm registration", self.step_2_confirm_registration) + step1 = RunnableStep("request_registration", WorkflowStepUserActionType.tx, f"ENS domain {self.domain} registration request for 1 year. After confirming transaction, ENS will take ~1min to process next step", self.step_1_request_registration) + step2 = RunnableStep("confirm_registration", WorkflowStepUserActionType.tx, f"ENS domain {self.domain} confirm registration for 1 year", self.step_2_confirm_registration) steps = [step1, step2] @@ -79,7 +83,7 @@ def step_2_confirm_registration(self) -> ContractStepProcessingResult: secret = self.prev_step.step_state['secret'] # Wait for 1 min as per ENS docs - https://docs.ens.domains/contract-api-reference/.eth-permanent-registrar/controller - time.sleep(ONE_MINUTE_REQUIRED_WAIT) + time.sleep(ONE_MINUTE_REQUIRED_WAIT + BUFFER_TIME_SECS) rent_price = get_ens_registrar_controller_contract().functions.rentPrice(self.name_label, ONE_YEAR_DURATION).call({}) From 78e9cea22257247db08ff9bb62d396e8035b44d6 Mon Sep 17 00:00:00 2001 From: Sabnock <24715302+Sabnock01@users.noreply.github.com> Date: Wed, 9 Aug 2023 18:31:49 -0500 Subject: [PATCH 02/24] feat: Arbitrum integration for ETH deposit/withdrawal (#197) * feat: add arbitrum eth transfer integration * fix: arbitrum-eth args * update widget index * chore: move to bottom * feat: handle any token * fix: revert formatting * fix: require error --------- Co-authored-by: marcomariscal --- chat/display_widgets.py | 8 +++++++- knowledge_base/widgets.yaml | 32 +++++++++++++++++++++++++++++++- utils/constants.py | 2 +- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/chat/display_widgets.py b/chat/display_widgets.py index e27bbb92..28465e45 100644 --- a/chat/display_widgets.py +++ b/chat/display_widgets.py @@ -64,7 +64,7 @@ def _widgetize_inner(command: str, params: str, depth: int = 0) -> str: operation = params['operation'] if operation == 'create': prefix = params.get('prefix') - prefix = f' ({prefix})' if prefix else '' + prefix = f' ({prefix})' if prefix else '' lines.append(f'A list of items{prefix}:') elif operation == 'update': prefix = params.get('prefix') or '' @@ -138,6 +138,12 @@ def _widgetize_inner(command: str, params: str, depth: int = 0) -> str: elif command == 'zksync-withdraw': params = json.loads(params) lines.append(f"ZkSync bridge withdraw action for token: {params['token']}, amount: {params['amount']}.") + elif command == 'arbitrum-deposit': + params = json.load(params) + lines.append(f"Arbitrum bridge deposit action for token {params['token']} amount: {params['amount']}.") + elif command == 'arbitrum-withdraw': + params = json.load(params) + lines.append(f"Arbitrum bridge withdraw action for token: {params['token']}, amount: {params['amount']}.") elif command == 'stake-sfrxeth': params = json.load(params) lines.append(f"sfrxETH deposit action for address: {params['receiver']}, amount: {params['value']}.") diff --git a/knowledge_base/widgets.yaml b/knowledge_base/widgets.yaml index e94c870d..973116b5 100644 --- a/knowledge_base/widgets.yaml +++ b/knowledge_base/widgets.yaml @@ -600,6 +600,36 @@ - value type: object return_value_description: '' +- _name_: display_arbitrum_deposit + description: Used to bridge/deposit ETH or token from mainnet L1 to arbitrum L2. + parameters: + properties: + token: + description: token to deposit/bridge + type: string + amount: + description: amount to deposit + type: string + required: + - token + - amount + type: object + return_value_description: '' +- _name_: display_arbitrum_withdraw + description: Used to withdraw ETH from arbitrum L2 to mainnet L1 + parameters: + properties: + token: + description: token to withdraw + type: string + amount: + description: amount to withdraw + type: string + required: + - token + - amount + type: object + return_value_description: '' - _name_: display_yield_protocol_lend description: use the yield protocol to lend tokens at a fixed rate parameters: @@ -663,4 +693,4 @@ required: - borrowToken type: object - return_value_description: "" \ No newline at end of file + return_value_description: "" diff --git a/utils/constants.py b/utils/constants.py index 3d93d4c3..0a559066 100644 --- a/utils/constants.py +++ b/utils/constants.py @@ -53,7 +53,7 @@ WIDGET_INFO_TOKEN_LIMIT = 4000 # Widget Index -WIDGET_INDEX_NAME = "WidgetV18" +WIDGET_INDEX_NAME = "WidgetV19" def get_widget_index_name(): if env.is_local(): From f8b3be8be9a0410441507d83e223ae61ee2cdfa4 Mon Sep 17 00:00:00 2001 From: Sagar Shah Date: Thu, 10 Aug 2023 13:52:46 -0500 Subject: [PATCH 03/24] task: improve ENS set avatar workflow (#229) --- chat/display_widgets.py | 9 +++++++++ knowledge_base/widgets.yaml | 4 ++++ tools/index_widget.py | 3 ++- .../ens_set_avatar_nft.py | 15 +++++++++------ .../tests/test_ens_set_avatar_nft.py | 7 ++++--- utils/constants.py | 2 +- 6 files changed, 29 insertions(+), 11 deletions(-) diff --git a/chat/display_widgets.py b/chat/display_widgets.py index 28465e45..00dedc0f 100644 --- a/chat/display_widgets.py +++ b/chat/display_widgets.py @@ -59,6 +59,15 @@ def _widgetize_inner(command: str, params: str, depth: int = 0) -> str: f"-Item {idx}.{_widgetize(item['name'], json.dumps(item['params']), depth=depth)}" for idx, item in enumerate(items, start=1) ]) + elif command == 'nft-asset-list-container': + params = json.loads(params) + nfts = params['assets'] + lines.extend([ + f"A list with {len(nfts)} NFTs:", + ] + [ + f"-Item {idx}.{_widgetize(nft['name'], json.dumps(nft['params']), depth=depth)}" + for idx, nft in enumerate(nfts, start=1) + ]) elif command == 'streaming-list-container': params = json.loads(params) operation = params['operation'] diff --git a/knowledge_base/widgets.yaml b/knowledge_base/widgets.yaml index 973116b5..5bf628f3 100644 --- a/knowledge_base/widgets.yaml +++ b/knowledge_base/widgets.yaml @@ -314,10 +314,14 @@ nftId: description: Token ID of the NFT. type: string + collectionName: + description: Name of NFT collection. Use an empty string if the input parameter value is unknown but do not ask user to input empty string. + type: string required: - domain - nftContractAddress - nftId + - collectionName type: object return_value_description: '' - _name_: aave_supply diff --git a/tools/index_widget.py b/tools/index_widget.py index b289a72e..c0f02a21 100644 --- a/tools/index_widget.py +++ b/tools/index_widget.py @@ -638,7 +638,7 @@ def set_ens_primary_name(domain: str) ->TxPayloadForSending: @error_wrap @ensure_wallet_connected -def set_ens_avatar_nft(domain: str, nftContractAddress: str, nftId: str) ->TxPayloadForSending: +def set_ens_avatar_nft(domain: str, nftContractAddress: str, nftId: str, collectionName: str) ->TxPayloadForSending: wallet_chain_id = 1 # TODO: get from context wallet_address = context.get_wallet_address() user_chat_message_id = context.get_user_chat_message_id() @@ -647,6 +647,7 @@ def set_ens_avatar_nft(domain: str, nftContractAddress: str, nftId: str) ->TxPay 'domain': domain, 'nftContractAddress': nftContractAddress, 'nftId': nftId, + 'collectionName': collectionName } result = ens.ENSSetAvatarNFTWorkflow(wallet_chain_id, wallet_address, user_chat_message_id, params).run() diff --git a/ui_workflows/ens/contract_abi_integratrion/ens_set_avatar_nft.py b/ui_workflows/ens/contract_abi_integratrion/ens_set_avatar_nft.py index 2109bc76..923129cc 100644 --- a/ui_workflows/ens/contract_abi_integratrion/ens_set_avatar_nft.py +++ b/ui_workflows/ens/contract_abi_integratrion/ens_set_avatar_nft.py @@ -18,10 +18,13 @@ class ENSSetAvatarNFTWorkflow(BaseSingleStepContractWorkflow): def __init__(self, wallet_chain_id: int, wallet_address: str, chat_message_id: str, workflow_params: Dict) -> None: self.domain = workflow_params['domain'] - self.nftContractAddress = workflow_params['nftContractAddress'] - self.nftId = workflow_params['nftId'] + self.nft_contract_address = workflow_params['nftContractAddress'] + self.nft_id = workflow_params['nftId'] + self.collection_name = workflow_params['collectionName'] - user_description = f"Set avatar for ENS {self.domain}" + collection_name_text = self.collection_name or 'NFT' + + user_description = f"Set {collection_name_text} #{self.nft_id} as avatar for ENS {self.domain}" super().__init__(wallet_chain_id, wallet_address, chat_message_id, user_description, self.WORKFLOW_TYPE, workflow_params) @@ -29,10 +32,10 @@ def _general_workflow_validation(self): if not self.domain: raise WorkflowValidationError("Unable to interpret an ENS domain in current chat for setting avatar, please specify an ENS domain") - if not self.nftContractAddress: + if not self.nft_contract_address: raise WorkflowValidationError("Unable to interpret an NFT collection in current chat for setting avatar, ask for a collection first and try again") - if not self.nftId: + if not self.nft_id: raise WorkflowValidationError("Unable to interpret an NFT ID in current chat for setting avatar, please specify an NFT ID") ens_update_common_pre_workflow_validation(self.web3_provider, self.domain, self.wallet_address) @@ -41,7 +44,7 @@ def _run(self) -> Result: params = { "domain": self.domain, "key": "avatar", - "value": f"eip155:1/erc721:{self.nftContractAddress}/{self.nftId}" + "value": f"eip155:1/erc721:{self.nft_contract_address}/{self.nft_id}" } result = ENSSetTextWorkflow(self.wallet_chain_id, self.wallet_address, self.chat_message_id, params).run() diff --git a/ui_workflows/ens/contract_abi_integratrion/tests/test_ens_set_avatar_nft.py b/ui_workflows/ens/contract_abi_integratrion/tests/test_ens_set_avatar_nft.py index 63b1ff08..c9da3186 100644 --- a/ui_workflows/ens/contract_abi_integratrion/tests/test_ens_set_avatar_nft.py +++ b/ui_workflows/ens/contract_abi_integratrion/tests/test_ens_set_avatar_nft.py @@ -5,14 +5,15 @@ # Invoke this with python -m pytest -s -k "test_contract_ens_set_avatar_nft" def test_contract_ens_set_avatar_nft(setup_fork): - domain = "owocki.gitcoin.eth" - wallet_address = "0xDDF369C3bf18b1B12EA295d597B943b955eF4671" + domain = "vitalik.eth" + wallet_address = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" wallet_chain_id = 1 # Tenderly Mainnet Fork mock_chat_message_id = str(uuid.uuid4()) workflow_params = { "domain": domain, "nftContractAddress": "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D", - "nftId": "2836" + "nftId": "2836", + "collectionName": "Bored Ape Yacht Club" } result = ENSSetAvatarNFTWorkflow(wallet_chain_id, wallet_address, mock_chat_message_id, workflow_params).run() diff --git a/utils/constants.py b/utils/constants.py index 0a559066..4fc1db93 100644 --- a/utils/constants.py +++ b/utils/constants.py @@ -53,7 +53,7 @@ WIDGET_INFO_TOKEN_LIMIT = 4000 # Widget Index -WIDGET_INDEX_NAME = "WidgetV19" +WIDGET_INDEX_NAME = "WidgetV20" def get_widget_index_name(): if env.is_local(): From 8bb74fecc61648385670ab8b19012f0b635e2574 Mon Sep 17 00:00:00 2001 From: Harsh Raj Date: Sat, 12 Aug 2023 01:30:43 +0530 Subject: [PATCH 04/24] task: change sys prompt --- chat/chatgpt_function_call.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chat/chatgpt_function_call.py b/chat/chatgpt_function_call.py index cd1fad2b..3770be79 100644 --- a/chat/chatgpt_function_call.py +++ b/chat/chatgpt_function_call.py @@ -31,7 +31,7 @@ from tools.index_widget import * SYSTEM_MESSAGE_DEFAULT = \ -"""You are an agent that is trained to execute functions based on a user request. If you found a suitable function but not all the input parameters are known, ask for them. Otherwise just proceed with calling the function without reconfirming. +"""You are an agent named Cacti, that is trained to execute functions based on a user request. If you found a suitable function but not all the input parameters are known, ask for them. Otherwise just proceed with calling the function without reconfirming. Here is the user personal information, which you can use as input parameters of the functions. # USER INFO: From f66b4e3f56826c2ef531ee1cefe55053e7cbb02a Mon Sep 17 00:00:00 2001 From: Kah Keng Tay Date: Mon, 14 Aug 2023 15:26:44 -0700 Subject: [PATCH 05/24] opensea: filter listings by original address --- integrations/opensea.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/integrations/opensea.py b/integrations/opensea.py index 4239460f..54156c8a 100644 --- a/integrations/opensea.py +++ b/integrations/opensea.py @@ -104,15 +104,20 @@ def fetch_listings(address: str, token_id: str) -> List[NFTListing]: return ret -def fetch_all_listings(slug: str) -> List[NFTListing]: +def fetch_all_listings(address: str) -> List[NFTListing]: """Fetch all listings for a collection.""" # NOTE: a given token ID might have more than one listing + contract = fetch_contract(address) + slug = contract.slug limit = PAGE_LIMIT next_cursor = None ret = [] - # Arbitary limit to optimize for latency, based on hueristics related to observed number of NFTs listed for blue-chip collections. + # Arbitary limit to optimize for latency, based on hueristics related to observed number of NFTs listed for blue-chip collections. max_results = 300 - while len(ret) < max_results: + max_queries = 5 + queries = 0 + while len(ret) < max_results and queries < max_queries: + queries += 1 q = urlencode(dict( limit=limit, **(dict(next=next_cursor) if next_cursor else {}) @@ -123,6 +128,9 @@ def fetch_all_listings(slug: str) -> List[NFTListing]: obj = response.json() for item in obj['listings']: offer = item["protocol_data"]["parameters"]["offer"][0] + item_address = offer["token"] + if item_address != address: + continue current_price = item["price"]["current"] currency = current_price["currency"] price_value = int(current_price['value']) @@ -132,7 +140,7 @@ def fetch_all_listings(slug: str) -> List[NFTListing]: price_str = f"{price_value / 10 ** current_price['decimals']} {currency}" listing = NFTListing( chain=item["chain"], - address=offer["token"], + address=item_address, token_id=offer["identifierOrCriteria"], price_str=price_str, price_value=price_value, @@ -161,8 +169,7 @@ def _get_listing_prices(): def fetch_contract_listing_prices_with_retries(address: str) -> Dict[str, Dict[str, Union[str, int]]]: def _get_listing_prices(): - contract = fetch_contract(address) - listings = fetch_all_listings(contract.slug) + listings = fetch_all_listings(address) ret = {} for listing in listings: if listing.token_id not in ret or ret[listing.token_id].price_value > listing.price_value: From b7fcf2a894acd1cee96cfa9fbcc470acb7c8522f Mon Sep 17 00:00:00 2001 From: Kah Keng Tay Date: Mon, 14 Aug 2023 17:02:59 -0700 Subject: [PATCH 06/24] center: don't bubble up failed request errors --- integrations/center.py | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/integrations/center.py b/integrations/center.py index 32af4be5..0784aee6 100644 --- a/integrations/center.py +++ b/integrations/center.py @@ -1,5 +1,6 @@ from dataclasses import dataclass from typing import Any, Dict, Generator, List, Optional, Union +import traceback from urllib.parse import urlencode import requests @@ -192,7 +193,11 @@ def fetch_nft_search(search_str: str) -> Generator[Union[NFTCollection, NFTAsset url = f"{API_URL}/{network}/search?{q}" timing.log('search_begin') response = requests.get(url, headers=HEADERS) - response.raise_for_status() + try: + response.raise_for_status() + except Exception: + traceback.print_exc() + break timing.log('search_done') obj = response.json() for r in obj['results']: @@ -264,7 +269,11 @@ def fetch_nft_search_collection_by_trait(network: str, address: str, trait_name: )) url = f"{API_URL}/{network}/{address}/assets/searchByTraits?{q}" response = requests.post(url, headers=headers, json=payload) - response.raise_for_status() + try: + response.raise_for_status() + except Exception: + traceback.print_exc() + break timing.log('search_done') obj = response.json() if not obj['items']: @@ -331,7 +340,11 @@ def fetch_nft_collection_assets(network: str, address: str) -> NFTCollectionAsse ]} url = f"{API_URL}/{network}/assets" response = requests.post(url, headers=HEADERS, json=payload) - response.raise_for_status() + try: + response.raise_for_status() + except Exception: + traceback.print_exc() + break obj = response.json() for item in obj: if not item: @@ -389,7 +402,11 @@ def fetch_nft_collection_assets_for_sale(network: str, address: str, _skip_timin ]} url = f"{API_URL}/{network}/assets" response = requests.post(url, headers=HEADERS, json=payload) - response.raise_for_status() + try: + response.raise_for_status() + except Exception: + traceback.print_exc() + break if not _skip_timing: timing.log('search_done') obj = response.json() @@ -436,7 +453,11 @@ def fetch_nft_collection_traits(network: str, address: str) -> NFTCollectionTrai )) url = f"{API_URL}/{network}/{address}/traits?{q}" response = requests.get(url, headers=HEADERS) - response.raise_for_status() + try: + response.raise_for_status() + except Exception: + traceback.print_exc() + break obj = response.json() for item in obj['items']: total = 0 @@ -475,7 +496,11 @@ def fetch_nft_collection_trait_values(network: str, address: str, trait: str) -> )) url = f"{API_URL}/{network}/{address}/traits/{trait}?{q}" response = requests.get(url, headers=HEADERS) - response.raise_for_status() + try: + response.raise_for_status() + except Exception: + traceback.print_exc() + break obj = response.json() total = 0 for item in obj['items']: From 8c5e2be88239ae464aaed63b10a08c23dcb00906 Mon Sep 17 00:00:00 2001 From: Kah Keng Tay Date: Mon, 14 Aug 2023 17:16:21 -0700 Subject: [PATCH 07/24] opensea: move request retries to be closer to original request --- integrations/opensea.py | 73 ++++++++++++++++++++++------------------- 1 file changed, 40 insertions(+), 33 deletions(-) diff --git a/integrations/opensea.py b/integrations/opensea.py index 54156c8a..6b1f2471 100644 --- a/integrations/opensea.py +++ b/integrations/opensea.py @@ -53,9 +53,16 @@ class NFTListing: def fetch_contract(address: str) -> NFTContract: """Fetch data about a contract (collection).""" url = f"{API_V1_URL}/asset_contract/{address}" - response = requests.get(url, headers=HEADERS) - response.raise_for_status() - obj = response.json() + + def _exec_request(): + response = requests.get(url, headers=HEADERS) + response.raise_for_status() + return response.json() + + obj = retry_on_exceptions_with_backoff( + _exec_request, + [ErrorToRetry(requests.exceptions.HTTPError, _should_retry_exception)], + ) collection = obj["collection"] return NFTContract( chain=obj["chain_identifier"], @@ -82,9 +89,16 @@ def fetch_listings(address: str, token_id: str) -> List[NFTListing]: **(dict(next=next_cursor) if next_cursor else {}) )) url = f"{API_V2_URL}/orders/{chain}/seaport/listings?{q}" - response = requests.get(url, headers=HEADERS) - response.raise_for_status() - obj = response.json() + + def _exec_request(): + response = requests.get(url, headers=HEADERS) + response.raise_for_status() + return response.json() + + obj = retry_on_exceptions_with_backoff( + _exec_request, + [ErrorToRetry(requests.exceptions.HTTPError, _should_retry_exception)], + ) for item in obj['orders']: offer = item["protocol_data"]["parameters"]["offer"][0] price_value = int(item["current_price"]) @@ -123,9 +137,16 @@ def fetch_all_listings(address: str) -> List[NFTListing]: **(dict(next=next_cursor) if next_cursor else {}) )) url = f"{API_V2_URL}/listings/collection/{slug}/all?{q}" - response = requests.get(url, headers=HEADERS) - response.raise_for_status() - obj = response.json() + + def _exec_request(): + response = requests.get(url, headers=HEADERS) + response.raise_for_status() + return response.json() + + obj = retry_on_exceptions_with_backoff( + _exec_request, + [ErrorToRetry(requests.exceptions.HTTPError, _should_retry_exception)], + ) for item in obj['listings']: offer = item["protocol_data"]["parameters"]["offer"][0] item_address = offer["token"] @@ -153,33 +174,19 @@ def fetch_all_listings(address: str) -> List[NFTListing]: def fetch_asset_listing_prices_with_retries(address: str, token_id: str) -> Optional[Dict[str, Union[str, int]]]: - - def _get_listing_prices(): - listings = fetch_listings(address, token_id) - for listing in listings: - return dict(price_str=listing.price_str, price_value=listing.price_value) - return None - - return retry_on_exceptions_with_backoff( - _get_listing_prices, - [ErrorToRetry(requests.exceptions.HTTPError, _should_retry_exception)], - ) + listings = fetch_listings(address, token_id) + for listing in listings: + return dict(price_str=listing.price_str, price_value=listing.price_value) + return None def fetch_contract_listing_prices_with_retries(address: str) -> Dict[str, Dict[str, Union[str, int]]]: - - def _get_listing_prices(): - listings = fetch_all_listings(address) - ret = {} - for listing in listings: - if listing.token_id not in ret or ret[listing.token_id].price_value > listing.price_value: - ret[listing.token_id] = listing - return {token_id: dict(price_str=listing.price_str, price_value=listing.price_value) for token_id, listing in ret.items()} - - return retry_on_exceptions_with_backoff( - _get_listing_prices, - [ErrorToRetry(requests.exceptions.HTTPError, _should_retry_exception)], - ) + listings = fetch_all_listings(address) + ret = {} + for listing in listings: + if listing.token_id not in ret or ret[listing.token_id].price_value > listing.price_value: + ret[listing.token_id] = listing + return {token_id: dict(price_str=listing.price_str, price_value=listing.price_value) for token_id, listing in ret.items()} def _should_retry_exception(exception): From 94fb71c95faf8b1e2428f8198b95a40ebc86b44c Mon Sep 17 00:00:00 2001 From: Kah Keng Tay Date: Mon, 14 Aug 2023 17:22:56 -0700 Subject: [PATCH 08/24] utils: change to user-friendly error message --- utils/common.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/common.py b/utils/common.py index 58d4a6bb..2e1ed194 100644 --- a/utils/common.py +++ b/utils/common.py @@ -165,7 +165,7 @@ def wrapped_fn(*args, **kwargs): return str(e) except Exception as e: traceback.print_exc() - return f'Got exception evaluating {fn.__name__}(args={args}, kwargs={kwargs}): {e}' + return "An error occurred. Please try again." @functools.wraps(fn) def wrapped_generator_fn(*args, **kwargs): From cc0e1212cd53bdf4fd1b40b164a85b49dac472c0 Mon Sep 17 00:00:00 2001 From: Sagar Shah Date: Tue, 15 Aug 2023 11:41:29 -0500 Subject: [PATCH 09/24] task: implement nft purchasing and fix display widgets (#230) --- chat/display_widgets.py | 49 ++++---- finetune/generate.py | 25 +++- integrations/center.py | 68 ++++++++++- integrations/opensea.py | 114 +++++++++++------- tools/index_widget.py | 5 +- .../aave_borrow_contract_workflow.py | 2 +- .../aave_repay_contract_workflow.py | 2 +- .../aave_supply_contract_workflow.py | 2 +- .../aave_withdraw_contract_workflow.py | 2 +- 9 files changed, 191 insertions(+), 78 deletions(-) diff --git a/chat/display_widgets.py b/chat/display_widgets.py index 00dedc0f..06fa7ddd 100644 --- a/chat/display_widgets.py +++ b/chat/display_widgets.py @@ -3,6 +3,7 @@ from typing import List import re import json +import traceback # this differs from tool/index_widget.py's RE_COMMAND because it matches @@ -35,6 +36,7 @@ def _widgetize(command: str, params: str, depth: int = 0) -> str: try: return _widgetize_inner(command, params, depth) except Exception: + traceback.print_exc() return f"An error occurred evaluating command: {command}({params})" @@ -47,9 +49,10 @@ def _widgetize_inner(command: str, params: str, depth: int = 0) -> str: elif command == 'uniswap': items = params.split(",") lines.append(f"A swap of {items[0]} to {items[1]} with transaction keyword {items[2]} and amount {items[3]}") - elif command == 'buy-nft': - items = params.split(",") - lines.append(f"A widget to purchase token {items[1]} of contract address {items[0]}") + elif command == 'nft-asset-fulfillment-container': + params = json.loads(params) + asset = params['asset']['params'] + lines.append(f"A widget to purchase NFT for collection name {asset['collectionName']}, NFT address {asset['address']}, NFT ID {asset['tokenId']}") elif command == 'list-container': params = json.loads(params) items = params['items'] @@ -139,35 +142,35 @@ def _widgetize_inner(command: str, params: str, depth: int = 0) -> str: params = json.loads(params) lines.append(f"A workflow step was presented: {params['description']}.") elif command == 'yield-farm': - params = json.loads(params) - lines.append(f"Yield farm action for network: {params['network']}, project: {params['project']}, token: {params['token']}, amount: {params['amount']}.") + items = params.split(",") + lines.append(f"Yield farm action for network: {items[1]}, project: {items[0]}, token: {items[2]}, amount: {items[3]}.") elif command == 'zksync-deposit': - params = json.loads(params) - lines.append(f"ZkSync bridge deposit action for token: {params['token']}, amount: {params['amount']}.") + items = params.split(",") + lines.append(f"ZkSync bridge deposit action for token: {items[0]}, amount: {items[1]}.") elif command == 'zksync-withdraw': - params = json.loads(params) - lines.append(f"ZkSync bridge withdraw action for token: {params['token']}, amount: {params['amount']}.") + items = params.split(",") + lines.append(f"ZkSync bridge withdraw action for token: {items[0]}, amount: {items[1]}.") elif command == 'arbitrum-deposit': - params = json.load(params) - lines.append(f"Arbitrum bridge deposit action for token {params['token']} amount: {params['amount']}.") + items = params.split(",") + lines.append(f"Arbitrum bridge deposit action for token {items[0]} amount: {items[1]}.") elif command == 'arbitrum-withdraw': - params = json.load(params) - lines.append(f"Arbitrum bridge withdraw action for token: {params['token']}, amount: {params['amount']}.") + items = params.split(",") + lines.append(f"Arbitrum bridge withdraw action for token: {items[0]}, amount: {items[1]}.") elif command == 'stake-sfrxeth': - params = json.load(params) - lines.append(f"sfrxETH deposit action for address: {params['receiver']}, amount: {params['value']}.") + items = params.split(",") + lines.append(f"sfrxETH deposit action for address: {items[0]}, amount: {items[1]}.") elif command == 'yield-protocol-lend': - params = json.loads(params) - lines.append(f"yield protocol lend action for token: {params['token']}, amount: {params['amount']}.") + items = params.split(",") + lines.append(f"yield protocol lend action for token: {items[0]}, amount: {items[1]}.") elif command == 'yield-protocol-lend-close': - params = json.loads(params) - lines.append(f"yield protocol lend close action for token: {params['token']}, amount: {params['amount']}.") + items = params.split(",") + lines.append(f"yield protocol lend close action for token: {items[0]}, amount: {items[1]}.") elif command == 'yield-protocol-borrow': - params = json.loads(params) - lines.append(f"yield protocol borrow action for borrow token: {params['borrowToken']}, borrow amount: {params['borrowAmount']}, collateral token: {params['collateralToken']}, collateral amount: {params['collateralAmount']}.") + items = params.split(",") + lines.append(f"yield protocol borrow action for borrow token: {items[0]}, borrow amount: {items[1]}, collateral token: {items[2]}, collateral amount: {items[3]}.") elif command == 'yield-protocol-borrow-close': - params = json.loads(params) - lines.append(f"yield protocol borrow close action: {params['borrowToken']}") + items = params.split(",") + lines.append(f"yield protocol borrow close action: {items[0]}") else: # assert 0, f'unrecognized command: {command}({params})' lines.append(f"An unrecognized command: {command}({params})") diff --git a/finetune/generate.py b/finetune/generate.py index 70971731..76128616 100644 --- a/finetune/generate.py +++ b/finetune/generate.py @@ -3,6 +3,7 @@ import enum import random import uuid +import json from tools.index_widget import ( StreamingListContainer, @@ -333,7 +334,29 @@ def generate_nft_asset_flow(asset: NFTAsset, already_referenced: bool): "purchase this asset", ] if already_referenced else [])) yield Message("user", message) - yield Message("bot", f"<|fetch-nft-buy-asset({asset.network},{asset.address},{asset.token_id})|>", f"<|display-buy-nft({asset.address},{asset.token_id})|>") + + nft_fulfillment_payload = dict( + isForSale=False, + orderParameters=dict( + offerer='sample-offerer', + param1='sample-param1' + ), + orderSignature="sample-signature", + asset=dict( + name="display-nft-asset-container", + params=dict( + network="ethereum-mainnet", + address=asset.address, + tokenId=asset.token_id, + collectionName=asset.collection_name, + name=asset.name, + previewImageUrl=asset.preview_image_url, + price=asset.price, + ) + ) + ) + + yield Message("bot", f"<|fetch-nft-buy-asset({asset.network},{asset.address},{asset.token_id})|>", f"<|display-nft-asset-fulfillment-container({json.dumps(nft_fulfillment_payload)})|>") def generate_wallet_balance_flow(token=None) -> Iterable[Message]: diff --git a/integrations/center.py b/integrations/center.py index 0784aee6..96e8da32 100644 --- a/integrations/center.py +++ b/integrations/center.py @@ -1,3 +1,4 @@ +import time from dataclasses import dataclass from typing import Any, Dict, Generator, List, Optional, Union import traceback @@ -120,6 +121,7 @@ class NFTAsset(ContainerMixin): collection_name: str name: str preview_image_url: str + description: str = '' price: Optional[str] = None def container_name(self) -> str: @@ -128,6 +130,22 @@ def container_name(self) -> str: def container_params(self) -> Dict: return dataclass_to_container_params(self) +@dataclass +class NFTAssetFulfillment(ContainerMixin): + is_for_sale: bool + asset: NFTAsset + order_parameters: Optional[Dict[str, Any]] = None + order_signature: Optional[str] = None + order_value: Optional[str] = None + protocol_address: Optional[str] = None + + def container_name(self) -> str: + return 'display-nft-asset-fulfillment-container' + + def container_params(self) -> Dict: + ret = dataclass_to_container_params(self) + ret['asset'] = self.asset.struct() + return ret @dataclass class NFTAssetTraitValue(ContainerMixin): @@ -537,15 +555,12 @@ def fetch_nft_asset(network: str, address: str, token_id: str) -> NFTAsset: collection_name=obj['collectionName'], name=obj['name'], preview_image_url=obj['mediumPreviewImageUrl'], + description=obj['metadata']['description'], ) def fetch_nft_asset_traits(network: str, address: str, token_id: str) -> NFTAssetTraits: - if network == "ethereum-mainnet": - price_dict = opensea.fetch_asset_listing_prices_with_retries(address, token_id) - price = price_dict['price_str'] if price_dict else 'unlisted' - else: - price = None + price = _fetch_nft_asset_price_str(network, address, token_id) url = f"{API_URL}/{network}/{address}/{token_id}" response = requests.get(url, headers=HEADERS) response.raise_for_status() @@ -621,4 +636,45 @@ def fetch_nfts_owned_by_address_or_domain(network: str, address_or_domain: str) timing.log('results_done') result = NFTAssetList(assets=assets) - return result \ No newline at end of file + return result + +def fetch_nft_buy(network: str, wallet_address: str, nft_address: str, token_id: str) -> NFTAssetFulfillment: + nft_asset = fetch_nft_asset(network, nft_address, token_id) + listing = opensea.fetch_asset_listing_with_retries(nft_address, token_id) + if listing is None: + return NFTAssetFulfillment( + is_for_sale=False, + asset=nft_asset + ) + + nft_asset.price = listing.price_str + + current_time_sec = int(time.time()) + is_listing_expired = listing.expiration_time < current_time_sec + + if is_listing_expired: + return NFTAssetFulfillment( + is_for_sale=False, + asset=nft_asset + ) + + fullfilment_data = opensea.fetch_fulfillment_data_with_retries(network, listing.order_hash, wallet_address, listing.protocol_address) + + return NFTAssetFulfillment( + is_for_sale=True, + asset=nft_asset, + order_parameters=fullfilment_data.parameters, + order_signature=fullfilment_data.signature, + order_value=str(fullfilment_data.value_amount), + protocol_address=listing.protocol_address + ) + + + +def _fetch_nft_asset_price_str(network: str, address: str, token_id: str) -> Optional[str]: + if network == "ethereum-mainnet": + price_dict = opensea.fetch_asset_listing_prices_with_retries(address, token_id) + price = price_dict['price_str'] if price_dict else 'unlisted' + else: + price = None + return price \ No newline at end of file diff --git a/integrations/opensea.py b/integrations/opensea.py index 6b1f2471..8238f876 100644 --- a/integrations/opensea.py +++ b/integrations/opensea.py @@ -23,13 +23,6 @@ MAX_RESULTS = 100 PAGE_LIMIT = 100 - -def fetch_nft_buy(network: str, address: str, token_id: str) -> str: - network = NETWORKS_MAP.get(network, network) - # TODO: for now, we just omit network altogether since frontend only works with ethereum - return f"<|display-buy-nft({address},{token_id})|>" - - # this represents an NFT collection @dataclass class NFTContract: @@ -48,6 +41,15 @@ class NFTListing: token_id: str price_str: str price_value: int + order_hash: Optional[str] = None + protocol_address: Optional[str] = None + expiration_time: Optional[int] = None + +@dataclass +class NFTFulfillmentData: + parameters: Dict[str, Any] + signature: str + value_amount: int def fetch_contract(address: str) -> NFTContract: @@ -77,44 +79,40 @@ def fetch_listings(address: str, token_id: str) -> List[NFTListing]: """Fetch cheapest listing for an asset.""" chain = "ethereum" limit = 1 - next_cursor = None ret = [] - while len(ret) < MAX_RESULTS: - q = urlencode(dict( - limit=limit, - asset_contract_address=address, - token_ids=token_id, - order_by='eth_price', - order_direction='asc', - **(dict(next=next_cursor) if next_cursor else {}) - )) - url = f"{API_V2_URL}/orders/{chain}/seaport/listings?{q}" + q = urlencode(dict( + limit=limit, + asset_contract_address=address, + token_ids=token_id, + order_by='eth_price', + order_direction='asc' + )) + url = f"{API_V2_URL}/orders/{chain}/seaport/listings?{q}" - def _exec_request(): - response = requests.get(url, headers=HEADERS) - response.raise_for_status() - return response.json() + def _exec_request(): + response = requests.get(url, headers=HEADERS) + response.raise_for_status() + return response.json() - obj = retry_on_exceptions_with_backoff( - _exec_request, - [ErrorToRetry(requests.exceptions.HTTPError, _should_retry_exception)], + obj = retry_on_exceptions_with_backoff( + _exec_request, + [ErrorToRetry(requests.exceptions.HTTPError, _should_retry_exception)], + ) + for item in obj['orders']: + price_value = int(item["current_price"]) + currency = "ETH" + price_str = f"{utils.w3.from_wei(price_value, 'ether')} {currency}" + listing = NFTListing( + chain=chain, + address=address, + token_id=token_id, + price_str=price_str, + price_value=price_value, + order_hash=item["order_hash"], + protocol_address=item["protocol_address"], + expiration_time=item["expiration_time"] ) - for item in obj['orders']: - offer = item["protocol_data"]["parameters"]["offer"][0] - price_value = int(item["current_price"]) - currency = "eth" - price_str = f"{utils.w3.from_wei(price_value, 'ether')} {currency}" - listing = NFTListing( - chain=chain, - address=address, - token_id=token_id, - price_str=price_str, - price_value=price_value, - ) - ret.append(listing) - next_cursor = obj.get("next") - if not next_cursor: - break + ret.append(listing) return ret @@ -164,7 +162,7 @@ def _exec_request(): address=item_address, token_id=offer["identifierOrCriteria"], price_str=price_str, - price_value=price_value, + price_value=price_value ) ret.append(listing) next_cursor = obj.get("next") @@ -179,6 +177,9 @@ def fetch_asset_listing_prices_with_retries(address: str, token_id: str) -> Opti return dict(price_str=listing.price_str, price_value=listing.price_value) return None +def fetch_asset_listing_with_retries(address: str, token_id: str) -> Optional[NFTListing]: + listings = fetch_listings(address, token_id) + return listings[0] if len(listings) > 0 else None def fetch_contract_listing_prices_with_retries(address: str) -> Dict[str, Dict[str, Union[str, int]]]: listings = fetch_all_listings(address) @@ -188,6 +189,35 @@ def fetch_contract_listing_prices_with_retries(address: str) -> Dict[str, Dict[s ret[listing.token_id] = listing return {token_id: dict(price_str=listing.price_str, price_value=listing.price_value) for token_id, listing in ret.items()} +def fetch_fulfillment_data_with_retries(network: str, order_hash: str, fulfiller_address: str, protocol_address: str) -> NFTFulfillmentData: + normalized_network = NETWORKS_MAP.get(network, network) + url = f"{API_V2_URL}/listings/fulfillment_data" + data = { + "listing": { + "hash": order_hash, + "chain": normalized_network, + "protocol_address": protocol_address, + }, + "fulfiller": { + "address": fulfiller_address, + }, + } + + def _exec_request(): + response = requests.post(url, headers=HEADERS, json=data) + response.raise_for_status() + return response.json() + + fulfillment_data = retry_on_exceptions_with_backoff( + _exec_request, + [ErrorToRetry(requests.exceptions.HTTPError, _should_retry_exception)], + ) + return NFTFulfillmentData( + parameters=fulfillment_data["fulfillment_data"]["orders"][0]["parameters"], + signature=fulfillment_data["fulfillment_data"]["orders"][0]["signature"], + value_amount=fulfillment_data["fulfillment_data"]["transaction"]["value"], + ) + def _should_retry_exception(exception): if exception.response.status_code in (400, 401, 402, 403, 404, 405, 406): diff --git a/tools/index_widget.py b/tools/index_widget.py index c0f02a21..9e3ab922 100644 --- a/tools/index_widget.py +++ b/tools/index_widget.py @@ -531,8 +531,9 @@ def fetch_nfts_owned_by_user(network: str = None) -> str: @error_wrap def fetch_nft_buy(network: str, address: str, token_id: str) -> str: - ret = opensea.fetch_nft_buy(network, address, token_id) - return ret + wallet_address = context.get_wallet_address() + nft_fulfillment_container = center.fetch_nft_buy(network, wallet_address, address, token_id) + return str(nft_fulfillment_container) @error_wrap diff --git a/ui_workflows/aave/contract_abi_integration/aave_borrow_contract_workflow.py b/ui_workflows/aave/contract_abi_integration/aave_borrow_contract_workflow.py index cadd566e..9418c98d 100644 --- a/ui_workflows/aave/contract_abi_integration/aave_borrow_contract_workflow.py +++ b/ui_workflows/aave/contract_abi_integration/aave_borrow_contract_workflow.py @@ -17,7 +17,7 @@ class AaveBorrowContractWorkflow(BaseMultiStepContractWorkflow): WORKFLOW_TYPE = 'aave-borrow' def __init__(self, wallet_chain_id: int, wallet_address: str, chat_message_id: str, workflow_params: Dict, multistep_workflow: Optional[MultiStepWorkflow] = None, curr_step_client_payload: Optional[WorkflowStepClientPayload] = None) -> None: - self.token = workflow_params["token"] + self.token = workflow_params["token"].upper() self.amount = workflow_params["amount"] if self.token == "ETH": diff --git a/ui_workflows/aave/contract_abi_integration/aave_repay_contract_workflow.py b/ui_workflows/aave/contract_abi_integration/aave_repay_contract_workflow.py index f551ec46..0354b0cf 100644 --- a/ui_workflows/aave/contract_abi_integration/aave_repay_contract_workflow.py +++ b/ui_workflows/aave/contract_abi_integration/aave_repay_contract_workflow.py @@ -13,7 +13,7 @@ class AaveRepayContractWorkflow(BaseMultiStepContractWorkflow): WORKFLOW_TYPE = 'aave-repay' def __init__(self, wallet_chain_id: int, wallet_address: str, chat_message_id: str, workflow_params: Dict, multistep_workflow: Optional[MultiStepWorkflow] = None, curr_step_client_payload: Optional[WorkflowStepClientPayload] = None) -> None: - self.token = workflow_params["token"] + self.token = workflow_params["token"].upper() self.amount = workflow_params["amount"] if self.token == "ETH": diff --git a/ui_workflows/aave/contract_abi_integration/aave_supply_contract_workflow.py b/ui_workflows/aave/contract_abi_integration/aave_supply_contract_workflow.py index adcb6e0a..f867850a 100644 --- a/ui_workflows/aave/contract_abi_integration/aave_supply_contract_workflow.py +++ b/ui_workflows/aave/contract_abi_integration/aave_supply_contract_workflow.py @@ -20,7 +20,7 @@ class AaveSupplyContractWorkflow(BaseMultiStepContractWorkflow): WORKFLOW_TYPE = 'aave-supply' def __init__(self, wallet_chain_id: int, wallet_address: str, chat_message_id: str, workflow_params: Dict, multistep_workflow: Optional[MultiStepWorkflow] = None, curr_step_client_payload: Optional[WorkflowStepClientPayload] = None) -> None: - self.token = workflow_params["token"] + self.token = workflow_params["token"].upper() self.amount = workflow_params["amount"] # Only one step for ETH as it doesn't require an approval step unlike ERC20 tokens diff --git a/ui_workflows/aave/contract_abi_integration/aave_withdraw_contract_workflow.py b/ui_workflows/aave/contract_abi_integration/aave_withdraw_contract_workflow.py index e30ee5fb..def72e15 100644 --- a/ui_workflows/aave/contract_abi_integration/aave_withdraw_contract_workflow.py +++ b/ui_workflows/aave/contract_abi_integration/aave_withdraw_contract_workflow.py @@ -13,7 +13,7 @@ class AaveWithdrawContractWorkflow(BaseMultiStepContractWorkflow): WORKFLOW_TYPE = 'aave-withdraw' def __init__(self, wallet_chain_id: int, wallet_address: str, chat_message_id: str, workflow_params: Dict, multistep_workflow: Optional[MultiStepWorkflow] = None, curr_step_client_payload: Optional[WorkflowStepClientPayload] = None) -> None: - self.token = workflow_params["token"] + self.token = workflow_params["token"].upper() self.amount = workflow_params["amount"] if self.token == "ETH": From 6ca1f8e3c2ecc0b64a2bf61c2711983cd5c47e02 Mon Sep 17 00:00:00 2001 From: Allan Niemerg Date: Wed, 16 Aug 2023 10:09:40 -0500 Subject: [PATCH 10/24] add AGPLv3 (#219) --- COPYING.md | 660 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 660 insertions(+) create mode 100644 COPYING.md diff --git a/COPYING.md b/COPYING.md new file mode 100644 index 00000000..c6f01c63 --- /dev/null +++ b/COPYING.md @@ -0,0 +1,660 @@ +# GNU AFFERO GENERAL PUBLIC LICENSE + +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +## Preamble + +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains +free software for all its users. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + +A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + +The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + +An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing +under this license. + +The precise terms and conditions for copying, distribution and +modification follow. + +## TERMS AND CONDITIONS + +### 0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public +License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +### 13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your +version supports such interaction) an opportunity to receive the +Corresponding Source of your version by providing access to the +Corresponding Source from a network server at no charge, through some +standard or customary means of facilitating copying of software. This +Corresponding Source shall include the Corresponding Source for any +work covered by version 3 of the GNU General Public License that is +incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + +### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU Affero General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever +published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +## How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively state +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper +mail. + +If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for +the specific requirements. + +You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU AGPL, see . From 660b702629111979993f25ad9dd845c6cbd64038 Mon Sep 17 00:00:00 2001 From: Allan Niemerg Date: Mon, 7 Aug 2023 11:03:35 -0500 Subject: [PATCH 11/24] Update README.md --- README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/README.md b/README.md index 56ac0154..8f41a81b 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,25 @@ Cacti includes a frontend and backend repo. This is the backend. The frontend is The Cacti backend manages chat interactions with OpenAI, chat history, and user logins. +### Features + +**Widget Commands**: Central to Cacti's extensible design are the Widget Commands. These commands act as functions that an LLM can call to display an interaction dialogue box, allowing users to engage in web3 actions or access data seamlessly. The Widget Commands can be expanded upon, allowing for a broad array of functions catered to the user's needs. + +**Eval**: Cacti employs a flexible evaluation framework that is crucial for developers wishing to assess the performance of added widgets. This includes features like hard-coded testing, automatic evaluations, and evaluations via manually annotated test samples that can be input via a CSV file. + +**Chat Context**: All dialog boxes can add information to the chat context, enabling the LLM use context added by previous widget commands to execute a later command effectively, enhancing the overall user experience. + +**Configurable Chat Modules**: Chat modules can be configured to permit the use of alternative LLMs, fine-tuned LLMs, alternate prompts to LLMs, etc. Different chat modules can be used just by using a modified URL. This allows for easy testing of potential improvements to the chat modes and new features. + +**Streaming Support**: Cacti supports streaming from LLM models, providing users with real-time updates. The system can sensibly handle widget commands included in the LLM stream, ensuring smooth and intuitive interactions. + +**Support for Structured/Rich Media Output**: Cacti offers the ability to handle widget commands that need to display structured or rich media output as part of the interface. This includes tables, NFTs, and other forms of rich media, allowing users to engage with a dynamic and visually engaging interface. + +**Cacti ReactJS Component Framework**: For easy UI integration, Cacti has built a ReactJS component framework that requires only basic ReactJS, HTML, and CSS skills. The components are composable, making it possible to mix and match the components to fit the information display requirements of the widget. Widget commands can be built on the frontend, or invoked from the backend using string responses. Developers can create more sophisticated functions by creating separate React components if needed. + +**Wallet-based Authentication**: Cacti uses wallet-based authentication specifically for web3 wallets like MetaMask. This provides a secure means of identification and ensures the secure execution of web3 transactions. + +**Transaction Handling**: Cacti is designed to handle web3 transactions on Ethereum or Layer 2 solutions (L2s). It abstracts away the complexity of transaction handling from the integrator. All the integrator needs to do is pass the transaction details, and Cacti takes care of the rest, ensuring a user-friendly experience for those engaging with web3 protocols. ## Running Locally From 914c3ec14ebe0e497711f7e3b1b7d634ed4b2c22 Mon Sep 17 00:00:00 2001 From: Sagar Shah Date: Mon, 21 Aug 2023 12:14:38 -0500 Subject: [PATCH 12/24] fix: switch to alchemy rpc for prod (#237) --- integrations/etherscan.py | 2 +- integrations/opensea.py | 8 +++++--- tools/index_widget.py | 9 +++++++-- utils/common.py | 7 ++++--- utils/constants.py | 2 +- 5 files changed, 18 insertions(+), 10 deletions(-) diff --git a/integrations/etherscan.py b/integrations/etherscan.py index 1cb14022..b8cd224b 100644 --- a/integrations/etherscan.py +++ b/integrations/etherscan.py @@ -1,6 +1,6 @@ import requests -from utils import ETHERSCAN_API_KEY, w3 +from utils import ETHERSCAN_API_KEY def get_ABI(contract_address): diff --git a/integrations/opensea.py b/integrations/opensea.py index 8238f876..d1bea6ae 100644 --- a/integrations/opensea.py +++ b/integrations/opensea.py @@ -1,8 +1,10 @@ from dataclasses import dataclass from typing import Any, Dict, List, Optional, Union -from urllib.parse import urlencode import requests +from web3 import Web3 + +from urllib.parse import urlencode from gpt_index.utils import ErrorToRetry, retry_on_exceptions_with_backoff import utils @@ -101,7 +103,7 @@ def _exec_request(): for item in obj['orders']: price_value = int(item["current_price"]) currency = "ETH" - price_str = f"{utils.w3.from_wei(price_value, 'ether')} {currency}" + price_str = f"{Web3.from_wei(price_value, 'ether')} {currency}" listing = NFTListing( chain=chain, address=address, @@ -154,7 +156,7 @@ def _exec_request(): currency = current_price["currency"] price_value = int(current_price['value']) if currency == "eth": - price_str = f"{utils.w3.from_wei(price_value, 'ether')} {currency}" + price_str = f"{Web3.from_wei(price_value, 'ether')} {currency}" else: price_str = f"{price_value / 10 ** current_price['decimals']} {currency}" listing = NFTListing( diff --git a/tools/index_widget.py b/tools/index_widget.py index 9e3ab922..d2bc86e6 100644 --- a/tools/index_widget.py +++ b/tools/index_widget.py @@ -10,6 +10,7 @@ from langchain.prompts import PromptTemplate from langchain.chains import LLMChain from langchain.prompts.base import BaseOutputParser +from ens import ENS import ui_workflows import config @@ -559,7 +560,9 @@ def fetch_yields(token, network, count) -> str: def ens_from_address(address) -> str: try: - domain = utils.ns.name(address) + web3 = context.get_web3_provider() + ns = ENS.from_web3(web3) + domain = ns.name(address) if domain is None: return f"No ENS domain for {address}" else: @@ -573,7 +576,9 @@ def ens_from_address(address) -> str: def address_from_ens(domain) -> str: try: - address = utils.ns.address(domain) + web3 = context.get_web3_provider() + ns = ENS.from_web3(web3) + address = ns.address(domain) if address is None: return f"No address for {domain}" else: diff --git a/utils/common.py b/utils/common.py index 2e1ed194..d08988d9 100644 --- a/utils/common.py +++ b/utils/common.py @@ -124,10 +124,7 @@ def set_api_key(): OpenAI.api_key = OPENAI_API_KEY -w3 = Web3(Web3.HTTPProvider(TENDERLY_FORK_URL)) tokenizer = tiktoken.encoding_for_model("text-davinci-003") -ns = ENS.from_web3(w3) - def estimate_gas(tx): if USE_CLIENT_TO_ESTIMATE_GAS: @@ -200,7 +197,11 @@ def wrapped_fn(*args, **kwargs): def get_real_user_info(user_info: dict) -> dict: try: user_info["Wallet Address"] = context.get_wallet_address() + + web3 = context.get_web3_provider() + ns = ENS.from_web3(web3) user_info["ENS Domain"] = ns.name(user_info["Wallet Address"]) + chain_id = context.get_wallet_chain_id() if chain_id in CHAIN_ID_TO_NETWORK_NAME: user_info["Network"] = CHAIN_ID_TO_NETWORK_NAME[chain_id] return user_info diff --git a/utils/constants.py b/utils/constants.py index 4fc1db93..cd74a884 100644 --- a/utils/constants.py +++ b/utils/constants.py @@ -64,6 +64,6 @@ def get_widget_index_name(): ### Network/Chain ### ETH_MAINNET_CHAIN_ID = 1 -ETH_MAINNET_RPC_URL = f"https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}" +ETH_MAINNET_RPC_URL = f"https://eth-mainnet.g.alchemy.com/v2/{ALCHEMY_API_KEY}" CHAIN_ID_TO_NETWORK_NAME = {ETH_MAINNET_CHAIN_ID: "ethereum-mainnet"} From 7da9a812dbd7f11065541305fa66c71d267d0231 Mon Sep 17 00:00:00 2001 From: Kah Keng Tay Date: Mon, 21 Aug 2023 12:58:02 -0700 Subject: [PATCH 13/24] integrations: optimize nft search --- integrations/center.py | 33 ++++++++++++++------------------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/integrations/center.py b/integrations/center.py index 96e8da32..c7f1ad74 100644 --- a/integrations/center.py +++ b/integrations/center.py @@ -241,9 +241,10 @@ def _is_valid_collection(collection: NFTCollection) -> bool: if not collection_traits.traits: return False # should have listed and valid assets - assets_for_sale = list(fetch_nft_collection_assets_for_sale(collection.network, collection.address, _skip_timing=True)) - if not assets_for_sale: - return False + if collection.network == "ethereum-mainnet": + token_prices = opensea.fetch_contract_listing_prices_with_retries(collection.address) + if not token_prices: + return False return True @@ -393,11 +394,8 @@ def fetch_nft_collection_assets(network: str, address: str) -> NFTCollectionAsse ) -def fetch_nft_collection_assets_for_sale(network: str, address: str, _skip_timing: bool = False) -> Generator[NFTAsset, None, None]: - # we set _skip_timing=True if we are using this as an internal helper, to avoid cluttering - # logs with irrelevant events - if not _skip_timing: - timing.log('search_begin') +def fetch_nft_collection_assets_for_sale(network: str, address: str) -> Generator[NFTAsset, None, None]: + timing.log('search_begin') collection = fetch_nft_collection(network, address) if collection.network == "ethereum-mainnet": token_prices = opensea.fetch_contract_listing_prices_with_retries(address) @@ -425,8 +423,7 @@ def fetch_nft_collection_assets_for_sale(network: str, address: str, _skip_timin except Exception: traceback.print_exc() break - if not _skip_timing: - timing.log('search_done') + timing.log('search_done') obj = response.json() for item in obj: if not item: @@ -449,14 +446,12 @@ def fetch_nft_collection_assets_for_sale(network: str, address: str, _skip_timin if not _is_valid_asset(asset): continue yield asset - if not _skip_timing: - timing.log('first_result_done') + timing.log('first_result_done') count += 1 if count >= MAX_RESULTS: break offset += limit - if not _skip_timing: - timing.log('%d_results_done' % count) + timing.log('%d_results_done' % count) def fetch_nft_collection_traits(network: str, address: str) -> NFTCollectionTraits: @@ -595,7 +590,7 @@ def fetch_nfts_owned_by_address_or_domain(network: str, address_or_domain: str) normalized_network = "ethereum-mainnet" else: raise ExecError("Network not supported") - + timing.log('fetch_started') # TODO: Add pagination once we have a UI component such as a Carousel to support it. @@ -617,12 +612,12 @@ def fetch_nfts_owned_by_address_or_domain(network: str, address_or_domain: str) except requests.exceptions.HTTPError as err: print(err) raise FetchError("Invalid address or domain") - + obj = response.json() for item in obj['items']: nft_address = item['address'] nft_token_id = item['tokenID'] - nft_asset = fetch_nft_asset(normalized_network, nft_address, nft_token_id) + nft_asset = fetch_nft_asset(normalized_network, nft_address, nft_token_id) assets.append(nft_asset) # In dev, tester's wallet would only have NFTs on the fork so fallback to fetching from contract on the fork @@ -646,7 +641,7 @@ def fetch_nft_buy(network: str, wallet_address: str, nft_address: str, token_id: is_for_sale=False, asset=nft_asset ) - + nft_asset.price = listing.price_str current_time_sec = int(time.time()) @@ -677,4 +672,4 @@ def _fetch_nft_asset_price_str(network: str, address: str, token_id: str) -> Opt price = price_dict['price_str'] if price_dict else 'unlisted' else: price = None - return price \ No newline at end of file + return price From 658c6f85518f7edaa5bc3db87fc0a2d52595b576 Mon Sep 17 00:00:00 2001 From: Kah Keng Tay Date: Tue, 22 Aug 2023 10:23:46 -0700 Subject: [PATCH 14/24] utils: restore original exception message Will be hidden by default in frontend. --- utils/common.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/common.py b/utils/common.py index d08988d9..fd5fb455 100644 --- a/utils/common.py +++ b/utils/common.py @@ -162,7 +162,7 @@ def wrapped_fn(*args, **kwargs): return str(e) except Exception as e: traceback.print_exc() - return "An error occurred. Please try again." + return f'Got exception evaluating {fn.__name__}(args={args}, kwargs={kwargs}): {e}' @functools.wraps(fn) def wrapped_generator_fn(*args, **kwargs): From 4cadac0802c1bd7b4e56e11ecaba008f7c5d333f Mon Sep 17 00:00:00 2001 From: Kah Keng Tay Date: Tue, 22 Aug 2023 11:03:59 -0700 Subject: [PATCH 15/24] integrations: switch some endpoints to center v2 Note the addresses need to be converted to checksum addresses before passing to OpenSea. --- integrations/center.py | 58 +++++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/integrations/center.py b/integrations/center.py index c7f1ad74..c699197f 100644 --- a/integrations/center.py +++ b/integrations/center.py @@ -5,6 +5,7 @@ from urllib.parse import urlencode import requests +import web3 import env import utils @@ -31,6 +32,8 @@ MAX_RESULTS = 12 PAGE_LIMIT = 12 +MAX_RESULTS_FOR_SEARCH = 12 + MAX_RESULTS_FOR_TRAITS = 100 PAGE_LIMIT_FOR_TRAITS = 100 @@ -39,7 +42,7 @@ class NFTCollection(ContainerMixin): network: str address: str name: str - num_assets: int + num_assets: Optional[int] preview_image_url: str def container_name(self) -> str: @@ -202,13 +205,16 @@ def container_params(self) -> Dict: ) def fetch_nft_search(search_str: str) -> Generator[Union[NFTCollection, NFTAsset], None, None]: + limit = MAX_RESULTS_FOR_SEARCH + offset = 0 q = urlencode(dict( query=search_str, - type='collection', # too noisy otherwise + limit=limit, + offset=offset, )) count = 0 for network in NETWORKS: - url = f"{API_URL}/{network}/search?{q}" + url = f"{API_V2_URL}/{network}/search?{q}" timing.log('search_begin') response = requests.get(url, headers=HEADERS) try: @@ -218,17 +224,24 @@ def fetch_nft_search(search_str: str) -> Generator[Union[NFTCollection, NFTAsset break timing.log('search_done') obj = response.json() - for r in obj['results']: - if not r.get('previewImageUrl'): + for item in obj['items']: + if 'collection' not in item: + continue + collection = item['collection'] + if 'featuredImageURL' not in collection or not collection['featuredImageURL']: + continue + count += 1 # increment pre-filtered count, to determine filtering cost to speed + # v2 endpoint might return a non-checksum address, convert it for compatibility with elsewhere + address = web3.utils.address.to_checksum_address(collection['address']) + result = NFTCollection( + network=network, + address=address, + name=collection['name'], + num_assets=collection['totalSupply'], + preview_image_url=collection['featuredImageURL'], + ) + if not _is_valid_collection(result): continue - count += 1 - network = r['id'].split('/')[0] - if r['type'].lower() == 'collection': - result = fetch_nft_collection(network, r['address']) - if not _is_valid_collection(result): - continue - else: - result = fetch_nft_asset(network, r['address'], r['tokenId']) yield result timing.log('first_result_done') timing.log('%d_results_done' % count) @@ -236,10 +249,6 @@ def fetch_nft_search(search_str: str) -> Generator[Union[NFTCollection, NFTAsset def _is_valid_collection(collection: NFTCollection) -> bool: """Check if this NFT collection is a valid search result.""" - # there should be traits - collection_traits = fetch_nft_collection_traits(collection.network, collection.address) - if not collection_traits.traits: - return False # should have listed and valid assets if collection.network == "ethereum-mainnet": token_prices = opensea.fetch_contract_listing_prices_with_retries(collection.address) @@ -328,16 +337,25 @@ def fetch_nft_search_collection_by_trait(network: str, address: str, trait_name: def fetch_nft_collection(network: str, address: str) -> NFTCollection: - url = f"{API_URL}/{network}/{address}" + url = f"{API_V2_URL}/{network}/{address}/nft/metadata" response = requests.get(url, headers=HEADERS) response.raise_for_status() obj = response.json() + num_assets = obj['totalSupply'] + if num_assets == 0: # seems to return 0 incorrectly + # use the asset endpoint with dummy token + token_id = 1 + url = f"{API_V2_URL}/{network}/{address}/nft/{token_id}/metadata" + response = requests.get(url, headers=HEADERS) + if response.status_code == 200: + token_obj = response.json() + num_assets = token_obj['collection']['totalSupply'] return NFTCollection( network=network, address=address, name=obj['name'], - num_assets=obj['numAssets'], - preview_image_url=obj['smallPreviewImageUrl'], + num_assets=num_assets, + preview_image_url=obj['featuredImageURL'], ) From 85f17392c0618dfed82aeb0a7b909d442f06ed2c Mon Sep 17 00:00:00 2001 From: Kah Keng Tay Date: Tue, 22 Aug 2023 15:00:59 -0700 Subject: [PATCH 16/24] integrations: limit opensea api calls for nft search --- integrations/center.py | 2 +- integrations/opensea.py | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/integrations/center.py b/integrations/center.py index c699197f..027a7bea 100644 --- a/integrations/center.py +++ b/integrations/center.py @@ -251,7 +251,7 @@ def _is_valid_collection(collection: NFTCollection) -> bool: """Check if this NFT collection is a valid search result.""" # should have listed and valid assets if collection.network == "ethereum-mainnet": - token_prices = opensea.fetch_contract_listing_prices_with_retries(collection.address) + token_prices = opensea.fetch_contract_listing_prices_with_retries(collection.address, max_results=1) if not token_prices: return False return True diff --git a/integrations/opensea.py b/integrations/opensea.py index d1bea6ae..a1c65cab 100644 --- a/integrations/opensea.py +++ b/integrations/opensea.py @@ -118,18 +118,18 @@ def _exec_request(): return ret -def fetch_all_listings(address: str) -> List[NFTListing]: +def fetch_all_listings(address: str, max_results: Optional[int] = None) -> List[NFTListing]: """Fetch all listings for a collection.""" # NOTE: a given token ID might have more than one listing contract = fetch_contract(address) slug = contract.slug - limit = PAGE_LIMIT next_cursor = None ret = [] # Arbitary limit to optimize for latency, based on hueristics related to observed number of NFTs listed for blue-chip collections. - max_results = 300 - max_queries = 5 + max_results = 300 if max_results is None else max_results + max_queries = 3 queries = 0 + limit = min(PAGE_LIMIT, max_results) while len(ret) < max_results and queries < max_queries: queries += 1 q = urlencode(dict( @@ -170,7 +170,7 @@ def _exec_request(): next_cursor = obj.get("next") if not next_cursor: break - return ret + return ret[:max_results] def fetch_asset_listing_prices_with_retries(address: str, token_id: str) -> Optional[Dict[str, Union[str, int]]]: @@ -183,8 +183,8 @@ def fetch_asset_listing_with_retries(address: str, token_id: str) -> Optional[NF listings = fetch_listings(address, token_id) return listings[0] if len(listings) > 0 else None -def fetch_contract_listing_prices_with_retries(address: str) -> Dict[str, Dict[str, Union[str, int]]]: - listings = fetch_all_listings(address) +def fetch_contract_listing_prices_with_retries(address: str, max_results: Optional[int] = None) -> Dict[str, Dict[str, Union[str, int]]]: + listings = fetch_all_listings(address, max_results=max_results) ret = {} for listing in listings: if listing.token_id not in ret or ret[listing.token_id].price_value > listing.price_value: From acf03a105c081fb37a89ae27dd23ef2565f1300c Mon Sep 17 00:00:00 2001 From: Sagar Shah Date: Fri, 25 Aug 2023 13:08:57 -0500 Subject: [PATCH 17/24] task: update GH workflow file (#244) --- .../workflows/check-update-widget-index.yaml | 31 +++++++------------ .../workflows/check-widget-translation.yaml | 15 ++++++--- 2 files changed, 22 insertions(+), 24 deletions(-) diff --git a/.github/workflows/check-update-widget-index.yaml b/.github/workflows/check-update-widget-index.yaml index 4925c211..d75cd8b1 100644 --- a/.github/workflows/check-update-widget-index.yaml +++ b/.github/workflows/check-update-widget-index.yaml @@ -27,6 +27,13 @@ jobs: with: path: backend + - name: Extract branch name + run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})" + id: extract_branch + + - name: Show branch name + run: echo "Branch name is ${{ steps.extract_branch.outputs.branch }}" + - id: 'auth' uses: 'google-github-actions/auth@v1' with: @@ -58,25 +65,9 @@ jobs: echo "SERVER_HOST=" >> "$GITHUB_ENV" echo "SERVER_ORIGINS=" >> "$GITHUB_ENV" echo "SERVER_SECRET_KEY=" >> "$GITHUB_ENV" - - if [[ ${GITHUB_BASE_REF:-${GITHUB_REF#refs/heads/}} == 'master' ]]; then - echo "ENV_TAG=prod" >> "$GITHUB_ENV" - else - echo "ENV_TAG=dev" >> "$GITHUB_ENV" - echo "WEAVIATE_URL=${{ secrets.DEV_WEAVIATE_URL }}" >> "$GITHUB_ENV" - echo "WEAVIATE_API_KEY=" >> "$GITHUB_ENV" - echo "CHATDB_URL=${{ secrets.DEV_CHATDB_URL }}" >> "$GITHUB_ENV" - fi - - - name: Set environment for branch - run: | - echo "SERVER_HOST=" >> "$GITHUB_ENV" - echo "SERVER_ORIGINS=" >> "$GITHUB_ENV" - echo "SERVER_SECRET_KEY=" >> "$GITHUB_ENV" - echo "CHATDB_URL=" >> "$GITHUB_ENV" echo "WEAVIATE_URL=${{ secrets.WEAVIATE_URL }}" >> "$GITHUB_ENV" - if [[ ${GITHUB_BASE_REF:-${GITHUB_REF#refs/heads/}} == 'master' ]]; then + if [[ ${{ steps.extract_branch.outputs.branch }} == 'master' ]]; then echo "ENV_TAG=prod" >> "$GITHUB_ENV" echo "WEAVIATE_API_KEY=${{ secrets.PROD_WEAVIATE_API_KEY }}" >> "$GITHUB_ENV" echo "CHATDB_URL=${{ secrets.PROD_CHATDB_URL }}" >> "$GITHUB_ENV" @@ -91,10 +82,10 @@ jobs: - name: Check and update widget index run: | GCP_SSH_CMD="gcloud compute ssh cacti-bastion-server --zone us-east1-b --ssh-key-file /tmp/gcp/google_compute_engine --quiet --tunnel-through-iap --ssh-flag" - if [[ ${GITHUB_BASE_REF:-${GITHUB_REF#refs/heads/}} == 'master' ]]; then - $GCP_SSH_CMD '-vvv -fN -L 8080:${{ secrets.PROD_WEAVIATE_INTERNAL_IP }}' + if [[ ${{ steps.extract_branch.outputs.branch }} == 'master' ]]; then + $GCP_SSH_CMD '-fN -L 8080:${{ secrets.PROD_WEAVIATE_INTERNAL_IP }}' else - $GCP_SSH_CMD '-vvv -fN -L 8080:${{ secrets.DEV_WEAVIATE_INTERNAL_IP }}' + $GCP_SSH_CMD '-fN -L 8080:${{ secrets.DEV_WEAVIATE_INTERNAL_IP }}' fi cd backend diff --git a/.github/workflows/check-widget-translation.yaml b/.github/workflows/check-widget-translation.yaml index 95b3133f..cbdbb115 100644 --- a/.github/workflows/check-widget-translation.yaml +++ b/.github/workflows/check-widget-translation.yaml @@ -29,6 +29,13 @@ jobs: with: path: backend + - name: Extract branch name + run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})" + id: extract_branch + + - name: Show branch name + run: echo "Branch name is ${{ steps.extract_branch.outputs.branch }}" + - id: 'auth' uses: 'google-github-actions/auth@v1' with: @@ -63,7 +70,7 @@ jobs: echo "CHATDB_URL=" >> "$GITHUB_ENV" echo "WEAVIATE_URL=${{ secrets.WEAVIATE_URL }}" >> "$GITHUB_ENV" - if [[ ${GITHUB_BASE_REF:-${GITHUB_REF#refs/heads/}} == 'master' ]]; then + if [[ ${{ steps.extract_branch.outputs.branch }} == 'master' ]]; then echo "ENV_TAG=prod" >> "$GITHUB_ENV" echo "WEAVIATE_API_KEY=${{ secrets.PROD_WEAVIATE_API_KEY }}" >> "$GITHUB_ENV" echo "CHATDB_URL=${{ secrets.PROD_CHATDB_URL }}" >> "$GITHUB_ENV" @@ -76,10 +83,10 @@ jobs: - name: Check widget translation run: | GCP_SSH_CMD="gcloud compute ssh cacti-bastion-server --zone us-east1-b --ssh-key-file /tmp/gcp/google_compute_engine --quiet --tunnel-through-iap --ssh-flag" - if [[ ${GITHUB_BASE_REF:-${GITHUB_REF#refs/heads/}} == 'master' ]]; then - $GCP_SSH_CMD '-vvv -fN -L 8080:${{ secrets.PROD_WEAVIATE_INTERNAL_IP }}' + if [[ ${{ steps.extract_branch.outputs.branch }} == 'master' ]]; then + $GCP_SSH_CMD '-fN -L 8080:${{ secrets.PROD_WEAVIATE_INTERNAL_IP }}' else - $GCP_SSH_CMD '-vvv -fN -L 8080:${{ secrets.DEV_WEAVIATE_INTERNAL_IP }}' + $GCP_SSH_CMD '-fN -L 8080:${{ secrets.DEV_WEAVIATE_INTERNAL_IP }}' fi cd backend From 6ce29ea6fc47466b20990f15dcc42a5758244864 Mon Sep 17 00:00:00 2001 From: Sagar Shah Date: Fri, 25 Aug 2023 17:50:30 -0500 Subject: [PATCH 18/24] task: change GH workflow trigger for widget index (#246) --- .github/workflows/check-update-widget-index.yaml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/check-update-widget-index.yaml b/.github/workflows/check-update-widget-index.yaml index d75cd8b1..8bfc4a91 100644 --- a/.github/workflows/check-update-widget-index.yaml +++ b/.github/workflows/check-update-widget-index.yaml @@ -1,9 +1,7 @@ name: Check and update widget index on: - workflow_run: - workflows: [Check widget translation] - types: [completed] + push: branches: [master, dev] jobs: From 11ec2a651587689d368d590f6340e23069973f12 Mon Sep 17 00:00:00 2001 From: Sagar Shah Date: Fri, 25 Aug 2023 18:32:24 -0500 Subject: [PATCH 19/24] fix: GH workflow for updating widget index (#247) --- .github/workflows/check-update-widget-index.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/check-update-widget-index.yaml b/.github/workflows/check-update-widget-index.yaml index 8bfc4a91..497c9331 100644 --- a/.github/workflows/check-update-widget-index.yaml +++ b/.github/workflows/check-update-widget-index.yaml @@ -8,7 +8,6 @@ jobs: main: name: Check and update widget index runs-on: ${{ matrix.os }} - if: ${{ github.event.workflow_run.conclusion == 'success' }} timeout-minutes: 15 strategy: fail-fast: false From 4edb0ee635dcbf451975f7ad282bdc2bf2f2ccde Mon Sep 17 00:00:00 2001 From: Bruce Donovan Date: Thu, 31 Aug 2023 11:29:30 +0100 Subject: [PATCH 20/24] update fetch_contract to opensea V2 (#248) --- integrations/opensea.py | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/integrations/opensea.py b/integrations/opensea.py index a1c65cab..214f1efa 100644 --- a/integrations/opensea.py +++ b/integrations/opensea.py @@ -31,8 +31,6 @@ class NFTContract: chain: str address: str slug: str - name: str - image_url: str # this is a listing of an NFT asset @@ -56,7 +54,7 @@ class NFTFulfillmentData: def fetch_contract(address: str) -> NFTContract: """Fetch data about a contract (collection).""" - url = f"{API_V1_URL}/asset_contract/{address}" + url = f"{API_V2_URL}/chain/ethereum/contract/{address}/nfts" def _exec_request(): response = requests.get(url, headers=HEADERS) @@ -67,16 +65,12 @@ def _exec_request(): _exec_request, [ErrorToRetry(requests.exceptions.HTTPError, _should_retry_exception)], ) - collection = obj["collection"] return NFTContract( - chain=obj["chain_identifier"], + chain='ethereum', address=address, - slug=collection["slug"], - name=collection["name"], - image_url=collection["image_url"], + slug=obj["nfts"][0]["collection"], ) - def fetch_listings(address: str, token_id: str) -> List[NFTListing]: """Fetch cheapest listing for an asset.""" chain = "ethereum" From 61b02b19afb474a59ff5fff304d3ab046447bf7c Mon Sep 17 00:00:00 2001 From: marcomariscal <42938673+marcomariscal@users.noreply.github.com> Date: Thu, 14 Sep 2023 08:32:47 -0700 Subject: [PATCH 21/24] integration: hop protocol (#252) * feat: hop protocol * fix: formatting * fix: try again * feat: update widget index num --- chat/display_widgets.py | 3 +++ knowledge_base/widgets.yaml | 23 +++++++++++++++++++++++ utils/constants.py | 2 +- 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/chat/display_widgets.py b/chat/display_widgets.py index 06fa7ddd..977ceae8 100644 --- a/chat/display_widgets.py +++ b/chat/display_widgets.py @@ -171,6 +171,9 @@ def _widgetize_inner(command: str, params: str, depth: int = 0) -> str: elif command == 'yield-protocol-borrow-close': items = params.split(",") lines.append(f"yield protocol borrow close action: {items[0]}") + elif command == 'hop-protocol-bridge': + items = params.split(",") + lines.append(f"hop protocol bridge action for amount: {items[0]}, token symbol: {items[1]}, from chain: {items[2]}, to chain: {items[3]}.") else: # assert 0, f'unrecognized command: {command}({params})' lines.append(f"An unrecognized command: {command}({params})") diff --git a/knowledge_base/widgets.yaml b/knowledge_base/widgets.yaml index 5bf628f3..53b2773e 100644 --- a/knowledge_base/widgets.yaml +++ b/knowledge_base/widgets.yaml @@ -698,3 +698,26 @@ - borrowToken type: object return_value_description: "" +- _name_: display_hop_protocol_bridge + description: use the hop protocol to bridge/deposit tokens from a supported chain to a different supported chain + parameters: + properties: + amount: + description: token amount + type: string + tokenSymbol: + description: token symbol + type: string + fromChain: + description: chain to bridge from + type: string + toChain: + description: chain to bridge to + type: string + required: + - amount + - tokenSymbol + - fromChain + - toChain + type: object + return_value_description: "" \ No newline at end of file diff --git a/utils/constants.py b/utils/constants.py index cd74a884..61566777 100644 --- a/utils/constants.py +++ b/utils/constants.py @@ -53,7 +53,7 @@ WIDGET_INFO_TOKEN_LIMIT = 4000 # Widget Index -WIDGET_INDEX_NAME = "WidgetV20" +WIDGET_INDEX_NAME = "WidgetV21" def get_widget_index_name(): if env.is_local(): From e16cc4ffc26dff60ff7e80c2bf12690b2669d12e Mon Sep 17 00:00:00 2001 From: marcomariscal <42938673+marcomariscal@users.noreply.github.com> Date: Thu, 14 Sep 2023 08:48:22 -0700 Subject: [PATCH 22/24] integration: tx replay (#249) --- chat/display_widgets.py | 3 +++ knowledge_base/widgets.yaml | 11 +++++++++++ utils/constants.py | 2 +- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/chat/display_widgets.py b/chat/display_widgets.py index 977ceae8..67fdc5fe 100644 --- a/chat/display_widgets.py +++ b/chat/display_widgets.py @@ -174,6 +174,9 @@ def _widgetize_inner(command: str, params: str, depth: int = 0) -> str: elif command == 'hop-protocol-bridge': items = params.split(",") lines.append(f"hop protocol bridge action for amount: {items[0]}, token symbol: {items[1]}, from chain: {items[2]}, to chain: {items[3]}.") + elif command == 'tx-replay': + items = params.split(",") + lines.append(f"replay transaction with tx hash: {items[0]}") else: # assert 0, f'unrecognized command: {command}({params})' lines.append(f"An unrecognized command: {command}({params})") diff --git a/knowledge_base/widgets.yaml b/knowledge_base/widgets.yaml index 53b2773e..afeb6c90 100644 --- a/knowledge_base/widgets.yaml +++ b/knowledge_base/widgets.yaml @@ -720,4 +720,15 @@ - fromChain - toChain type: object + return_value_description: "" +- _name_: display_tx_replay + description: replay a transaction with the same parameters + parameters: + properties: + txHash: + description: the transaction with tx hash to replay + type: string + required: + - txHash + type: object return_value_description: "" \ No newline at end of file diff --git a/utils/constants.py b/utils/constants.py index 61566777..20bfb489 100644 --- a/utils/constants.py +++ b/utils/constants.py @@ -53,7 +53,7 @@ WIDGET_INFO_TOKEN_LIMIT = 4000 # Widget Index -WIDGET_INDEX_NAME = "WidgetV21" +WIDGET_INDEX_NAME = "WidgetV22" def get_widget_index_name(): if env.is_local(): From 5181d491d927c0b361140f72abf888302b571a29 Mon Sep 17 00:00:00 2001 From: Bruce Donovan Date: Mon, 18 Sep 2023 09:23:41 +0100 Subject: [PATCH 23/24] Use center V2 for assets (#243) * use center V2 for assets * task: update GH workflow file (#244) * task: change GH workflow trigger for widget index (#246) * fix: GH workflow for updating widget index (#247) * new preview image + nft images * use center V2 for assets * new preview image + nft images * render images from center * chcekuser * imageUrl add --------- Co-authored-by: Sagar Shah --- integrations/__init__.py | 0 integrations/center.py | 54 ++++++++++++++++++++++++++++------------ main.py | 7 +++++- 3 files changed, 44 insertions(+), 17 deletions(-) create mode 100644 integrations/__init__.py diff --git a/integrations/__init__.py b/integrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/integrations/center.py b/integrations/center.py index 027a7bea..a5e9e2ed 100644 --- a/integrations/center.py +++ b/integrations/center.py @@ -7,8 +7,11 @@ import requests import web3 +from fastapi.responses import Response + import env import utils +import auth from utils import ETH_MAINNET_CHAIN_ID, nft, FetchError, ExecError import utils.timing as timing @@ -26,8 +29,7 @@ #"polygon-mainnet", ] -API_URL = "https://api.center.dev/v1" -API_V2_URL = "https://api.center.dev/v2" +API_URL = "https://api.center.dev" MAX_RESULTS = 12 PAGE_LIMIT = 12 @@ -126,6 +128,7 @@ class NFTAsset(ContainerMixin): preview_image_url: str description: str = '' price: Optional[str] = None + attributes: Optional[ List ] = None def container_name(self) -> str: return 'display-nft-asset-container' @@ -214,7 +217,7 @@ def fetch_nft_search(search_str: str) -> Generator[Union[NFTCollection, NFTAsset )) count = 0 for network in NETWORKS: - url = f"{API_V2_URL}/{network}/search?{q}" + url = f"{API_URL}/v2/{network}/search?{q}" timing.log('search_begin') response = requests.get(url, headers=HEADERS) try: @@ -295,7 +298,7 @@ def fetch_nft_search_collection_by_trait(network: str, address: str, trait_name: limit=limit, offset=offset, )) - url = f"{API_URL}/{network}/{address}/assets/searchByTraits?{q}" + url = f"{API_URL}/v1/{network}/{address}/assets/searchByTraits?{q}" response = requests.post(url, headers=headers, json=payload) try: response.raise_for_status() @@ -337,7 +340,7 @@ def fetch_nft_search_collection_by_trait(network: str, address: str, trait_name: def fetch_nft_collection(network: str, address: str) -> NFTCollection: - url = f"{API_V2_URL}/{network}/{address}/nft/metadata" + url = f"{API_URL}/v2/{network}/{address}/nft/metadata" response = requests.get(url, headers=HEADERS) response.raise_for_status() obj = response.json() @@ -345,7 +348,7 @@ def fetch_nft_collection(network: str, address: str) -> NFTCollection: if num_assets == 0: # seems to return 0 incorrectly # use the asset endpoint with dummy token token_id = 1 - url = f"{API_V2_URL}/{network}/{address}/nft/{token_id}/metadata" + url = f"{API_URL}/v2/{network}/{address}/nft/{token_id}/metadata" response = requests.get(url, headers=HEADERS) if response.status_code == 200: token_obj = response.json() @@ -375,7 +378,7 @@ def fetch_nft_collection_assets(network: str, address: str) -> NFTCollectionAsse {"Address": address, "TokenID": token_id} for token_id in token_ids[offset: offset + limit] ]} - url = f"{API_URL}/{network}/assets" + url = f"{API_URL}/v1/{network}/assets" response = requests.post(url, headers=HEADERS, json=payload) try: response.raise_for_status() @@ -400,6 +403,7 @@ def fetch_nft_collection_assets(network: str, address: str) -> NFTCollectionAsse name=item['name'], preview_image_url=item['mediumPreviewImageUrl'], price=price, + ) if not _is_valid_asset(asset): continue @@ -434,7 +438,7 @@ def fetch_nft_collection_assets_for_sale(network: str, address: str) -> Generato {"Address": address, "TokenID": token_id} for token_id in token_ids[offset: offset + limit] ]} - url = f"{API_URL}/{network}/assets" + url = f"{API_URL}/v1/{network}/assets" response = requests.post(url, headers=HEADERS, json=payload) try: response.raise_for_status() @@ -482,7 +486,7 @@ def fetch_nft_collection_traits(network: str, address: str) -> NFTCollectionTrai limit=limit, offset=offset, )) - url = f"{API_URL}/{network}/{address}/traits?{q}" + url = f"{API_URL}/v1/{network}/{address}/traits?{q}" response = requests.get(url, headers=HEADERS) try: response.raise_for_status() @@ -525,7 +529,7 @@ def fetch_nft_collection_trait_values(network: str, address: str, trait: str) -> limit=limit, offset=offset, )) - url = f"{API_URL}/{network}/{address}/traits/{trait}?{q}" + url = f"{API_URL}/v1/{network}/{address}/traits/{trait}?{q}" response = requests.get(url, headers=HEADERS) try: response.raise_for_status() @@ -557,7 +561,7 @@ def fetch_nft_collection_trait_values(network: str, address: str, trait: str) -> def fetch_nft_asset(network: str, address: str, token_id: str) -> NFTAsset: - url = f"{API_URL}/{network}/{address}/{token_id}" + url = f"{API_URL}/v2/{network}/{address}/nft/{token_id}/metadata" response = requests.get(url, headers=HEADERS) response.raise_for_status() obj = response.json() @@ -565,16 +569,18 @@ def fetch_nft_asset(network: str, address: str, token_id: str) -> NFTAsset: network=network, address=address, token_id=token_id, - collection_name=obj['collectionName'], - name=obj['name'], - preview_image_url=obj['mediumPreviewImageUrl'], + collection_name=obj['collection']['name'], + name=obj['metadata']['name'], + preview_image_url=f"{API_URL}{obj['media']['small']}", + # image_url=f"{API_URL}{obj['media']['medium']}", description=obj['metadata']['description'], + attributes=obj['metadata']['attributes'], ) def fetch_nft_asset_traits(network: str, address: str, token_id: str) -> NFTAssetTraits: price = _fetch_nft_asset_price_str(network, address, token_id) - url = f"{API_URL}/{network}/{address}/{token_id}" + url = f"{API_URL}/v1/{network}/{address}/{token_id}" response = requests.get(url, headers=HEADERS) response.raise_for_status() obj = response.json() @@ -622,7 +628,7 @@ def fetch_nfts_owned_by_address_or_domain(network: str, address_or_domain: str) limit=limit, offset=offset, )) - url = f"{API_V2_URL}/{normalized_network}/{address_or_domain}/nfts-owned?{q}" + url = f"{API_URL}/v2/{normalized_network}/{address_or_domain}/nfts-owned?{q}" try: response = requests.get(url, headers=HEADERS) @@ -691,3 +697,19 @@ def _fetch_nft_asset_price_str(network: str, address: str, token_id: str) -> Opt else: price = None return price + +@auth.authenticate_user_id() +def fetch_center_image(response, network: str, address: str, token_id: str, size: str, user_id:str=None): + + url = f"{API_URL}/v2/{network}/{address}/nft/{token_id}/render/{size}" + resp = requests.get(url, headers=HEADERS) + + # Check if user is authenticated + if not user_id: return None + + # return response.content + if resp.status_code != 200: + # Handle error appropriately, return a message, or another status code + return Response(content="Could not retrieve image", status_code=resp.status_code) + + return Response(content=resp.content) \ No newline at end of file diff --git a/main.py b/main.py index 16a4eb9d..faeb9ee1 100644 --- a/main.py +++ b/main.py @@ -3,9 +3,10 @@ from dataclasses import dataclass from typing import Any, Dict, Optional, Set -from fastapi import FastAPI, Request, Response, Body, WebSocket, WebSocketDisconnect +from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect from fastapi.middleware.cors import CORSMiddleware from starlette.middleware.sessions import SessionMiddleware +from fastapi.responses import StreamingResponse import server import chat @@ -15,6 +16,7 @@ from app import chat as app_chat from app import share as app_share +from integrations import center app = FastAPI() @@ -80,6 +82,9 @@ class ClientState: async def api_nonce(request: Request): return auth.api_nonce(request) +@app.get("/center_image/{network}/{address}/{token_id}/{size}") +async def fetch_nft_image(request: Request, network: str, address: str, token_id: str, size: str): + return center.fetch_center_image(request, network, address, token_id, size) @app.post("/login") async def api_login(request: Request, data: auth.AcceptJSON): From 7ee1d254d7c01aad3992615447643768b91cc670 Mon Sep 17 00:00:00 2001 From: Kah Keng Tay Date: Mon, 18 Sep 2023 08:27:31 -0700 Subject: [PATCH 24/24] server: be more relaxed for db lookups --- server.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.py b/server.py index e977cbed..950917ba 100644 --- a/server.py +++ b/server.py @@ -49,7 +49,7 @@ def _register_system(system_config_id, system_config_json): def _get_default_system_config_id(): # we query the db but return the identifier to store, so that we can still # reference the id even after the session has been closed. - default_system_config = SystemConfig.query.filter_by(json=config.default_config).one_or_none() + default_system_config = SystemConfig.query.filter_by(json=config.default_config).first() if not default_system_config: default_system_config = SystemConfig(json=config.default_config) db_session.add(default_system_config)