### Install py-builder-relayer-client using pip Source: https://github.com/polymarket/py-builder-relayer-client/blob/main/README.md This snippet shows how to install the py-builder-relayer-client library using pip. It is a straightforward installation process requiring only pip. ```bash pip install py-builder-relayer-client ``` -------------------------------- ### Get Transaction Details by ID in Python Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt This Python example illustrates how to query the details of a specific transaction using its unique ID. The 'get_transaction' method of the RelayClient is used, and the snippet iterates through the returned transaction details, printing key information like state, transaction hash, sender, receiver, and data. It includes error handling for cases where the transaction is not found. ```python from py_builder_relayer_client.client import RelayClient import os # Initialize client client = RelayClient( "https://relayer-v2-staging.polymarket.dev/", 80002 ) # Get transaction by ID transaction_id = "019a2e46-3fc9-77d7-9ad7-451288a2a8a6" transactions = client.get_transaction(transaction_id) if transactions: for txn in transactions: print(f"State: {txn.get('state')}") print(f"Transaction Hash: {txn.get('transactionHash')}") print(f"From: {txn.get('from')}") print(f"To: {txn.get('to')}") print(f"Data: {txn.get('data')}") else: print("Transaction not found") ``` -------------------------------- ### Poll Transaction Until State in Python Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt This Python example demonstrates how to poll for a transaction's state until it reaches one of the specified target states (e.g., MINED or CONFIRMED), or until it reaches a fail state. It allows customization of polling frequency and maximum attempts, providing a robust way to monitor transaction progress without blocking indefinitely. ```python from py_builder_relayer_client.client import RelayClient from py_builder_relayer_client.models import RelayerTransactionState import os # Initialize client client = RelayClient( "https://relayer-v2-staging.polymarket.dev/", 80002 ) transaction_id = "019a2e46-3fc9-77d7-9ad7-451288a2a8a6" # Poll until transaction is mined or confirmed result = client.poll_until_state( transaction_id=transaction_id, states=[ RelayerTransactionState.STATE_MINED.value, RelayerTransactionState.STATE_CONFIRMED.value ], fail_state=RelayerTransactionState.STATE_FAILED.value, max_polls=30, # Maximum number of polling attempts poll_frequency=2000 # Poll every 2 seconds (milliseconds) ) if result: print(f"Transaction reached target state: {result.get('state')}") print(f"Transaction Hash: {result.get('transactionHash')}") else: print("Transaction failed or polling timed out") ``` -------------------------------- ### Get Nonce Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt Retrieve the current nonce for a specified signer address and signer type (e.g., 'SAFE' or 'SAFE-CREATE'). This is crucial for ensuring transaction ordering and preventing replay attacks. ```APIDOC ## Get Nonce ### Description Retrieve the current nonce for a signer address. ### Method GET ### Endpoint `/api/v1/nonce` ### Parameters #### Query Parameters - **address** (string) - Required - The signer address for which to retrieve the nonce. - **signerType** (string) - Required - The type of signer, e.g., 'SAFE' or 'SAFE-CREATE'. ### Request Example ``` GET /api/v1/nonce?address=0x6e0c80c90ea6c15917308f820Eac91Ce2724B5b5&signerType=SAFE ``` ### Response #### Success Response (200) - **nonce** (integer) - The current nonce for the given address and signer type. #### Response Example ```json { "nonce": 15 } ``` ``` -------------------------------- ### Get Nonce for Signer Address in Python Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt This Python code retrieves the current nonce for a given signer address using the RelayClient. Nonces are essential for preventing replay attacks and ensuring transactions are processed in the correct order. The snippet shows how to initialize the client and call the 'get_nonce' method, handling potential failures in retrieval. ```python from py_builder_relayer_client.client import RelayClient import os # Initialize client (no authentication needed for read operations) client = RelayClient( "https://relayer-v2-staging.polymarket.dev/", 80002 ) # Get nonce for a signer address address = "0x6e0c80c90ea6c15917308F820Eac91Ce2724B5b5" signer_type = "SAFE" # or "SAFE-CREATE" nonce_payload = client.get_nonce(address, signer_type) if nonce_payload and nonce_payload.get("nonce") is not None: print(f"Current nonce: {nonce_payload['nonce']}") else: print("Failed to retrieve nonce") ``` -------------------------------- ### Get Transaction Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt Query detailed information about a specific transaction using its unique transaction ID. This endpoint allows retrieval of transaction state, hash, sender, recipient, and data. ```APIDOC ## Get Transaction ### Description Query transaction details by transaction ID. ### Method GET ### Endpoint `/api/v1/transaction/{transaction_id}` ### Parameters #### Path Parameters - **transaction_id** (string) - Required - The unique identifier of the transaction. ### Request Example ``` GET /api/v1/transaction/019a2e46-3fc9-77d7-9ad7-451288a2a8a6 ``` ### Response #### Success Response (200) - **transactions** (array) - An array of transaction objects matching the ID. - **state** (string) - The current state of the transaction (e.g., PENDING, MINED, CONFIRMED, FAILED). - **transactionHash** (string) - The hash of the transaction on the blockchain. - **from** (string) - The sender address. - **to** (string) - The recipient address. - **data** (string) - The transaction data payload. #### Response Example ```json [ { "state": "MINED", "transactionHash": "0x...", "from": "0x...", "to": "0x...", "data": "0x..." } ] ``` ``` -------------------------------- ### Initialize RelayClient in Python Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt Initializes the RelayClient for interacting with the Polymarket Relayer. Requires relayer URL, chain ID, private key, and builder credentials. Read-only operations can be performed with only URL and chain ID. Dependencies include `dotenv`, `os`, `py_builder_relayer_client`, and `py_builder_signing_sdk`. ```python from dotenv import load_dotenv import os from py_builder_relayer_client.client import RelayClient from py_builder_signing_sdk.config import BuilderConfig, BuilderApiKeyCreds load_dotenv() # Initialize with full authentication relayer_url = "https://relayer-v2-staging.polymarket.dev/" chain_id = 80002 # Amoy testnet private_key = os.getenv("PK") builder_config = BuilderConfig( local_builder_creds=BuilderApiKeyCreds( key=os.getenv("BUILDER_API_KEY"), secret=os.getenv("BUILDER_SECRET"), passphrase=os.getenv("BUILDER_PASS_PHRASE"), ) ) client = RelayClient(relayer_url, chain_id, private_key, builder_config) # For read-only operations, initialize without credentials client_readonly = RelayClient(relayer_url, chain_id) ``` -------------------------------- ### Configure Environment Variables for Relayer Client Source: https://github.com/polymarket/py-builder-relayer-client/blob/main/README.md This snippet details the necessary environment variables to configure the client for interacting with the Polymarket Relayer infrastructure. These variables include relayer URL, chain ID, and API credentials for the builder. ```env RELAYER_URL=https://relayer-v2-staging.polymarket.dev/ CHAIN_ID=80002 PK=your_private_key_here BUILDER_API_KEY=your_api_key BUILDER_SECRET=your_api_secret BUILDER_PASS_PHRASE=your_passphrase ``` -------------------------------- ### Deploy Safe Wallet using Python SDK Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt Deploys a new Safe smart contract wallet for a given signer address using the RelayClient. It first checks the expected Safe address and whether it's already deployed. If not deployed, it initiates the deployment and waits for the transaction to complete. Dependencies include `py_builder_relayer_client` and `py_builder_signing_sdk`. ```python from py_builder_relayer_client.client import RelayClient from py_builder_signing_sdk.config import BuilderConfig, BuilderApiKeyCreds import os # Initialize client with full credentials client = RelayClient( "https://relayer-v2-staging.polymarket.dev/", 80002, os.getenv("PK"), BuilderConfig( local_builder_creds=BuilderApiKeyCreds( key=os.getenv("BUILDER_API_KEY"), secret=os.getenv("BUILDER_SECRET"), passphrase=os.getenv("BUILDER_PASS_PHRASE"), ) ) ) # Check expected safe address before deployment expected_safe = client.get_expected_safe() print(f"Expected Safe address: {expected_safe}") # Check if already deployed is_deployed = client.get_deployed(expected_safe) if not is_deployed: # Deploy the safe wallet resp = client.deploy() print(f"Transaction ID: {resp.transaction_id}") print(f"Transaction Hash: {resp.transaction_hash}") # Wait for deployment to complete awaited_txn = resp.wait() if awaited_txn: print(f"Safe deployed successfully: {awaited_txn}") else: print("Deployment failed or timed out") else: print("Safe already deployed") ``` -------------------------------- ### Error Handling with RelayerClient Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt This code snippet illustrates comprehensive error handling when using the RelayClient. It includes a try-except block to catch specific exceptions like RelayerClientException for relayer-related issues, ValueError for configuration problems, and a general Exception for any other unexpected errors. ```python from py_builder_relayer_client.client import RelayClient from py_builder_relayer_client.exceptions import RelayerClientException from py_builder_relayer_client.models import SafeTransaction, OperationType from py_builder_signing_sdk.config import BuilderConfig, BuilderApiKeyCreds import os try: # Initialize client client = RelayClient( "https://relayer-v2-staging.polymarket.dev/", 80002, os.getenv("PK"), BuilderConfig( local_builder_creds=BuilderApiKeyCreds( key=os.getenv("BUILDER_API_KEY"), secret=os.getenv("BUILDER_SECRET"), passphrase=os.getenv("BUILDER_PASS_PHRASE"), ) ) ) # Try to execute transaction txn = SafeTransaction( to="0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", operation=OperationType.Call, data="0x", value="0", ) resp = client.execute([txn]) print(f"Success: {resp.transaction_id}") except RelayerClientException as e: # Handle client-specific errors # - "signer is required for this endpoint" # - "builder credentials are required for this endpoint" # - "expected safe {address} is not deployed" # - "safe {address} is already deployed" # - "invalid nonce payload received" # - "could not generate builder headers" print(f"Relayer client error: {e}") except ValueError as e: # Handle invalid configuration (invalid private key or chain_id) print(f"Configuration error: {e}") except Exception as e: # Handle other errors (network issues, etc.) print(f"Unexpected error: {e}") ``` -------------------------------- ### Execute Transaction using RelayClient in Python Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt This Python snippet shows how to initialize the RelayClient with necessary credentials (API keys and private key) and then execute a transaction. It defines a SafeTransaction object with destination, operation type, data, and value, and submits it using the client's 'execute' method. This is a fundamental step for sending signed transactions through the relayer. ```python from py_builder_relayer_client.client import RelayClient from py_builder_relayer_client.models import OperationType, SafeTransaction from py_builder_signing_sdk.config import BuilderConfig, BuilderApiKeyCreds import os # Initialize and execute transaction client = RelayClient( "https://relayer-v2-staging.polymarket.dev/", 80002, os.getenv("PK"), BuilderConfig( local_builder_creds=BuilderApiKeyCreds( key=os.getenv("BUILDER_API_KEY"), secret=os.getenv("BUILDER_SECRET"), passphrase=os.getenv("BUILDER_PASS_PHRASE"), ) ) ) # Execute a transaction txn = SafeTransaction( to="0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", operation=OperationType.Call, data="0x", value="0", ) resp = client.execute([txn]) ``` -------------------------------- ### Check Safe Deployment Status in Python Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt This Python code verifies whether a Safe wallet is deployed at a specified address. It utilizes the 'get_deployed' method of the RelayClient. The output clearly indicates whether the Safe contract exists at the given address, which is useful for conditional logic before interacting with a Safe. ```python from py_builder_relayer_client.client import RelayClient import os # Initialize client client = RelayClient( "https://relayer-v2-staging.polymarket.dev/", 80002 ) # Check if safe is deployed safe_address = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb" is_deployed = client.get_deployed(safe_address) if is_deployed: print(f"Safe at {safe_address} is deployed") else: print(f"Safe at {safe_address} is not deployed") ``` -------------------------------- ### Derive Safe Address in Python Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt This Python snippet shows two methods for deriving the expected Safe wallet address for a given signer. The first method uses the RelayClient, which requires signer information. The second method uses the 'derive' function directly from the 'py_builder_relayer_client.builder.derive' module, requiring the signer address and contract configuration. This is essential for pre-calculating Safe addresses before deployment. ```python from py_builder_relayer_client.client import RelayClient from py_builder_relayer_client.builder.derive import derive from py_builder_relayer_client.config import get_contract_config import os # Method 1: Using client (requires signer) client = RelayClient( "https://relayer-v2-staging.polymarket.dev/", 80002, os.getenv("PK") ) expected_safe = client.get_expected_safe() print(f"Expected Safe address: {expected_safe}") # Method 2: Using derive function directly signer_address = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb" chain_id = 80002 contract_config = get_contract_config(chain_id) safe_address = derive(signer_address, contract_config.safe_factory) print(f"Derived Safe address: {safe_address}") ``` -------------------------------- ### Execute Safe Transactions in Python Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt Executes single or batched transactions through a deployed Safe wallet using the RelayClient. It includes helper functions for encoding transaction data, such as ERC20 approvals. Dependencies include `eth_utils`, `eth_abi`, `py_builder_relayer_client`, and `py_builder_signing_sdk`. ```python from eth_utils import to_checksum_address, keccak from eth_abi import encode from py_builder_relayer_client.client import RelayClient from py_builder_relayer_client.models import OperationType, SafeTransaction from py_builder_signing_sdk.config import BuilderConfig, BuilderApiKeyCreds import os # Helper function to encode function calls def _function_selector(signature: str) -> bytes: """First 4 bytes of Keccak-256 of the function signature.""" return keccak(text=signature)[:4] def encode_approve(spender: str, amount: int) -> str: selector = _function_selector("approve(address,uint256)") encoded_args = encode(["address", "uint256"], [spender, amount]) return "0x" + (selector + encoded_args).hex() # Create transaction def create_usdc_approve_txn(token: str, spender: str): token = to_checksum_address(token) spender = to_checksum_address(spender) # Max uint256 approval max_amount = 115792089237316195423570985008687907853269984665640564039457584007913129639935 data = encode_approve(spender, max_amount) return SafeTransaction( to=token, operation=OperationType.Call, data=data, value="0", ) # Initialize client client = RelayClient( "https://relayer-v2-staging.polymarket.dev/", 80002, os.getenv("PK"), BuilderConfig( local_builder_creds=BuilderApiKeyCreds( key=os.getenv("BUILDER_API_KEY"), secret=os.getenv("BUILDER_SECRET"), passphrase=os.getenv("BUILDER_PASS_PHRASE"), ) ) ) # Create transactions usdc = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174" ctf = "0x4d97dcd97ec945f40cf65f87097ace5ea0476045" txn = create_usdc_approve_txn(usdc, ctf) # Execute batched transactions with metadata resp = client.execute([txn], "approve USDC on CTF") print(f"Transaction ID: {resp.transaction_id}") print(f"Transaction Hash: {resp.transaction_hash}") ``` -------------------------------- ### Check Safe Deployment Status Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt Verify if a Safe wallet has been deployed on the blockchain at a given address. This is useful for checking the existence and readiness of a Safe account. ```APIDOC ## Check Safe Deployment Status ### Description Verify if a Safe wallet is deployed at a given address. ### Method GET ### Endpoint `/api/v1/safe/{safe_address}/deployed` ### Parameters #### Path Parameters - **safe_address** (string) - Required - The address of the Safe wallet to check. ### Request Example ``` GET /api/v1/safe/0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb/deployed ``` ### Response #### Success Response (200) - **isDeployed** (boolean) - True if the Safe is deployed, false otherwise. #### Response Example ```json { "isDeployed": true } ``` ``` -------------------------------- ### Wait for Transaction Confirmation in Python Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt This snippet demonstrates how to wait for a transaction to be confirmed after it has been initiated. It checks the response from the 'wait()' method and prints a success or failure message based on the confirmation status. This is crucial for ensuring that a transaction has been successfully processed by the network. ```python awaited_txn = resp.wait() if awaited_txn: print(f"Transaction completed: {awaited_txn}") else: print("Transaction failed or timed out") ``` -------------------------------- ### Accessing Transaction Response Properties Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt This snippet demonstrates how to access various properties of a transaction response object, including the transaction ID, transaction hash, and hash alias. It also shows how to retrieve the current transaction details and wait for the transaction to complete, checking its final state. ```python print(f"Transaction ID: {resp.transaction_id}") print(f"Transaction Hash: {resp.transaction_hash}") print(f"Hash alias: {resp.hash}") # Same as transaction_hash # Get current transaction details current_txn = resp.get_transaction() print(f"Current transaction state: {current_txn}") # Wait for completion (blocks until STATE_MINED or STATE_CONFIRMED) final_txn = resp.wait() if final_txn: print(f"Final state: {final_txn.get('state')}") else: print("Transaction failed") ``` -------------------------------- ### Derive Safe Address Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt Calculate the expected blockchain address for a Safe wallet based on its factory contract and creation parameters. This can be done using the client or the standalone derive function. ```APIDOC ## Derive Safe Address ### Description Calculate the expected Safe wallet address for a signer. ### Method POST ### Endpoint `/api/v1/safe/derive` ### Parameters #### Request Body - **signerAddress** (string) - Required - The address of the signer. - **saltNonce** (integer) - Optional - The salt nonce used for deriving the address (defaults to 0 if not provided). ### Request Example ```json { "signerAddress": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", "saltNonce": 1 } ``` ### Response #### Success Response (200) - **safeAddress** (string) - The derived Safe wallet address. #### Response Example ```json { "safeAddress": "0x..." } ``` ``` -------------------------------- ### Execute Transaction Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt Submit a transaction to be executed by the relayer service. This endpoint is used for sending standard blockchain operations. ```APIDOC ## Execute Transaction ### Description Submit a transaction for execution by the relayer service. ### Method POST ### Endpoint `/api/v1/transaction` ### Parameters #### Request Body - **transactions** (array of objects) - Required - An array containing one or more transaction objects to execute. - **to** (string) - Required - The recipient address of the transaction. - **operation** (string) - Required - The type of operation (e.g., 'CALL', 'DELEGATE_CALL'). - **data** (string) - Optional - The data payload for the transaction. - **value** (string) - Optional - The value to send with the transaction (in wei). ### Request Example ```json { "transactions": [ { "to": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", "operation": "CALL", "data": "0x", "value": "0" } ] } ``` ### Response #### Success Response (200) - **resp** (object) - The response object containing transaction details. - **wait()** (method) - A method to wait for the transaction to be confirmed. #### Response Example ```python # Example of using the response object resp = client.execute([txn]) awaited_txn = resp.wait() if awaited_txn: print(f"Transaction completed: {awaited_txn}") else: print("Transaction failed or timed out") ``` ``` -------------------------------- ### Poll Transaction Until State Source: https://context7.com/polymarket/py-builder-relayer-client/llms.txt Continuously monitor a transaction's progress until it reaches one of the specified target states or a failure state. Allows customization of polling frequency and limits. ```APIDOC ## Poll Transaction Until State ### Description Wait for a transaction to reach a specific state with custom polling configuration. ### Method GET ### Endpoint `/api/v1/transaction/{transaction_id}/poll` ### Parameters #### Path Parameters - **transaction_id** (string) - Required - The unique identifier of the transaction to poll. #### Query Parameters - **states** (array of strings) - Required - An array of target transaction states (e.g., `["MINED", "CONFIRMED"]`). - **fail_state** (string) - Required - The transaction state that should be considered a failure (e.g., `"FAILED"`). - **max_polls** (integer) - Optional - The maximum number of polling attempts (defaults to 30). - **poll_frequency** (integer) - Optional - The frequency of polling in milliseconds (defaults to 2000). ### Request Example ``` GET /api/v1/transaction/019a2e46-3fc9-77d7-9ad7-451288a2a8a6/poll?states=MINED&states=CONFIRMED&fail_state=FAILED&max_polls=60&poll_frequency=3000 ``` ### Response #### Success Response (200) - **result** (object) - The transaction object once it reaches a target or failure state. - **state** (string) - The final state of the transaction. - **transactionHash** (string) - The transaction hash if the state is MINED or confirmed. #### Response Example ```json { "state": "CONFIRMED", "transactionHash": "0x..." } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.