#!/usr/bin/env python3 """Buy a NeuraLiquid signal pass with an explicit budget, or preview its offer.""" import argparse import asyncio import json import os import re import tempfile import time import uuid from decimal import Decimal from pathlib import Path from urllib.parse import urljoin, urlsplit import httpx from eth_account import Account from eth_account.messages import encode_defunct from x402 import x402Client from x402.http.utils import decode_payment_required_header, encode_payment_signature_header from x402.mechanisms.evm.exact import ExactEvmClientScheme from x402.mechanisms.evm.signers import EthAccountSigner DEFAULT_URL = 'https://futurecast.ml85.xyz/api/v1/x402/signals/patterns' DEFAULT_RECIPIENT = '0xb779aF773aCfe6306070bf0b2faBBE2AB0b100F6' USDC = { 'eip155:8453': '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', 'eip155:84532': '0x036CbD53842c5426634e7929541eC2318f3dCF7e', } def write_private(fd, value): with os.fdopen(fd, 'w') as stream: json.dump(value, stream) stream.flush() os.fsync(stream.fileno()) def create_private(path, value): write_private(os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600), value) def save_private(path, value): fd, temporary = tempfile.mkstemp(prefix=path.name + '.', dir=path.parent) try: write_private(fd, value) os.replace(temporary, path) finally: if os.path.exists(temporary): os.unlink(temporary) def origin(url): location = urlsplit(url) if location.scheme != 'https' or not location.hostname or location.username is not None or location.password is not None: raise ValueError('A HTTPS URL without user information is required') return 'https://' + location.netloc def status_url(base, path): location = urljoin(base, path) if origin(location) != origin(base): raise ValueError('Unexpected payment status origin') return location def load_account(path): if path.stat().st_mode & 0o077: raise ValueError('Private key file must have permission 600') return Account.from_key(path.read_text().strip()) async def offer(http, url): response = await http.get(url) if response.status_code != 402: raise RuntimeError(f'Expected 402, received {response.status_code}') required = decode_payment_required_header(response.headers['PAYMENT-REQUIRED']) if len(required.accepts) != 1: raise ValueError('Expected one explicit payment option') terms = required.accepts[0] if terms.network not in USDC or terms.scheme != 'exact' or terms.asset.lower() != USDC[terms.network].lower(): raise ValueError('Unsupported token, scheme or network') return required async def purchase(http, args, account): if args.access_file.exists(): raise ValueError('Access file already exists. Use --resume to recover your purchase.') required = await offer(http, args.url) terms = required.accepts[0] if terms.network == 'eip155:8453' and not args.allow_mainnet: raise ValueError('Mainnet requires --allow-mainnet') if args.register_referral and terms.network != 'eip155:8453': raise ValueError('Referral registration requires Base mainnet') if terms.pay_to.lower() != args.recipient.lower(): raise ValueError('Recipient mismatch') if Decimal(terms.amount) / 1_000_000 > args.max_usdc: raise ValueError('Price exceeds authorized budget') client = x402Client() client.set_spend_controls({'max_amount_per_payment': str(args.max_usdc)}) client.register(terms.network, ExactEvmClientScheme(EthAccountSigner(account))) authorization = encode_payment_signature_header(await client.create_payment_payload(required)) # Persist this authorization before the first network send. An uncertain reply # can be recovered with the same nonce and exact signature after a restart. create_private(args.access_file, {'payment_signature': authorization, 'url': args.url}) return await http.get(args.url, headers={'PAYMENT-SIGNATURE': authorization}) async def resume(http, args): saved = json.loads(args.access_file.read_text()) if 'payment_signature' in saved: if saved['url'] != args.url: raise ValueError('Resume URL mismatch. Use the original URL including its referral code.') return await http.get(args.url, headers={'PAYMENT-SIGNATURE': saved['payment_signature']}) return await http.get(status_url(args.url, saved['status_url']), headers={'Authorization': 'Bearer ' + saved['access_token']}) def checked_challenge(base, wallet, challenge): # Only sign the agreed registration statement. A generic message returned # by an arbitrary seller must never become an arbitrary signing capability. challenge_id = str(uuid.UUID(challenge['id'])) expires = challenge['expires_at'] if not isinstance(expires, int) or not time.time() < expires <= time.time() + 660: raise ValueError('Invalid registration challenge expiry') statement = 'Bind this wallet to a new direct-referral code. Commission: 34% of eligible confirmed Base USDC payments.' if 'recover_code' in challenge: code = challenge['recover_code'] public_links(base, code) # Validate the code before inserting it in a signing prompt. statement = f'Recover direct-referral code {code} and replace its private rewards token.' message = (f'FutureCast referral wallet registration\nOrigin: {base}\nChain: 8453\nWallet: {wallet}\n' f'Challenge: {challenge_id}\nExpires: {expires}\n{statement} ' 'No payment or token approval authorized by this signature.') if challenge.get('signature_method') != 'personal_sign' or challenge.get('message') != message: raise ValueError('Unexpected wallet registration message') return message def public_links(base, code): if not isinstance(code, str) or not re.fullmatch(r'[A-Za-z0-9_-]{1,24}', code): raise ValueError('Invalid referral code') return {'url': f'{base}/?ref={code}', 'x402_url': f'{base}/api/v1/x402/signals/patterns?ref={code}'} async def register_referral(http, base, account, file): pending = file.exists() request = {'wallet': account.address} recovery_kind = None if pending: saved = json.loads(file.read_text()) if saved.get('origin') != base or saved.get('wallet') != account.address: raise ValueError('Rewards file belongs to a different wallet or origin') if saved.get('access_token'): return public_links(base, saved['code']) if saved.get('launch_partner'): recovery_kind = 'launch_partner' request['recover_partner'] = True elif saved.get('referral_campaign'): recovery_kind = 'referral_campaign' request['recover_campaign'] = True else: raise RuntimeError('Registration outcome uncertain. Inspect the existing rewards file before attempting a new registration.') endpoint = base + '/api/v1/referrals/' response = await http.post(endpoint + 'wallet-challenges', json=request) response.raise_for_status() challenge = response.json() if recovery_kind and challenge.get(recovery_kind) is not True: raise ValueError('Expected the original referral registration program') message = checked_challenge(base, account.address, challenge) signature = account.sign_message(encode_defunct(text=message)).signature state = {'origin': base, 'wallet': account.address, 'challenge_id': challenge['id']} for program in ('launch_partner', 'referral_campaign'): if challenge.get(program) is True: state[program] = True if pending: save_private(file, state) else: create_private(file, state) response = await http.post(endpoint + 'register', json={'challenge_id': challenge['id'], 'signature': '0x' + bytes(signature).hex()}) response.raise_for_status() registration = response.json() code = registration['code'] links = public_links(base, code) if (challenge.get('recover_code', code) != code or registration.get('wallet') != account.address or not registration.get('access_token') or any(registration.get(field) != url for field, url in links.items())): raise ValueError('Unexpected referral registration response') save_private(file, {**state, 'code': code, 'access_token': registration['access_token'], 'rewards_url': f'{endpoint}{code}/rewards', **links}) return links def display_signals(rows): public = [] for row in rows: if row.get('direction') not in ('long', 'short') or not isinstance(row.get('time'), str) or not isinstance(row.get('token'), str): raise ValueError('Unexpected signal format') public.append({field: row[field] for field in ('direction', 'time', 'token')}) return public async def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument('--url', default=DEFAULT_URL) p.add_argument('--key-file', type=Path) p.add_argument('--access-file', type=Path, help='Private file used to resume a purchase') p.add_argument('--max-usdc', type=Decimal) p.add_argument('--recipient', default=DEFAULT_RECIPIENT) p.add_argument('--allow-mainnet', action='store_true') modes = p.add_mutually_exclusive_group() modes.add_argument('--resume', action='store_true') modes.add_argument('--offer-only', action='store_true', help='Read the offer without a wallet or payment') modes.add_argument('--referral-only', action='store_true', help='Sign to register or recover a referral link without paying. See /partners for current eligibility.') p.add_argument('--register-referral', action='store_true', help='Register the paying wallet after on-chain confirmation') p.add_argument('--rewards-file', type=Path, help='Separate private rewards credentials file (default: ACCESS_FILE.referral.json)') p.add_argument('--show-signals', action='store_true', help='Include direction, time and token from the paid feed in JSON output') p.add_argument('--wait-seconds', type=int, default=1800) args = p.parse_args() base = origin(args.url) if not args.offer_only and not args.access_file: p.error('--access-file required') buying = not (args.offer_only or args.resume or args.referral_only) if buying and (args.max_usdc is None or not args.max_usdc.is_finite() or args.max_usdc <= 0): p.error('Positive --max-usdc required') registering = args.register_referral or args.referral_only if registering or buying: if not args.key_file: p.error('--key-file required') account = load_account(args.key_file) if registering: rewards_file = args.rewards_file or Path(str(args.access_file) + '.referral.json') if rewards_file.resolve() in (args.access_file.resolve(), args.key_file.resolve()): p.error('Use a separate rewards file') async with httpx.AsyncClient(timeout=60, follow_redirects=False) as http: if args.offer_only: required = await offer(http, args.url) terms = required.accepts[0] print(json.dumps({'network': terms.network, 'recipient': terms.pay_to, 'usdc': str(Decimal(terms.amount) / 1_000_000), 'description': required.resource.description if required.resource else ''})) return if args.referral_only: links = await register_referral(http, base, account, rewards_file) print(json.dumps({'referral': links, 'rewards_file': str(rewards_file)})) return response = await resume(http, args) if args.resume else await purchase(http, args, account) deadline = time.monotonic() + args.wait_seconds while True: source_wait = (response.status_code == 503 and response.json().get('status') == 'source_unavailable' and response.json().get('payment_confirmed') is True) if response.status_code not in (200, 202) and not source_wait: raise RuntimeError(f'Status {response.status_code}. Keep the saved authorization. Resume with the same access file.') body = response.json() poll_url = status_url(args.url, body['status_url']) token = body['access_token'] save_private(args.access_file, {'access_token': token, 'status_url': poll_url}) if response.status_code == 200 and body['status'] == 'confirmed': rows = body['data'].get('signals', []) output = {'status': body['status'], 'transaction': body['transaction'], 'expires_in': body['expires_in'], 'product': body['data'].get('product', 'neuraliquid-patterns' if 'signals' in body['data'] else 'historical-aapl'), 'signals': display_signals(rows) if args.show_signals else len(rows), 'points': len(body['data'].get('points', [])), 'access_file': str(args.access_file)} if args.register_referral: output['referral'] = await register_referral(http, base, account, rewards_file) output['rewards_file'] = str(rewards_file) print(json.dumps(output)) return if time.monotonic() >= deadline: print('Still pending. Resume using --resume and the same --access-file. Your original payment will be reused.') return await asyncio.sleep(15) response = await http.get(poll_url, headers={'Authorization': 'Bearer ' + token}) if __name__ == '__main__': asyncio.run(main())