@onecraft/wallet 0.0.0-stage → 0.1.145
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +20 -0
- package/.openclaw/AGENTS.md +100 -0
- package/.openclaw/extensions/agent-wallet/README.md +195 -0
- package/.openclaw/extensions/agent-wallet/dist/index.js +2198 -0
- package/.openclaw/extensions/agent-wallet/index.ts +2198 -0
- package/.openclaw/extensions/agent-wallet/openclaw.plugin.json +251 -0
- package/.openclaw/extensions/agent-wallet/package.json +49 -0
- package/.openclaw/extensions/agent-wallet/skills/cards/SKILL.md +211 -0
- package/.openclaw/extensions/agent-wallet/skills/wallet-operator/SKILL.md +30 -0
- package/CHANGELOG.md +1232 -0
- package/LICENSE +104 -0
- package/README.md +193 -2
- package/VERSION +1 -0
- package/agent-wallet/.env.example +63 -0
- package/agent-wallet/AGENTS.md +130 -0
- package/agent-wallet/CARD_VAULT.md +640 -0
- package/agent-wallet/README.md +615 -0
- package/agent-wallet/UPGRADE_COMPATIBILITY.md +66 -0
- package/agent-wallet/agent_wallet/__init__.py +16 -0
- package/agent-wallet/agent_wallet/approval.py +165 -0
- package/agent-wallet/agent_wallet/autonomous_permissions.py +281 -0
- package/agent-wallet/agent_wallet/autonomous_policy.py +305 -0
- package/agent-wallet/agent_wallet/autonomous_session.py +236 -0
- package/agent-wallet/agent_wallet/boot_key_migration.py +155 -0
- package/agent-wallet/agent_wallet/boot_key_recovery.py +57 -0
- package/agent-wallet/agent_wallet/bootstrap.py +194 -0
- package/agent-wallet/agent_wallet/card_catalog.py +243 -0
- package/agent-wallet/agent_wallet/card_runtime_secrets.py +108 -0
- package/agent-wallet/agent_wallet/card_vault.py +331 -0
- package/agent-wallet/agent_wallet/card_vault_cli.py +174 -0
- package/agent-wallet/agent_wallet/card_vault_import.py +65 -0
- package/agent-wallet/agent_wallet/card_vault_keychain.py +239 -0
- package/agent-wallet/agent_wallet/config.py +719 -0
- package/agent-wallet/agent_wallet/connector_cli.py +198 -0
- package/agent-wallet/agent_wallet/connectors/__init__.py +28 -0
- package/agent-wallet/agent_wallet/connectors/catalog.py +68 -0
- package/agent-wallet/agent_wallet/connectors/client.py +308 -0
- package/agent-wallet/agent_wallet/connectors/intent_policy.py +243 -0
- package/agent-wallet/agent_wallet/connectors/manifest.py +192 -0
- package/agent-wallet/agent_wallet/connectors/registry.py +341 -0
- package/agent-wallet/agent_wallet/encrypted_storage.py +314 -0
- package/agent-wallet/agent_wallet/evm_user_wallets.py +910 -0
- package/agent-wallet/agent_wallet/exceptions.py +10 -0
- package/agent-wallet/agent_wallet/file_ops.py +34 -0
- package/agent-wallet/agent_wallet/http_client.py +25 -0
- package/agent-wallet/agent_wallet/kernel_browser.py +479 -0
- package/agent-wallet/agent_wallet/kernel_cli.py +57 -0
- package/agent-wallet/agent_wallet/kernel_gateway.py +95 -0
- package/agent-wallet/agent_wallet/keystore.py +503 -0
- package/agent-wallet/agent_wallet/laso_card_vault.py +246 -0
- package/agent-wallet/agent_wallet/models.py +66 -0
- package/agent-wallet/agent_wallet/morpho_monitor.py +298 -0
- package/agent-wallet/agent_wallet/nonce_registry.py +59 -0
- package/agent-wallet/agent_wallet/openclaw_adapter.py +9129 -0
- package/agent-wallet/agent_wallet/openclaw_cli.py +658 -0
- package/agent-wallet/agent_wallet/openclaw_runtime.py +194 -0
- package/agent-wallet/agent_wallet/plugin_bundle.py +44 -0
- package/agent-wallet/agent_wallet/providers/__init__.py +1 -0
- package/agent-wallet/agent_wallet/providers/bags.py +202 -0
- package/agent-wallet/agent_wallet/providers/dexscreener.py +147 -0
- package/agent-wallet/agent_wallet/providers/evm_activity.py +257 -0
- package/agent-wallet/agent_wallet/providers/evm_portfolio.py +459 -0
- package/agent-wallet/agent_wallet/providers/imd.py +720 -0
- package/agent-wallet/agent_wallet/providers/jupiter.py +519 -0
- package/agent-wallet/agent_wallet/providers/kamino.py +404 -0
- package/agent-wallet/agent_wallet/providers/lifi.py +302 -0
- package/agent-wallet/agent_wallet/providers/solana_rpc.py +447 -0
- package/agent-wallet/agent_wallet/providers/tokenized_stocks.py +189 -0
- package/agent-wallet/agent_wallet/providers/wdk_evm_local.py +346 -0
- package/agent-wallet/agent_wallet/providers/x402.py +1972 -0
- package/agent-wallet/agent_wallet/sealed_keys.py +118 -0
- package/agent-wallet/agent_wallet/solana_stake.py +103 -0
- package/agent-wallet/agent_wallet/solana_tx.py +93 -0
- package/agent-wallet/agent_wallet/spending_limits.py +119 -0
- package/agent-wallet/agent_wallet/telemetry.py +481 -0
- package/agent-wallet/agent_wallet/transaction_policy.py +573 -0
- package/agent-wallet/agent_wallet/update_check.py +190 -0
- package/agent-wallet/agent_wallet/user_wallets.py +573 -0
- package/agent-wallet/agent_wallet/validation.py +31 -0
- package/agent-wallet/agent_wallet/vault_executor.py +456 -0
- package/agent-wallet/agent_wallet/wallet_layer/__init__.py +1 -0
- package/agent-wallet/agent_wallet/wallet_layer/base.py +1204 -0
- package/agent-wallet/agent_wallet/wallet_layer/base58.py +44 -0
- package/agent-wallet/agent_wallet/wallet_layer/factory.py +117 -0
- package/agent-wallet/agent_wallet/wallet_layer/solana.py +5246 -0
- package/agent-wallet/agent_wallet/wallet_layer/wdk_evm.py +2705 -0
- package/agent-wallet/examples/bootstrap_wallet.py +21 -0
- package/agent-wallet/examples/openclaw_runtime_onboarding.py +28 -0
- package/agent-wallet/examples/openclaw_user_wallet_example.py +31 -0
- package/agent-wallet/examples/openclaw_wallet_adapter_example.py +33 -0
- package/agent-wallet/openclaw.plugin.json +118 -0
- package/agent-wallet/pyproject.toml +36 -0
- package/agent-wallet/scripts/bootstrap_openclaw_evm.py +312 -0
- package/agent-wallet/scripts/build_release_bundle.py +210 -0
- package/agent-wallet/scripts/finalize_openclaw_local_wallet_config.py +121 -0
- package/agent-wallet/scripts/install_agent_wallet.py +1357 -0
- package/agent-wallet/scripts/install_openclaw_local_config.py +421 -0
- package/agent-wallet/scripts/install_openclaw_sealed_keys.py +117 -0
- package/agent-wallet/scripts/manage_openclaw_evm_wallet.py +333 -0
- package/agent-wallet/scripts/security_utils.py +37 -0
- package/agent-wallet/scripts/setup_evm_wallet.sh +140 -0
- package/agent-wallet/scripts/switch_openclaw_wallet_network.py +109 -0
- package/agent-wallet/skills/wallet-operator/SKILL.md +157 -0
- package/bin/lib/boot-key.mjs +184 -0
- package/bin/lib/evm-daemon.mjs +389 -0
- package/bin/lib/host-detection.mjs +259 -0
- package/bin/lib/integrations.mjs +578 -0
- package/bin/lib/release-python.mjs +9 -0
- package/bin/lib/update-transaction.mjs +235 -0
- package/bin/openclaw-agent-wallet.mjs +3354 -0
- package/claude-code/plugins/agent-wallet/.claude-plugin/plugin.json +19 -0
- package/claude-code/plugins/agent-wallet/.mcp.json +14 -0
- package/claude-code/plugins/agent-wallet/AGENTLAYER_AGENT_GUIDE.md +282 -0
- package/claude-code/plugins/agent-wallet/README.md +134 -0
- package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-approve.md +39 -0
- package/claude-code/plugins/agent-wallet/commands/agentlayer-autonomous-revoke.md +17 -0
- package/claude-code/plugins/agent-wallet/commands/cards.md +129 -0
- package/claude-code/plugins/agent-wallet/commands/guide.md +40 -0
- package/claude-code/plugins/agent-wallet/commands/imd.md +125 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-base.md +60 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-ethereum.md +37 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-evm.md +39 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-setup.md +25 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-sol.md +51 -0
- package/claude-code/plugins/agent-wallet/commands/wallet-statusline.md +34 -0
- package/claude-code/plugins/agent-wallet/commands/x402.md +121 -0
- package/claude-code/plugins/agent-wallet/commands/yield.md +62 -0
- package/claude-code/plugins/agent-wallet/hooks/hooks.json +16 -0
- package/claude-code/plugins/agent-wallet/scripts/bootstrap_backend.sh +136 -0
- package/claude-code/plugins/agent-wallet/scripts/enable_statusline.py +52 -0
- package/claude-code/plugins/agent-wallet/scripts/resolve_wallet_addresses.py +69 -0
- package/claude-code/plugins/agent-wallet/scripts/run_mcp.sh +66 -0
- package/claude-code/plugins/agent-wallet/scripts/wallet_statusline.py +130 -0
- package/claude-code/plugins/agent-wallet/scripts/wallet_statusline_setup.sh +40 -0
- package/claude-code/plugins/agent-wallet/skills/wallet-operator/SKILL.md +21 -0
- package/codex/plugins/agent-wallet/.codex-plugin/plugin.json +37 -0
- package/codex/plugins/agent-wallet/.mcp.json +15 -0
- package/codex/plugins/agent-wallet/README.md +158 -0
- package/codex/plugins/agent-wallet/scripts/run_mcp.sh +47 -0
- package/codex/plugins/agent-wallet/server.py +1797 -0
- package/codex/plugins/agent-wallet/skills/cards/SKILL.md +225 -0
- package/codex/plugins/agent-wallet/skills/imd/SKILL.md +145 -0
- package/codex/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
- package/codex/plugins/agent-wallet/skills/wallet-operator/SKILL.md +85 -0
- package/codex/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
- package/codex/plugins/agent-wallet/skills/x402/SKILL.md +159 -0
- package/codex/plugins/agent-wallet/skills/yield/SKILL.md +65 -0
- package/connectors/AGENTS.md +37 -0
- package/connectors/DEVELOPER_GUIDE.md +131 -0
- package/connectors/README.md +139 -0
- package/connectors/READ_ONLY_BETA.md +54 -0
- package/connectors/RELEASING.md +48 -0
- package/connectors/conformance/README.md +31 -0
- package/connectors/conformance/package.json +54 -0
- package/connectors/conformance/scripts/sync-license.mjs +3 -0
- package/connectors/conformance/scripts/sync-spec.mjs +16 -0
- package/connectors/conformance/src/cli.ts +43 -0
- package/connectors/conformance/src/index.ts +7 -0
- package/connectors/conformance/src/runner.ts +314 -0
- package/connectors/conformance/src/types.ts +27 -0
- package/connectors/conformance/test/fixtures/invalid-response-identity.json +14 -0
- package/connectors/conformance/test/fixtures/missing-tool-fixture.json +4 -0
- package/connectors/conformance/test/runner.test.mjs +151 -0
- package/connectors/conformance/tsconfig.json +17 -0
- package/connectors/examples/reference-crypto-data/Dockerfile +21 -0
- package/connectors/examples/reference-crypto-data/README.md +51 -0
- package/connectors/examples/reference-crypto-data/conformance.json +11 -0
- package/connectors/examples/reference-crypto-data/connector.json +95 -0
- package/connectors/examples/reference-crypto-data/package.json +21 -0
- package/connectors/examples/reference-crypto-data/railway.toml +9 -0
- package/connectors/examples/reference-crypto-data/src/connector.ts +137 -0
- package/connectors/examples/reference-crypto-data/src/server.ts +13 -0
- package/connectors/examples/reference-crypto-data/test/connector.test.mjs +97 -0
- package/connectors/examples/reference-crypto-data/tsconfig.json +17 -0
- package/connectors/package-lock.json +561 -0
- package/connectors/package.json +19 -0
- package/connectors/scripts/smoke-packed-packages.mjs +121 -0
- package/connectors/sdk-typescript/README.md +47 -0
- package/connectors/sdk-typescript/package.json +49 -0
- package/connectors/sdk-typescript/scripts/sync-license.mjs +3 -0
- package/connectors/sdk-typescript/src/connector.ts +204 -0
- package/connectors/sdk-typescript/src/errors.ts +11 -0
- package/connectors/sdk-typescript/src/http.ts +116 -0
- package/connectors/sdk-typescript/src/index.ts +26 -0
- package/connectors/sdk-typescript/src/types.ts +101 -0
- package/connectors/sdk-typescript/test/sdk.test.mjs +181 -0
- package/connectors/sdk-typescript/tsconfig.json +21 -0
- package/connectors/spec/connector-manifest.schema.json +340 -0
- package/connectors/spec/connector-protocol.md +159 -0
- package/connectors/spec/transaction-intent.schema.json +281 -0
- package/connectors/templates/read-only/.env.example +1 -0
- package/connectors/templates/read-only/Dockerfile +11 -0
- package/connectors/templates/read-only/README.md +33 -0
- package/connectors/templates/read-only/conformance.json +11 -0
- package/connectors/templates/read-only/connector.json +64 -0
- package/connectors/templates/read-only/package.json +21 -0
- package/connectors/templates/read-only/railway.toml +9 -0
- package/connectors/templates/read-only/src/connector.ts +61 -0
- package/connectors/templates/read-only/src/server.ts +14 -0
- package/connectors/templates/read-only/test/connector.test.mjs +62 -0
- package/connectors/templates/read-only/tsconfig.json +17 -0
- package/cursor/plugins/agent-wallet/.cursor-plugin/plugin.json +14 -0
- package/cursor/plugins/agent-wallet/README.md +62 -0
- package/cursor/plugins/agent-wallet/mcp.json +16 -0
- package/cursor/plugins/agent-wallet/scripts/run_mcp.sh +33 -0
- package/cursor/plugins/agent-wallet/server.py +33 -0
- package/cursor/plugins/agent-wallet/skills/cards/SKILL.md +210 -0
- package/cursor/plugins/agent-wallet/skills/wallet-base/SKILL.md +56 -0
- package/cursor/plugins/agent-wallet/skills/wallet-operator/SKILL.md +23 -0
- package/cursor/plugins/agent-wallet/skills/wallet-sol/SKILL.md +29 -0
- package/cursor/plugins/agent-wallet/skills/x402/SKILL.md +130 -0
- package/hermes/plugins/agent_wallet/README.md +54 -0
- package/hermes/plugins/agent_wallet/__init__.py +55 -0
- package/hermes/plugins/agent_wallet/plugin.yaml +9 -0
- package/hermes/plugins/agent_wallet/schemas.py +211 -0
- package/hermes/plugins/agent_wallet/tools.py +622 -0
- package/install-from-github.sh +139 -0
- package/integrations/hedera/treasury-guard/README.md +92 -0
- package/integrations/hedera/treasury-guard/examples/treasury-policy.example.json +9 -0
- package/integrations/hedera/treasury-guard/package-lock.json +880 -0
- package/integrations/hedera/treasury-guard/package.json +8 -0
- package/integrations/hedera/treasury-guard/skills/onecraft-hedera-treasury/SKILL.md +22 -0
- package/integrations/hedera/treasury-guard/src/hedera-mirror-client.mjs +106 -0
- package/integrations/hedera/treasury-guard/src/hedera-signer.mjs +120 -0
- package/integrations/hedera/treasury-guard/src/treasury-cli.mjs +177 -0
- package/integrations/hedera/treasury-guard/src/treasury-policy.mjs +155 -0
- package/mcp/README.md +39 -0
- package/mcp/scripts/run_mcp.sh +37 -0
- package/mcp/server.py +33 -0
- package/package.json +106 -4
- package/scripts/check_release_version.mjs +72 -0
- package/scripts/version_targets.mjs +60 -0
- package/setup.sh +87 -0
- package/wdk-evm-wallet/.env.example +38 -0
- package/wdk-evm-wallet/README.md +254 -0
- package/wdk-evm-wallet/bootstrap.sh +8 -0
- package/wdk-evm-wallet/package-lock.json +2359 -0
- package/wdk-evm-wallet/package.json +43 -0
- package/wdk-evm-wallet/run-local.sh +12 -0
- package/wdk-evm-wallet/src/config.js +461 -0
- package/wdk-evm-wallet/src/imd.js +231 -0
- package/wdk-evm-wallet/src/json.js +35 -0
- package/wdk-evm-wallet/src/local_vault.js +407 -0
- package/wdk-evm-wallet/src/network_state.js +96 -0
- package/wdk-evm-wallet/src/pending_transactions.js +148 -0
- package/wdk-evm-wallet/src/server.js +849 -0
- package/wdk-evm-wallet/src/shutdown.js +63 -0
- package/wdk-evm-wallet/src/wdk_evm_wallet.js +10036 -0
|
@@ -0,0 +1,720 @@
|
|
|
1
|
+
"""IMD (https://imd.fun) paid actions: open jobs and other work for 0.5 IMD each.
|
|
2
|
+
|
|
3
|
+
IMD sells actions (``job.open``, ``schedule.create``...) through x402 v2
|
|
4
|
+
``exact`` with Permit2 on Ethereum mainnet, plus an IMD-specific EIP-712
|
|
5
|
+
QuoteApproval that binds the payment to the quote. A stock x402 client makes
|
|
6
|
+
only the first signature, and the flow is quote -> challenge -> submit rather
|
|
7
|
+
than a single 402 retry, so this provider drives it end to end.
|
|
8
|
+
|
|
9
|
+
Every value that reaches a signature is checked here against the pinned IMD
|
|
10
|
+
constants, and again by the wallet daemon (wdk-evm-wallet/src/imd.js) before
|
|
11
|
+
it signs.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import base64
|
|
17
|
+
import hashlib
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import secrets
|
|
21
|
+
import time
|
|
22
|
+
import uuid
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from agent_wallet.config import resolve_openclaw_home
|
|
27
|
+
from agent_wallet.exceptions import ProviderError
|
|
28
|
+
from agent_wallet.http_client import get_client
|
|
29
|
+
|
|
30
|
+
PROVIDER = "imd"
|
|
31
|
+
IMD_API_ORIGIN = "https://api.imd.fun"
|
|
32
|
+
IMD_NETWORK = "eip155:1"
|
|
33
|
+
IMD_TOKEN_ADDRESS = "0xd34a99bc0f67ae1bbd63c660e6d0b0dd03e263b7"
|
|
34
|
+
IMD_DECIMALS = 18
|
|
35
|
+
IMD_PAY_TO_ALLOWLIST = frozenset({"0x4e0fa57bde726079356537e2f34d671e9f41adbc"})
|
|
36
|
+
PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3"
|
|
37
|
+
X402_EXACT_PERMIT2_PROXY_ADDRESS = "0x402085c248EeA27D92E8b30b2C58ed07f9E20001"
|
|
38
|
+
IMD_ACTIONS = (
|
|
39
|
+
"job.open",
|
|
40
|
+
"job.continue",
|
|
41
|
+
"launch.open",
|
|
42
|
+
"workflow.open",
|
|
43
|
+
"oracle.request",
|
|
44
|
+
"schedule.create",
|
|
45
|
+
"schedule.topup",
|
|
46
|
+
)
|
|
47
|
+
# Actions this integration opens. launch/workflow/oracle stay out until they
|
|
48
|
+
# get their own UX (deployments, token economics, on-chain answers).
|
|
49
|
+
IMD_ENABLED_ACTIONS = ("job.open", "job.continue", "schedule.create", "schedule.topup")
|
|
50
|
+
IMD_PRICE_PER_ACTION_RAW = 500_000_000_000_000_000
|
|
51
|
+
IMD_MAX_PER_PAYMENT_RAW = 5 * 10**18
|
|
52
|
+
IMD_DEFAULT_DAILY_LIMIT_RAW = 5 * 10**18
|
|
53
|
+
DAY_SECONDS = 24 * 60 * 60
|
|
54
|
+
# The permit must end before the quote does; keep a margin for the submit.
|
|
55
|
+
PERMIT_DEADLINE_MARGIN_SECONDS = 30
|
|
56
|
+
PERMIT_MAX_LIFETIME_SECONDS = 300
|
|
57
|
+
MIN_QUOTE_REMAINING_SECONDS = 60
|
|
58
|
+
ORDER_POLL_ATTEMPTS = 4
|
|
59
|
+
ORDER_POLL_INTERVAL_SECONDS = 2.0
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# --------------------------------------------------------------------------
|
|
63
|
+
# Pure helpers
|
|
64
|
+
# --------------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def canonical_json(value: Any) -> str:
|
|
68
|
+
"""IMD's canonical JSON: sorted keys, no whitespace, integers only.
|
|
69
|
+
|
|
70
|
+
Mirrors the reference ``canon`` in IMD's docs (JSON.stringify per scalar),
|
|
71
|
+
which the paymentHash in the QuoteApproval is computed over.
|
|
72
|
+
"""
|
|
73
|
+
if value is None:
|
|
74
|
+
return "null"
|
|
75
|
+
if isinstance(value, bool):
|
|
76
|
+
return "true" if value else "false"
|
|
77
|
+
if isinstance(value, int):
|
|
78
|
+
return str(value)
|
|
79
|
+
if isinstance(value, float):
|
|
80
|
+
raise ProviderError(PROVIDER, "IMD canonical JSON allows integers only.")
|
|
81
|
+
if isinstance(value, str):
|
|
82
|
+
return json.dumps(value, ensure_ascii=False)
|
|
83
|
+
if isinstance(value, (list, tuple)):
|
|
84
|
+
return "[" + ",".join(canonical_json(item) for item in value) + "]"
|
|
85
|
+
if isinstance(value, dict):
|
|
86
|
+
return (
|
|
87
|
+
"{"
|
|
88
|
+
+ ",".join(
|
|
89
|
+
f"{json.dumps(str(key), ensure_ascii=False)}:{canonical_json(value[key])}"
|
|
90
|
+
for key in sorted(value, key=str)
|
|
91
|
+
)
|
|
92
|
+
+ "}"
|
|
93
|
+
)
|
|
94
|
+
raise ProviderError(PROVIDER, f"Unsupported value in IMD canonical JSON: {type(value).__name__}.")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def payment_hash(payment: dict[str, Any]) -> str:
|
|
98
|
+
return "0x" + hashlib.sha256(canonical_json(payment).encode("utf-8")).hexdigest()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def input_hash(action: str, action_input: dict[str, Any]) -> str:
|
|
102
|
+
return hashlib.sha256(canonical_json({"action": action, "input": action_input}).encode("utf-8")).hexdigest()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def encode_payment_header(payment: dict[str, Any]) -> str:
|
|
106
|
+
return base64.b64encode(json.dumps(payment, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).decode(
|
|
107
|
+
"ascii"
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def format_imd(amount_raw: int | str) -> str:
|
|
112
|
+
amount = int(amount_raw)
|
|
113
|
+
whole, frac = divmod(amount, 10**IMD_DECIMALS)
|
|
114
|
+
frac_text = str(frac).rjust(IMD_DECIMALS, "0").rstrip("0")
|
|
115
|
+
return f"{whole}.{frac_text}" if frac_text else str(whole)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _same_address(left: Any, right: Any) -> bool:
|
|
119
|
+
return isinstance(left, str) and isinstance(right, str) and left.lower() == right.lower()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def validate_action(action: Any) -> str:
|
|
123
|
+
if not isinstance(action, str) or action not in IMD_ENABLED_ACTIONS:
|
|
124
|
+
raise ProviderError(
|
|
125
|
+
PROVIDER,
|
|
126
|
+
f"action must be one of: {', '.join(IMD_ENABLED_ACTIONS)}.",
|
|
127
|
+
details={"action": action},
|
|
128
|
+
)
|
|
129
|
+
return action
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def validate_payment_terms(payment: Any, *, where: str) -> dict[str, Any]:
|
|
133
|
+
"""Check an IMD payment block (quote or challenge) against the pinned terms."""
|
|
134
|
+
if not isinstance(payment, dict):
|
|
135
|
+
raise ProviderError(PROVIDER, f"IMD {where} has no payment terms.")
|
|
136
|
+
problems = []
|
|
137
|
+
if payment.get("network") != IMD_NETWORK:
|
|
138
|
+
problems.append(f"network {payment.get('network')!r} is not {IMD_NETWORK}")
|
|
139
|
+
if not _same_address(payment.get("asset"), IMD_TOKEN_ADDRESS):
|
|
140
|
+
problems.append("asset is not the IMD token")
|
|
141
|
+
if not any(_same_address(payment.get("payTo"), allowed) for allowed in IMD_PAY_TO_ALLOWLIST):
|
|
142
|
+
problems.append("payTo is not the known IMD treasury")
|
|
143
|
+
try:
|
|
144
|
+
amount = int(str(payment.get("amount")))
|
|
145
|
+
except (TypeError, ValueError):
|
|
146
|
+
amount = 0
|
|
147
|
+
problems.append("amount is not an integer")
|
|
148
|
+
if amount <= 0 or amount > IMD_MAX_PER_PAYMENT_RAW:
|
|
149
|
+
problems.append("amount is outside (0, 5 IMD]")
|
|
150
|
+
if problems:
|
|
151
|
+
raise ProviderError(
|
|
152
|
+
PROVIDER,
|
|
153
|
+
f"IMD {where} payment terms do not match the pinned IMD terms ({'; '.join(problems)}); nothing was signed.",
|
|
154
|
+
details={"problems": problems, "payment": payment},
|
|
155
|
+
)
|
|
156
|
+
return payment
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def validate_challenge(challenge: Any, quote: dict[str, Any]) -> dict[str, Any]:
|
|
160
|
+
"""Validate the 402 challenge and return its accepts[0]."""
|
|
161
|
+
if not isinstance(challenge, dict):
|
|
162
|
+
raise ProviderError(PROVIDER, "IMD submit challenge is not a JSON object.")
|
|
163
|
+
accepts = challenge.get("accepts")
|
|
164
|
+
if not isinstance(accepts, list) or not accepts or not isinstance(accepts[0], dict):
|
|
165
|
+
raise ProviderError(PROVIDER, "IMD challenge has no accepts[0].")
|
|
166
|
+
requirement = accepts[0]
|
|
167
|
+
validate_payment_terms(requirement, where="challenge")
|
|
168
|
+
if requirement.get("scheme") != "exact":
|
|
169
|
+
raise ProviderError(PROVIDER, "IMD challenge scheme is not 'exact'.")
|
|
170
|
+
extra = requirement.get("extra") if isinstance(requirement.get("extra"), dict) else {}
|
|
171
|
+
if extra.get("assetTransferMethod") != "permit2":
|
|
172
|
+
raise ProviderError(PROVIDER, "IMD challenge does not ask for a Permit2 transfer.")
|
|
173
|
+
quote_payment = quote.get("payment") or {}
|
|
174
|
+
for key in ("amount", "asset", "payTo", "network"):
|
|
175
|
+
left, right = requirement.get(key), quote_payment.get(key)
|
|
176
|
+
same = _same_address(left, right) if key in {"asset", "payTo"} else str(left) == str(right)
|
|
177
|
+
if not same:
|
|
178
|
+
raise ProviderError(
|
|
179
|
+
PROVIDER,
|
|
180
|
+
f"IMD challenge {key} differs from the quote; nothing was signed.",
|
|
181
|
+
details={"challenge": left, "quote": right},
|
|
182
|
+
)
|
|
183
|
+
resource_url = challenge.get("resourceUrl")
|
|
184
|
+
if not isinstance(resource_url, str) or not resource_url.startswith(f"{IMD_API_ORIGIN}/"):
|
|
185
|
+
raise ProviderError(PROVIDER, "IMD challenge resourceUrl is not an api.imd.fun URL.")
|
|
186
|
+
scope = str(challenge.get("requesterScopeHash") or "").removeprefix("0x")
|
|
187
|
+
if len(scope) != 64:
|
|
188
|
+
raise ProviderError(PROVIDER, "IMD challenge requesterScopeHash is not 32 bytes.")
|
|
189
|
+
return requirement
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def build_permit(
|
|
193
|
+
*,
|
|
194
|
+
requirement: dict[str, Any],
|
|
195
|
+
owner: str,
|
|
196
|
+
quote_expires_at: int,
|
|
197
|
+
now: int | None = None,
|
|
198
|
+
nonce: int | None = None,
|
|
199
|
+
) -> dict[str, Any]:
|
|
200
|
+
current = int(time.time()) if now is None else int(now)
|
|
201
|
+
deadline = min(current + PERMIT_MAX_LIFETIME_SECONDS, quote_expires_at - PERMIT_DEADLINE_MARGIN_SECONDS)
|
|
202
|
+
if deadline <= current:
|
|
203
|
+
raise ProviderError(PROVIDER, "The IMD quote expires too soon to pay; request a fresh quote.")
|
|
204
|
+
return {
|
|
205
|
+
"from": owner,
|
|
206
|
+
"permitted": {"token": requirement["asset"], "amount": str(requirement["amount"])},
|
|
207
|
+
"spender": X402_EXACT_PERMIT2_PROXY_ADDRESS,
|
|
208
|
+
"nonce": str(secrets.randbits(256) if nonce is None else nonce),
|
|
209
|
+
"deadline": str(deadline),
|
|
210
|
+
"witness": {"to": requirement["payTo"], "validAfter": str(current - 600)},
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def build_payment(
|
|
215
|
+
*,
|
|
216
|
+
challenge: dict[str, Any],
|
|
217
|
+
requirement: dict[str, Any],
|
|
218
|
+
permit: dict[str, Any],
|
|
219
|
+
signature: str,
|
|
220
|
+
) -> dict[str, Any]:
|
|
221
|
+
"""Assemble the payment exactly as IMD's strict parser accepts it."""
|
|
222
|
+
payment: dict[str, Any] = {
|
|
223
|
+
"x402Version": 2,
|
|
224
|
+
"accepted": json.loads(json.dumps(requirement)),
|
|
225
|
+
"payload": {"signature": signature, "permit2Authorization": permit},
|
|
226
|
+
}
|
|
227
|
+
resource = challenge.get("resource")
|
|
228
|
+
if isinstance(resource, dict):
|
|
229
|
+
payment["resource"] = {
|
|
230
|
+
key: resource[key] for key in ("url", "description", "mimeType") if key in resource
|
|
231
|
+
}
|
|
232
|
+
payment["resource"]["url"] = challenge["resourceUrl"]
|
|
233
|
+
return payment
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def build_quote_approval(
|
|
237
|
+
*,
|
|
238
|
+
challenge: dict[str, Any],
|
|
239
|
+
quote: dict[str, Any],
|
|
240
|
+
payment: dict[str, Any],
|
|
241
|
+
) -> dict[str, Any]:
|
|
242
|
+
quote_payment = quote["payment"]
|
|
243
|
+
return {
|
|
244
|
+
"resource": challenge["resourceUrl"],
|
|
245
|
+
"requesterScopeHash": "0x" + str(challenge["requesterScopeHash"]).removeprefix("0x"),
|
|
246
|
+
"quoteId": quote["id"],
|
|
247
|
+
"quoteHash": "0x" + str(quote["quoteHash"]).removeprefix("0x"),
|
|
248
|
+
"paymentHash": payment_hash(payment),
|
|
249
|
+
"action": quote["action"],
|
|
250
|
+
"asset": quote_payment["asset"],
|
|
251
|
+
"amount": str(quote_payment["amount"]),
|
|
252
|
+
"payTo": quote_payment["payTo"],
|
|
253
|
+
"expiresAt": str(quote["expiresAt"]),
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# --------------------------------------------------------------------------
|
|
258
|
+
# Local state: the request token and the order journal
|
|
259
|
+
# --------------------------------------------------------------------------
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _state_dir() -> Path:
|
|
263
|
+
override = os.getenv("AGENT_WALLET_IMD_STATE_DIR")
|
|
264
|
+
path = Path(override).expanduser() if override else resolve_openclaw_home() / "agent-wallet" / "imd"
|
|
265
|
+
path.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
266
|
+
return path
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _token_path(owner: str) -> Path:
|
|
270
|
+
return _state_dir() / f"token-{owner.lower()}"
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _journal_path(owner: str) -> Path:
|
|
274
|
+
return _state_dir() / f"orders-{owner.lower()}.jsonl"
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def load_or_create_request_token(owner: str) -> str:
|
|
278
|
+
"""One IMD request token per wallet; it reads that wallet's orders later."""
|
|
279
|
+
path = _token_path(owner)
|
|
280
|
+
if path.exists():
|
|
281
|
+
token = path.read_text(encoding="utf-8").strip()
|
|
282
|
+
if len(token) == 64:
|
|
283
|
+
return token
|
|
284
|
+
token = secrets.token_hex(32)
|
|
285
|
+
fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
286
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
287
|
+
handle.write(token)
|
|
288
|
+
return token
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def append_journal(owner: str, entry: dict[str, Any]) -> None:
|
|
292
|
+
fd = os.open(str(_journal_path(owner)), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
293
|
+
with os.fdopen(fd, "a", encoding="utf-8") as handle:
|
|
294
|
+
handle.write(json.dumps(entry, separators=(",", ":")) + "\n")
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def read_journal(owner: str, *, limit: int = 50) -> list[dict[str, Any]]:
|
|
298
|
+
path = _journal_path(owner)
|
|
299
|
+
if not path.exists():
|
|
300
|
+
return []
|
|
301
|
+
entries = []
|
|
302
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
303
|
+
try:
|
|
304
|
+
entry = json.loads(line)
|
|
305
|
+
except json.JSONDecodeError:
|
|
306
|
+
continue
|
|
307
|
+
if isinstance(entry, dict):
|
|
308
|
+
entries.append(entry)
|
|
309
|
+
return entries[-limit:]
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def daily_limit_raw() -> int:
|
|
313
|
+
raw = os.getenv("AGENT_WALLET_IMD_DAILY_LIMIT_RAW")
|
|
314
|
+
if raw and raw.strip().isdigit():
|
|
315
|
+
return int(raw.strip())
|
|
316
|
+
return IMD_DEFAULT_DAILY_LIMIT_RAW
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def spent_last_day_raw(owner: str, *, now: int | None = None) -> int:
|
|
320
|
+
current = int(time.time()) if now is None else int(now)
|
|
321
|
+
total = 0
|
|
322
|
+
for entry in read_journal(owner, limit=10_000):
|
|
323
|
+
if entry.get("event") != "signed":
|
|
324
|
+
continue
|
|
325
|
+
if current - int(entry.get("ts") or 0) > DAY_SECONDS:
|
|
326
|
+
continue
|
|
327
|
+
try:
|
|
328
|
+
total += int(entry.get("amount_raw") or 0)
|
|
329
|
+
except (TypeError, ValueError):
|
|
330
|
+
continue
|
|
331
|
+
return total
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def assert_within_daily_limit(owner: str, amount_raw: int) -> None:
|
|
335
|
+
limit = daily_limit_raw()
|
|
336
|
+
spent = spent_last_day_raw(owner)
|
|
337
|
+
if spent + amount_raw > limit:
|
|
338
|
+
raise ProviderError(
|
|
339
|
+
PROVIDER,
|
|
340
|
+
f"IMD daily limit reached: {format_imd(spent)} of {format_imd(limit)} IMD signed in the last 24h; "
|
|
341
|
+
f"this payment needs {format_imd(amount_raw)} more.",
|
|
342
|
+
details={"spent_raw": str(spent), "limit_raw": str(limit), "amount_raw": str(amount_raw)},
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
# --------------------------------------------------------------------------
|
|
347
|
+
# HTTP
|
|
348
|
+
# --------------------------------------------------------------------------
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
async def _request(
|
|
352
|
+
method: str,
|
|
353
|
+
path: str,
|
|
354
|
+
*,
|
|
355
|
+
token: str | None = None,
|
|
356
|
+
json_body: Any = None,
|
|
357
|
+
headers: dict[str, str] | None = None,
|
|
358
|
+
expected: tuple[int, ...] = (200,),
|
|
359
|
+
) -> tuple[int, Any]:
|
|
360
|
+
if not path.startswith("/"):
|
|
361
|
+
raise ProviderError(PROVIDER, "IMD path must start with '/'.")
|
|
362
|
+
request_headers = {"Accept": "application/json"}
|
|
363
|
+
if token:
|
|
364
|
+
request_headers["Authorization"] = f"Bearer {token}"
|
|
365
|
+
if headers:
|
|
366
|
+
request_headers.update(headers)
|
|
367
|
+
client = get_client()
|
|
368
|
+
try:
|
|
369
|
+
response = await client.request(
|
|
370
|
+
method,
|
|
371
|
+
f"{IMD_API_ORIGIN}{path}",
|
|
372
|
+
headers=request_headers,
|
|
373
|
+
json=json_body,
|
|
374
|
+
follow_redirects=False,
|
|
375
|
+
)
|
|
376
|
+
except Exception as exc:
|
|
377
|
+
raise ProviderError(
|
|
378
|
+
PROVIDER,
|
|
379
|
+
f"IMD request failed before a response: {type(exc).__name__}.",
|
|
380
|
+
details={"path": path, "transport_error": True},
|
|
381
|
+
) from exc
|
|
382
|
+
try:
|
|
383
|
+
payload = response.json()
|
|
384
|
+
except Exception:
|
|
385
|
+
payload = {"raw": (response.text or "")[:2000]}
|
|
386
|
+
if response.status_code not in expected:
|
|
387
|
+
error = payload.get("error") if isinstance(payload, dict) else None
|
|
388
|
+
detail = payload.get("detail") if isinstance(payload, dict) else None
|
|
389
|
+
raise ProviderError(
|
|
390
|
+
PROVIDER,
|
|
391
|
+
f"IMD {method} {path} returned {response.status_code}"
|
|
392
|
+
+ (f" {error}" if error else "")
|
|
393
|
+
+ (f": {detail}" if detail else ""),
|
|
394
|
+
details={"status": response.status_code, "path": path, "response": payload},
|
|
395
|
+
)
|
|
396
|
+
return response.status_code, payload
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
async def get_capabilities() -> dict[str, Any]:
|
|
400
|
+
_, payload = await _request("GET", "/requests/capabilities")
|
|
401
|
+
return payload
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
async def check_request(action: str, action_input: dict[str, Any]) -> dict[str, Any]:
|
|
405
|
+
_, payload = await _request(
|
|
406
|
+
"POST", "/requests/check", json_body={"action": action, "input": action_input}
|
|
407
|
+
)
|
|
408
|
+
return payload
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
async def import_repository(url: str, kind: str, ref: str | None = None) -> dict[str, Any]:
|
|
412
|
+
body: dict[str, Any] = {"url": url, "kind": kind}
|
|
413
|
+
if ref:
|
|
414
|
+
body["ref"] = ref
|
|
415
|
+
_, payload = await _request("POST", "/requests/import", json_body=body)
|
|
416
|
+
return payload
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
async def get_order(token: str, order_id: str) -> dict[str, Any]:
|
|
420
|
+
_, payload = await _request("GET", f"/requests/{_path_id(order_id)}", token=token)
|
|
421
|
+
return payload
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
async def get_paid_by(address: str) -> dict[str, Any]:
|
|
425
|
+
_, payload = await _request("GET", f"/requests/paid-by/{_path_id(address)}")
|
|
426
|
+
return payload
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
async def get_job(job_id: str) -> dict[str, Any]:
|
|
430
|
+
_, payload = await _request("GET", f"/jobs/{_path_id(job_id)}")
|
|
431
|
+
return payload
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
async def get_job_result(job_id: str) -> dict[str, Any]:
|
|
435
|
+
_, payload = await _request("GET", f"/jobs/{_path_id(job_id)}/result", expected=(200, 404, 409))
|
|
436
|
+
return payload
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _path_id(value: str) -> str:
|
|
440
|
+
text = str(value or "").strip()
|
|
441
|
+
if not text or not all(ch.isalnum() or ch in "-_" for ch in text) or len(text) > 128:
|
|
442
|
+
raise ProviderError(PROVIDER, "IMD id must be alphanumeric (with - or _).", details={"id": value})
|
|
443
|
+
return text
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
# --------------------------------------------------------------------------
|
|
447
|
+
# Account readiness
|
|
448
|
+
# --------------------------------------------------------------------------
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
async def account_status(backend: Any) -> dict[str, Any]:
|
|
452
|
+
state = await backend.get_imd_account_state()
|
|
453
|
+
capabilities = await get_capabilities()
|
|
454
|
+
actions = {
|
|
455
|
+
item.get("action"): item
|
|
456
|
+
for item in capabilities.get("actions", [])
|
|
457
|
+
if isinstance(item, dict)
|
|
458
|
+
}
|
|
459
|
+
job_open = actions.get("job.open") or {}
|
|
460
|
+
price_raw = int(str((job_open.get("payment") or {}).get("amount") or IMD_PRICE_PER_ACTION_RAW))
|
|
461
|
+
terms_ok = True
|
|
462
|
+
terms_problem = None
|
|
463
|
+
try:
|
|
464
|
+
validate_payment_terms(job_open.get("payment"), where="capabilities")
|
|
465
|
+
except ProviderError as exc:
|
|
466
|
+
terms_ok, terms_problem = False, str(exc)
|
|
467
|
+
balance = int(state["imdBalanceRaw"])
|
|
468
|
+
allowance = int(state["permit2AllowanceRaw"])
|
|
469
|
+
owner = state["address"]
|
|
470
|
+
spent = spent_last_day_raw(owner)
|
|
471
|
+
return {
|
|
472
|
+
"address": owner,
|
|
473
|
+
"network": "ethereum",
|
|
474
|
+
"token": IMD_TOKEN_ADDRESS,
|
|
475
|
+
"imd_balance_raw": str(balance),
|
|
476
|
+
"imd_balance": format_imd(balance),
|
|
477
|
+
"permit2_allowance_raw": str(allowance),
|
|
478
|
+
"permit2_allowance": format_imd(allowance),
|
|
479
|
+
"eth_balance_wei": state["ethBalanceWei"],
|
|
480
|
+
"price_per_action_raw": str(price_raw),
|
|
481
|
+
"price_per_action": format_imd(price_raw),
|
|
482
|
+
"actions_affordable": balance // price_raw if price_raw else 0,
|
|
483
|
+
"actions_covered_by_allowance": allowance // price_raw if price_raw else 0,
|
|
484
|
+
"ready": terms_ok and balance >= price_raw and allowance >= price_raw,
|
|
485
|
+
"needs_imd": balance < price_raw,
|
|
486
|
+
"needs_permit2_allowance": allowance < price_raw,
|
|
487
|
+
"pinned_terms_match": terms_ok,
|
|
488
|
+
"pinned_terms_problem": terms_problem,
|
|
489
|
+
"per_payment_limit": format_imd(IMD_MAX_PER_PAYMENT_RAW),
|
|
490
|
+
"daily_limit": format_imd(daily_limit_raw()),
|
|
491
|
+
"signed_last_24h": format_imd(spent),
|
|
492
|
+
"enabled_actions": list(IMD_ENABLED_ACTIONS),
|
|
493
|
+
"quote_ttl_seconds": job_open.get("quoteTtlSeconds"),
|
|
494
|
+
"limits": capabilities.get("limits"),
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
# --------------------------------------------------------------------------
|
|
499
|
+
# The paid flow
|
|
500
|
+
# --------------------------------------------------------------------------
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
async def preview_paid_action(backend: Any, *, action: str, action_input: dict[str, Any]) -> dict[str, Any]:
|
|
504
|
+
"""Free: IMD's /requests/check plus the price, nothing held or signed."""
|
|
505
|
+
validate_action(action)
|
|
506
|
+
if not isinstance(action_input, dict) or not action_input:
|
|
507
|
+
raise ProviderError(PROVIDER, "input must be a non-empty object (the IMD action body).")
|
|
508
|
+
if len(canonical_json(action_input).encode("utf-8")) > 15_000:
|
|
509
|
+
raise ProviderError(PROVIDER, "IMD request bodies are limited to 16 KiB.")
|
|
510
|
+
status = await account_status(backend)
|
|
511
|
+
check = await check_request(action, action_input)
|
|
512
|
+
blockers = check.get("blockers") if isinstance(check, dict) else None
|
|
513
|
+
amount_raw = _expected_amount_raw(action, action_input, int(status["price_per_action_raw"]))
|
|
514
|
+
return {
|
|
515
|
+
"provider": PROVIDER,
|
|
516
|
+
"network": "ethereum",
|
|
517
|
+
"action": action,
|
|
518
|
+
"input": action_input,
|
|
519
|
+
"input_sha256": input_hash(action, action_input),
|
|
520
|
+
"owner": status["address"],
|
|
521
|
+
"amount_raw": str(amount_raw),
|
|
522
|
+
"amount": format_imd(amount_raw),
|
|
523
|
+
"asset": IMD_TOKEN_ADDRESS,
|
|
524
|
+
"asset_symbol": "IMD",
|
|
525
|
+
"pay_to": sorted(IMD_PAY_TO_ALLOWLIST)[0],
|
|
526
|
+
"check": check,
|
|
527
|
+
"blocked": bool(blockers),
|
|
528
|
+
"account": status,
|
|
529
|
+
"terms": {
|
|
530
|
+
"refundable": False,
|
|
531
|
+
"result_guaranteed": False,
|
|
532
|
+
"public_results": True,
|
|
533
|
+
"note": "IMD job pages, results and artifacts are public. github:true also commits the "
|
|
534
|
+
"output to an IMD-owned public GitHub repository.",
|
|
535
|
+
},
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _expected_amount_raw(action: str, action_input: dict[str, Any], price_raw: int) -> int:
|
|
540
|
+
if action in {"schedule.create", "schedule.topup"}:
|
|
541
|
+
runs = action_input.get("runs")
|
|
542
|
+
if not isinstance(runs, int) or isinstance(runs, bool) or runs < 1:
|
|
543
|
+
raise ProviderError(PROVIDER, "A schedule needs a positive integer 'runs'.")
|
|
544
|
+
amount = price_raw * runs
|
|
545
|
+
else:
|
|
546
|
+
amount = price_raw
|
|
547
|
+
if amount > IMD_MAX_PER_PAYMENT_RAW:
|
|
548
|
+
raise ProviderError(
|
|
549
|
+
PROVIDER,
|
|
550
|
+
f"This payment would be {format_imd(amount)} IMD, above the 5 IMD per-payment limit. "
|
|
551
|
+
"Split it into smaller schedules or top-ups.",
|
|
552
|
+
)
|
|
553
|
+
return amount
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
async def pay_paid_action(
|
|
557
|
+
backend: Any,
|
|
558
|
+
*,
|
|
559
|
+
action: str,
|
|
560
|
+
action_input: dict[str, Any],
|
|
561
|
+
approved_amount_raw: int,
|
|
562
|
+
purpose: str,
|
|
563
|
+
) -> dict[str, Any]:
|
|
564
|
+
"""Quote, challenge, sign twice, submit, then follow the order to admission."""
|
|
565
|
+
validate_action(action)
|
|
566
|
+
owner = await backend.get_address()
|
|
567
|
+
if not owner:
|
|
568
|
+
raise ProviderError(PROVIDER, "The EVM wallet has no address.")
|
|
569
|
+
token = load_or_create_request_token(owner)
|
|
570
|
+
request_key = str(uuid.uuid4())
|
|
571
|
+
|
|
572
|
+
_, quoted = await _request(
|
|
573
|
+
"POST",
|
|
574
|
+
"/requests/quote",
|
|
575
|
+
token=token,
|
|
576
|
+
json_body={"requestKey": request_key, "action": action, "input": action_input},
|
|
577
|
+
expected=(200, 201),
|
|
578
|
+
)
|
|
579
|
+
order = quoted.get("order") if isinstance(quoted, dict) else None
|
|
580
|
+
quote = order.get("quote") if isinstance(order, dict) else None
|
|
581
|
+
if not isinstance(quote, dict) or not order.get("id"):
|
|
582
|
+
raise ProviderError(PROVIDER, "IMD quote response has no order or quote.", details={"response": quoted})
|
|
583
|
+
order_id = str(order["id"])
|
|
584
|
+
validate_payment_terms(quote.get("payment"), where="quote")
|
|
585
|
+
amount_raw = int(str(quote["payment"]["amount"]))
|
|
586
|
+
if amount_raw != int(approved_amount_raw):
|
|
587
|
+
raise ProviderError(
|
|
588
|
+
PROVIDER,
|
|
589
|
+
f"IMD quoted {format_imd(amount_raw)} IMD but {format_imd(approved_amount_raw)} IMD was approved; "
|
|
590
|
+
"nothing was signed. Preview again.",
|
|
591
|
+
details={"order_id": order_id},
|
|
592
|
+
)
|
|
593
|
+
if quote.get("action") != action:
|
|
594
|
+
raise ProviderError(PROVIDER, "IMD quote is for a different action; nothing was signed.")
|
|
595
|
+
expires_at = int(quote.get("expiresAt") or 0)
|
|
596
|
+
if expires_at - int(time.time()) < MIN_QUOTE_REMAINING_SECONDS:
|
|
597
|
+
raise ProviderError(PROVIDER, "IMD quote expires too soon; preview and pay again.")
|
|
598
|
+
|
|
599
|
+
submit_path = f"/requests/{_path_id(order_id)}/submit"
|
|
600
|
+
_, challenge = await _request("POST", submit_path, token=token, expected=(402,))
|
|
601
|
+
requirement = validate_challenge(challenge, quote)
|
|
602
|
+
challenge_quote = challenge.get("quote") if isinstance(challenge.get("quote"), dict) else {}
|
|
603
|
+
if challenge_quote.get("quoteHash") not in (None, quote.get("quoteHash")):
|
|
604
|
+
raise ProviderError(PROVIDER, "IMD challenge quoteHash differs from the quote; nothing was signed.")
|
|
605
|
+
|
|
606
|
+
assert_within_daily_limit(owner, amount_raw)
|
|
607
|
+
permit = build_permit(requirement=requirement, owner=owner, quote_expires_at=expires_at)
|
|
608
|
+
permit_signed = await backend.sign_imd_permit2(permit)
|
|
609
|
+
payment = build_payment(
|
|
610
|
+
challenge=challenge,
|
|
611
|
+
requirement=requirement,
|
|
612
|
+
permit=permit,
|
|
613
|
+
signature=permit_signed["signature"],
|
|
614
|
+
)
|
|
615
|
+
quote_approval = build_quote_approval(challenge=challenge, quote=quote, payment=payment)
|
|
616
|
+
approval_signed = await backend.sign_imd_quote_approval(quote_approval)
|
|
617
|
+
append_journal(
|
|
618
|
+
owner,
|
|
619
|
+
{
|
|
620
|
+
"event": "signed",
|
|
621
|
+
"ts": int(time.time()),
|
|
622
|
+
"order_id": order_id,
|
|
623
|
+
"action": action,
|
|
624
|
+
"amount_raw": str(amount_raw),
|
|
625
|
+
"request_key": request_key,
|
|
626
|
+
"input_sha256": input_hash(action, action_input),
|
|
627
|
+
"purpose": purpose[:200],
|
|
628
|
+
},
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
header = encode_payment_header(payment)
|
|
632
|
+
body = {"quoteSignature": approval_signed["signature"]}
|
|
633
|
+
submit_status = None
|
|
634
|
+
submit_payload: Any = None
|
|
635
|
+
for attempt in range(2):
|
|
636
|
+
# Retries reuse the order and the same bytes, so IMD never charges twice.
|
|
637
|
+
try:
|
|
638
|
+
submit_status, submit_payload = await _request(
|
|
639
|
+
"POST",
|
|
640
|
+
submit_path,
|
|
641
|
+
token=token,
|
|
642
|
+
json_body=body,
|
|
643
|
+
headers={"PAYMENT-SIGNATURE": header},
|
|
644
|
+
expected=(200, 202),
|
|
645
|
+
)
|
|
646
|
+
break
|
|
647
|
+
except ProviderError as exc:
|
|
648
|
+
if not (exc.details or {}).get("transport_error") or attempt == 1:
|
|
649
|
+
raise
|
|
650
|
+
|
|
651
|
+
status = submit_payload if isinstance(submit_payload, dict) else {}
|
|
652
|
+
for _ in range(ORDER_POLL_ATTEMPTS):
|
|
653
|
+
if status.get("status") in {"admitted", "payment_failed", "expired", "refused"}:
|
|
654
|
+
break
|
|
655
|
+
await _sleep(ORDER_POLL_INTERVAL_SECONDS)
|
|
656
|
+
status = await get_order(token, order_id)
|
|
657
|
+
|
|
658
|
+
admission = status.get("admission") if isinstance(status, dict) else None
|
|
659
|
+
result = admission.get("result") if isinstance(admission, dict) else None
|
|
660
|
+
append_journal(
|
|
661
|
+
owner,
|
|
662
|
+
{
|
|
663
|
+
"event": "submitted",
|
|
664
|
+
"ts": int(time.time()),
|
|
665
|
+
"order_id": order_id,
|
|
666
|
+
"status": status.get("status"),
|
|
667
|
+
"job_id": result.get("jobId") if isinstance(result, dict) else None,
|
|
668
|
+
"schedule_id": result.get("scheduleId") if isinstance(result, dict) else None,
|
|
669
|
+
},
|
|
670
|
+
)
|
|
671
|
+
return {
|
|
672
|
+
"provider": PROVIDER,
|
|
673
|
+
"network": "ethereum",
|
|
674
|
+
"action": action,
|
|
675
|
+
"order_id": order_id,
|
|
676
|
+
"submit_http_status": submit_status,
|
|
677
|
+
"status": status.get("status"),
|
|
678
|
+
"payment": status.get("payment"),
|
|
679
|
+
"admission": admission,
|
|
680
|
+
"amount_raw": str(amount_raw),
|
|
681
|
+
"amount": format_imd(amount_raw),
|
|
682
|
+
"pay_to": quote["payment"]["payTo"],
|
|
683
|
+
"links": _result_links(result),
|
|
684
|
+
"next_step": (
|
|
685
|
+
"Follow the job with imd_get_job; work takes minutes to hours."
|
|
686
|
+
if status.get("status") == "admitted"
|
|
687
|
+
else "Payment is still settling; check again with imd_get_order before paying anything again."
|
|
688
|
+
),
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def _result_links(result: Any) -> dict[str, str]:
|
|
693
|
+
if not isinstance(result, dict):
|
|
694
|
+
return {}
|
|
695
|
+
links = {}
|
|
696
|
+
for key in ("statusUrl", "resultUrl", "jobUrl", "attestationUrl"):
|
|
697
|
+
value = result.get(key)
|
|
698
|
+
if isinstance(value, str) and value.startswith("/"):
|
|
699
|
+
links[key] = f"{IMD_API_ORIGIN}{value}"
|
|
700
|
+
return links
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
async def _sleep(seconds: float) -> None:
|
|
704
|
+
import asyncio
|
|
705
|
+
|
|
706
|
+
await asyncio.sleep(seconds)
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
async def order_status(backend: Any, *, order_id: str | None) -> dict[str, Any]:
|
|
710
|
+
owner = await backend.get_address()
|
|
711
|
+
if not owner:
|
|
712
|
+
raise ProviderError(PROVIDER, "The EVM wallet has no address.")
|
|
713
|
+
if order_id:
|
|
714
|
+
token = load_or_create_request_token(owner)
|
|
715
|
+
return {"order_id": order_id, "order": await get_order(token, order_id)}
|
|
716
|
+
return {
|
|
717
|
+
"address": owner,
|
|
718
|
+
"local_orders": [entry for entry in read_journal(owner) if entry.get("event") == "submitted"],
|
|
719
|
+
"paid_by": await get_paid_by(owner),
|
|
720
|
+
}
|