|
1 | 1 | """Create and fund a testnet account, swap 1.5 USDCx for ETH, and claim the output.""" |
2 | 2 | import time |
| 3 | +from decimal import Decimal |
3 | 4 |
|
4 | 5 | from aleo import testnet |
5 | 6 |
|
|
44 | 45 | else: |
45 | 46 | raise RuntimeError("USDCx is not available; inspect funding.results and the account balance") |
46 | 47 |
|
47 | | - # Submit one swap with a 0.5% slippage limit. The SDK journals its handle. |
48 | | - swaps = dex.swap_many( |
| 48 | + # Quote the selected pool and convert the expected ETH output to base units. |
| 49 | + quote = dex.api.get_route( |
| 50 | + token_in=source.id, token_out=target.id, amount_in="1.5", pool_key=pool.key, |
| 51 | + ) |
| 52 | + if not quote.estimated_amount_out: |
| 53 | + raise RuntimeError("The selected pool returned no quote") |
| 54 | + expected_out = int(Decimal(quote.estimated_amount_out) * 10**target.decimals) |
| 55 | + if expected_out <= 0: |
| 56 | + raise RuntimeError("The quote returned no ETH") |
| 57 | + |
| 58 | + # Submit one swap and wait for confirmation. The SDK journals its handle. |
| 59 | + handle = dex.swap( |
49 | 60 | pool_key=pool.key, |
50 | 61 | token_in_id=source.id, |
51 | 62 | amount_in=amount_in, |
52 | | - count=1, |
| 63 | + expected_out=expected_out, |
53 | 64 | slippage_bps=50, |
54 | | - ) |
55 | | - if swaps.failures or len(swaps.handles) != 1: |
56 | | - raise RuntimeError("Swap submission needs inspection; use the SDK journal before retrying") |
| 65 | + ).delegate(wait=True) |
57 | 66 |
|
58 | | - # Collect the output after confirmation, without submitting another swap. |
59 | | - for attempt in range(40): |
60 | | - claims = dex.collect_all() |
61 | | - claim = next((item for item in claims.claimed |
62 | | - if item["swap_id"] == swaps.handles[0].swap_id), None) |
63 | | - if claim is not None: |
64 | | - if claim["amount_out"] <= 0: |
65 | | - raise RuntimeError("The claim returned no ETH") |
66 | | - break |
67 | | - time.sleep(15) |
68 | | - else: |
69 | | - raise RuntimeError("Claim is still pending; resume with dex.collect_all()") |
| 67 | + # Claim the confirmed swap's output once, then update the SDK journal. |
| 68 | + claim = dex.claim_swap_output(handle).delegate(wait=True) |
| 69 | + dex.journal.record_claim(handle.swap_id, claim.transaction_id, claim.amount_out) |
| 70 | + if claim.amount_out <= 0: |
| 71 | + raise RuntimeError("The claim returned no ETH") |
0 commit comments