felix-mcp 2.0.129 → 2.0.133
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/README.md +50 -48
- package/dist/arc-first-deposit.js +366 -0
- package/dist/arc-polygon-funding.js +1207 -0
- package/dist/arc-venue-app-policy.js +24 -0
- package/dist/funding.js +27 -2
- package/dist/getting-started-guide.js +58 -57
- package/dist/index.js +1143 -125
- package/dist/manual-policy.js +281 -0
- package/dist/redact-output.js +3 -1
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/index.js
CHANGED
|
@@ -31,7 +31,7 @@ import { acceptedCryptoWithdrawalAmount, assertDeriveDepositReady, assertGasSpon
|
|
|
31
31
|
// executeOwnerEoaCancellation is deliberately NOT imported: see
|
|
32
32
|
// capitalOperationsUnavailable. This client no longer signs a nonce-replacing
|
|
33
33
|
// transfer, because the server has no cancellation protocol to coordinate it.
|
|
34
|
-
polygonFundingNonceUnchanged, relayedFundingNonceUnchanged, waitForRelayedFundingSubmission, waitForPolygonFundingSubmission, waitForDeriveFundingSubmission, executeFundingFeeTransfer, executeFundingIntent, fundingFeeInstructionsMatch, fundingFeeProofIntentToken, fundingRelayReadDenied, FundingFeeProofError, fundingIntentNeedsRefresh, fundingFeeNonceUnchanged, gasSponsorshipNeedsRefresh, inspectFeeSettlementIntent, preflightFundingFeeTransfer, preflightRecoveredFundingFeeTransfer, readArbitrumOwnerUsdcUnits, readDeriveOwnerReturnState, readDeriveReturnGasState, signGasSponsorship, validateFundingFeeTransfer, } from "./funding.js";
|
|
34
|
+
polygonFundingNonceUnchanged, relayedFundingNonceUnchanged, waitForRelayedFundingSubmission, waitForPolygonFundingSubmission, waitForDeriveFundingSubmission, executeFundingFeeTransfer, executeFundingIntent, predictionFundApprovalReady, fundingFeeInstructionsMatch, fundingFeeProofIntentToken, fundingRelayReadDenied, FundingFeeProofError, fundingIntentNeedsRefresh, fundingFeeNonceUnchanged, gasSponsorshipNeedsRefresh, inspectFeeSettlementIntent, preflightFundingFeeTransfer, preflightRecoveredFundingFeeTransfer, readArbitrumOwnerUsdcUnits, readDeriveOwnerReturnState, readDeriveReturnGasState, signGasSponsorship, validateFundingFeeTransfer, } from "./funding.js";
|
|
35
35
|
import { safeClientErrorMessage } from "./safe-error.js";
|
|
36
36
|
import { redactOutput, setOutputCredentialSource, SERVICE_DATA_NOTICE } from "./redact-output.js";
|
|
37
37
|
import { ARC_MIN_MAX_FEE_PER_GAS_WEI, ArcSettlementAmbiguity, ArcSettlementError, arcStageAtLeast, ownerPendingNonce, parseArcAuthorizationPlan, assertBurnIntentMatches, parseArcTransferPlan, parseMintCall, relayRetryStats, settlementReceipt, signAndBroadcastSettlementCall, settlementOwnerAddress, signBurnIntent, unitsToUsd, usdToUnits, waitForSettlementReceipt, } from "./arc-settlement.js";
|
|
@@ -42,9 +42,12 @@ import { driveHlArcReturn } from "./arc-hl-return.js";
|
|
|
42
42
|
import { hyperliquidPort, productionHlArcPorts, resolveHyperliquidEndpoint } from "./arc-hl-return-ports.js";
|
|
43
43
|
import { HYPERCORE_ACTIVATION_NEXT_ACTION, HYPERCORE_DIRECT_CLIENT_ENABLED, driveHypercoreFunding, readCappedText, } from "./arc-hypercore-funding.js";
|
|
44
44
|
import { HYPERCORE_RETURN_CLIENT_ENABLED, driveHypercoreReturn, } from "./arc-hypercore-return.js";
|
|
45
|
-
import { hypercoreAppPolicy, hypercoreReturnAppPolicy } from "./arc-venue-app-policy.js";
|
|
45
|
+
import { hypercoreAppPolicy, hypercoreReturnAppPolicy, polygonFundingAppPolicy } from "./arc-venue-app-policy.js";
|
|
46
|
+
import { ARC_POLYGON_CLIENT_ENABLED, driveArcPolygonFunding, } from "./arc-polygon-funding.js";
|
|
46
47
|
import { INVALIDATION_WRITERS, SHIPPED_INVALIDATION_POLICY, driveSafeInvalidation, isInvalidationWriter, } from "./arc-safe-invalidation.js";
|
|
47
|
-
import { ARC_GATEWAY_DOMAIN, ARC_GATEWAY_MINTER, ARC_GATEWAY_WALLET, ARC_HOME_CHAIN, ARC_HOME_DEPOSIT_CHAINS, ARC_HOME_EXTERNAL_CHAINS, ARC_HOME_WITHDRAWAL_CHAINS, ARC_MAINNET_CHAIN_ID, ARC_USDC, ArcHomeError, arcHomeChainRpcUrl,
|
|
48
|
+
import { ARC_GATEWAY_DOMAIN, ARC_GATEWAY_MINTER, ARC_GATEWAY_WALLET, ARC_HOME_CHAIN, ARC_HOME_DEPOSIT_CHAINS, ARC_HOME_EXTERNAL_CHAINS, ARC_HOME_WITHDRAWAL_CHAINS, ARC_MAINNET_CHAIN_ID, ARC_USDC, ArcHomeError, arcHomeChainRpcUrl, arcUsdToUnits, assertArcHomeBurnIntent, assertArcHomeSafeTx, assertArcHomeWithdrawalSafeTransactions, assertArcHomeSourceCalls, assertArcHubActivation, assertArcHubChallenge, broadcastOwnerCall, parseArcHomeAccount, parseArcHomeRecord, predictArcHomeSafe, publicArcHomeRecord, signArcHomeBurnIntent, signArcHomeOwnerProof, signArcHomeSafeTx, unitsToAmountString, waitForOwnerReceipt, } from "./arc-home.js";
|
|
49
|
+
import { ArcDepositError, RELAY_DEPOSIT_MAX_FROM_AMOUNT, arcDepositSteps, isRequestId, normalizeCurrencyKey, parseArcFunding, parseArcFundingGate, parseRelayCurrencies, parseRelayDeposit, parseRelayDepositStatus, parseRelayEstimate, } from "./arc-first-deposit.js";
|
|
50
|
+
import { ManualPolicyError, tradingPolicyQuestion, verifyManualTradingPolicy } from "./manual-policy.js";
|
|
48
51
|
import { PM_ARC_RETURN_CLIENT_ENABLED, drivePmArcReturn, } from "./arc-pm-return.js";
|
|
49
52
|
import { signHyperliquidAgentApproval } from "./hyperliquid-onboarding.js";
|
|
50
53
|
import { signPreparedSafePolicy, signPreparedWithdrawal } from "./safe-policy.js";
|
|
@@ -123,7 +126,7 @@ export function validatedApiBase(raw = process.env.FELIX_API_URL || `https://${O
|
|
|
123
126
|
return parsed.origin;
|
|
124
127
|
}
|
|
125
128
|
const API = validatedApiBase();
|
|
126
|
-
const MCP_VERSION = "2.0.
|
|
129
|
+
const MCP_VERSION = "2.0.133";
|
|
127
130
|
const AES_GCM_IV_BYTES = 12;
|
|
128
131
|
const AES_GCM_TAG_BYTES = 16;
|
|
129
132
|
const MAX_MONEY_JOURNAL_BYTES = 16 * 1024 * 1024;
|
|
@@ -457,6 +460,18 @@ function maxLocalLiveOrderUsd() {
|
|
|
457
460
|
? Math.min(PRACTICAL_NO_CAP_USD, Math.max(1, configured))
|
|
458
461
|
: PRACTICAL_NO_CAP_USD;
|
|
459
462
|
}
|
|
463
|
+
// A workflow left in_progress resumes automatically only when the process that held it is gone.
|
|
464
|
+
function workflowProcessAlive(pid) {
|
|
465
|
+
if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
|
|
466
|
+
return false;
|
|
467
|
+
try {
|
|
468
|
+
process.kill(pid, 0);
|
|
469
|
+
return true;
|
|
470
|
+
}
|
|
471
|
+
catch (error) {
|
|
472
|
+
return error?.code === "EPERM";
|
|
473
|
+
}
|
|
474
|
+
}
|
|
460
475
|
function workflowStageKey(workflowKey, stage) {
|
|
461
476
|
return `fxwf-${createHash("sha256").update(`${workflowKey}:${stage}`).digest("hex")}`;
|
|
462
477
|
}
|
|
@@ -944,7 +959,7 @@ async function runMoneyWorkflowLocked(workflowKey, operation, payload, action, o
|
|
|
944
959
|
const staleInProgress = existing.status === "in_progress" && existing.process_id !== process.pid;
|
|
945
960
|
const progress = workflowProgress(existing);
|
|
946
961
|
const ownerSetupCanResume = ["create_live_account", "repair_derive_session", "archive_account"].includes(operation)
|
|
947
|
-
&& existing.status === "reconciliation_required"
|
|
962
|
+
&& (existing.status === "reconciliation_required" || (staleInProgress && !workflowProcessAlive(existing.process_id)))
|
|
948
963
|
&& progress.money_moved === false;
|
|
949
964
|
if (!retiredHubStop && (!(options.resumeReconciliation || options.resumable || ownerSetupCanResume)
|
|
950
965
|
|| (existing.status !== "reconciliation_required" && !staleInProgress))) {
|
|
@@ -1885,44 +1900,67 @@ async function arcTransferPrecheck() {
|
|
|
1885
1900
|
}
|
|
1886
1901
|
return undefined;
|
|
1887
1902
|
}
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|| error.chain !== "polygon") {
|
|
1897
|
-
return clientError("account_funding_address_mismatch", "Felix did not confirm the Polygon owner address for this account's funding gate.", "Do not send funds. Retry create_account with the same idempotency_key after Felix resolves the funding address.", { account_id: accountId, money_moved: false });
|
|
1898
|
-
}
|
|
1899
|
-
const amount = (value) => {
|
|
1900
|
-
const parsed = finiteNumber(value);
|
|
1901
|
-
return parsed !== undefined && parsed >= 0 ? parsed : null;
|
|
1902
|
-
};
|
|
1903
|
-
const minimum = amount(error.minimum_deposit_usd);
|
|
1904
|
-
const observed = amount(error.observed_balance_usd);
|
|
1905
|
-
const additional = amount(error.additional_required_usd);
|
|
1906
|
-
if (minimum === null || minimum < 5 || observed === null || additional === null
|
|
1907
|
-
|| Math.abs(additional - Math.max(0, minimum - observed)) > 0.000001) {
|
|
1908
|
-
return clientError("account_funding_response_invalid", "Felix returned inconsistent owner-funding requirements.", "Do not send funds. Retry create_account with the same idempotency_key after Felix resolves the funding gate.", { account_id: accountId, money_moved: false });
|
|
1909
|
-
}
|
|
1910
|
-
return clientError("account_funding_required", "Fund the client-held Polygon owner address before wallet deployment continues.", "After the deposit confirms, retry create_account with this exact idempotency_key. No second account is created.", {
|
|
1903
|
+
// ARC_FIRST_DEPOSIT_MCP_20261117: a new account funds its Arc home exactly like app.felix.trade (Relay deposit into
|
|
1904
|
+
// the account's own CREATE2 Arc home Safe). The MCP never hands out the owner EOA on Polygon as a deposit address.
|
|
1905
|
+
function arcFundingGate(accountId, funding) {
|
|
1906
|
+
const additional = Math.max(funding.additional_required_usd, 0);
|
|
1907
|
+
return clientError("account_funding_required", `Deposit at least $${additional.toFixed(2)} more into this account's Arc home before setup continues `
|
|
1908
|
+
+ `(minimum $${funding.minimum_deposit_usd.toFixed(2)}, now $${funding.observed_balance_usd.toFixed(2)}).`, "Follow deposit_flow: create_deposit gives a one-time payment address for any listed token. When "
|
|
1909
|
+
+ "get_deposit_address reports funded:true, retry create_account with this exact idempotency_key. "
|
|
1910
|
+
+ "No second account is created.", {
|
|
1911
1911
|
account_id: accountId,
|
|
1912
1912
|
account_status: "awaiting_funding",
|
|
1913
|
-
deposit_address: ownerAddress,
|
|
1914
1913
|
funding: {
|
|
1915
|
-
chain: "
|
|
1916
|
-
|
|
1917
|
-
minimum_deposit_usd:
|
|
1918
|
-
observed_balance_usd:
|
|
1914
|
+
chain: "arc",
|
|
1915
|
+
arc_home_safe: funding.safe,
|
|
1916
|
+
minimum_deposit_usd: funding.minimum_deposit_usd,
|
|
1917
|
+
observed_balance_usd: funding.observed_balance_usd,
|
|
1919
1918
|
additional_required_usd: additional,
|
|
1920
|
-
|
|
1919
|
+
funded: false,
|
|
1921
1920
|
},
|
|
1921
|
+
deposit_flow: arcDepositSteps(accountId, funding),
|
|
1922
1922
|
recovery: { retry_tool: "create_account", reuse_same_idempotency_key: true },
|
|
1923
1923
|
money_moved: false,
|
|
1924
1924
|
});
|
|
1925
1925
|
}
|
|
1926
|
+
function arcDepositClientError(error, hint, extra = {}) {
|
|
1927
|
+
return clientError(error instanceof ArcDepositError ? error.code : "arc_deposit_unverified", safeClientErrorMessage(error, "Felix's Arc deposit answer could not be verified."), hint, { ...extra, money_moved: false });
|
|
1928
|
+
}
|
|
1929
|
+
function engineRouteMissing(response) {
|
|
1930
|
+
const meta = isRecord(response._meta) ? response._meta : {};
|
|
1931
|
+
const error = isRecord(response.error) ? response.error : {};
|
|
1932
|
+
return finiteNumber(meta.http_status) === 404 && error.message === "Not Found";
|
|
1933
|
+
}
|
|
1934
|
+
async function readArcFunding(accountId, owner, authKey) {
|
|
1935
|
+
const response = await call("GET", `/v1/arc-home/onboarding/funding${qs({ account_id: accountId })}`, undefined, { authKey, retryOnError: true, timeoutMs: 30_000 });
|
|
1936
|
+
if (response.ok === false)
|
|
1937
|
+
return { response };
|
|
1938
|
+
return { funding: parseArcFunding(response, owner) };
|
|
1939
|
+
}
|
|
1940
|
+
async function createAccountFundingGate(response, accountId, ownerAddress) {
|
|
1941
|
+
const error = isRecord(response.error) ? response.error : {};
|
|
1942
|
+
if (error.code !== "account_funding_required")
|
|
1943
|
+
return undefined;
|
|
1944
|
+
const retry = "Do not send funds. Retry create_account with the same idempotency_key.";
|
|
1945
|
+
if (error.chain === "arc") {
|
|
1946
|
+
try {
|
|
1947
|
+
return arcFundingGate(accountId, parseArcFundingGate(error, ownerAddress));
|
|
1948
|
+
}
|
|
1949
|
+
catch (failure) {
|
|
1950
|
+
return arcDepositClientError(failure, retry, { account_id: accountId });
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
// An engine that still names the owner EOA on Polygon: never show it. Read the Arc home funding instead.
|
|
1954
|
+
try {
|
|
1955
|
+
const read = await readArcFunding(accountId, ownerAddress, START_KEY);
|
|
1956
|
+
if (read.funding && !read.funding.funded)
|
|
1957
|
+
return arcFundingGate(accountId, read.funding);
|
|
1958
|
+
}
|
|
1959
|
+
catch (failure) {
|
|
1960
|
+
return arcDepositClientError(failure, retry, { account_id: accountId });
|
|
1961
|
+
}
|
|
1962
|
+
return clientError("arc_deposit_unavailable", "Felix asked for a deposit but could not name this account's Arc home. Nothing was created.", "Do not send funds anywhere. Retry create_account with the same idempotency_key in a few minutes.", { account_id: accountId, account_status: "awaiting_funding", money_moved: false });
|
|
1963
|
+
}
|
|
1926
1964
|
function createAccountArcError(error) {
|
|
1927
1965
|
return clientError(error instanceof ArcHomeError ? error.code : "arc_home_verification_failed", safeClientErrorMessage(error, "Arc home onboarding could not be verified."), "Retry create_account with the same idempotency_key; do not start another account.", { money_moved: false });
|
|
1928
1966
|
}
|
|
@@ -2043,11 +2081,26 @@ async function createAccountArcHome(workflowKey, context, accountId, ownerKey, l
|
|
|
2043
2081
|
};
|
|
2044
2082
|
let init = context.getCheckpoint("arc_home:challenge");
|
|
2045
2083
|
if (!init) {
|
|
2084
|
+
// ARC_FIRST_DEPOSIT_MCP_20261117: like the app, read the Arc home funding before asking Felix to set it up;
|
|
2085
|
+
// an unfunded home returns the app's Arc deposit flow instead of a refusal from init.
|
|
2086
|
+
try {
|
|
2087
|
+
const read = await readArcFunding(accountId, owner, START_KEY);
|
|
2088
|
+
if (read.funding && !read.funding.funded) {
|
|
2089
|
+
context.saveCheckpoint("arc_home:funding_gate", { status: "awaiting_funding" });
|
|
2090
|
+
return arcFundingGate(accountId, read.funding);
|
|
2091
|
+
}
|
|
2092
|
+
if (read.response && !engineRouteMissing(read.response)) {
|
|
2093
|
+
return { ...read.response, account_id: accountId, money_moved: false };
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
catch (failure) {
|
|
2097
|
+
return arcDepositClientError(failure, "Do not send funds. Retry create_account with the same idempotency_key.", { account_id: accountId });
|
|
2098
|
+
}
|
|
2046
2099
|
init = await call("POST", "/v1/arc-home/onboarding/init", request, {
|
|
2047
2100
|
...auth, idempotencyKey: workflowStageKey(workflowKey, "arc-home:init"),
|
|
2048
2101
|
});
|
|
2049
2102
|
if (init.ok === false)
|
|
2050
|
-
return createAccountFundingGate(init, accountId, owner) || init;
|
|
2103
|
+
return (await createAccountFundingGate(init, accountId, owner)) || init;
|
|
2051
2104
|
}
|
|
2052
2105
|
if (Number(init.expires_at) * 1_000 <= Date.now()
|
|
2053
2106
|
&& !context.getCheckpoint("arc_home:activation")) {
|
|
@@ -2062,7 +2115,7 @@ async function createAccountArcHome(workflowKey, context, accountId, ownerKey, l
|
|
|
2062
2115
|
idempotencyKey: workflowStageKey(workflowKey, `arc-home:init:funded-retry:${createHash("sha256").update(oldToken).digest("hex")}`),
|
|
2063
2116
|
});
|
|
2064
2117
|
if (replacement.ok === false)
|
|
2065
|
-
return createAccountFundingGate(replacement, accountId, owner) || replacement;
|
|
2118
|
+
return (await createAccountFundingGate(replacement, accountId, owner)) || replacement;
|
|
2066
2119
|
init = replacement;
|
|
2067
2120
|
context.saveCheckpoint("arc_home:challenge", init);
|
|
2068
2121
|
context.deleteCheckpoint("arc_home:funding_gate");
|
|
@@ -2088,7 +2141,7 @@ async function createAccountArcHome(workflowKey, context, accountId, ownerKey, l
|
|
|
2088
2141
|
proof_signature: proofSignature,
|
|
2089
2142
|
}, { ...auth, timeoutMs: 120_000 });
|
|
2090
2143
|
if (result.ok === false) {
|
|
2091
|
-
const fundingGate = createAccountFundingGate(result, accountId, owner);
|
|
2144
|
+
const fundingGate = await createAccountFundingGate(result, accountId, owner);
|
|
2092
2145
|
if (fundingGate && isRecord(fundingGate.error)
|
|
2093
2146
|
&& fundingGate.error.code === "account_funding_required") {
|
|
2094
2147
|
context.saveCheckpoint("arc_home:funding_gate", { status: "awaiting_funding" });
|
|
@@ -2146,7 +2199,7 @@ async function createAccountArcHome(workflowKey, context, accountId, ownerKey, l
|
|
|
2146
2199
|
account_id: accountId, activation_token: activation.activationToken, signature,
|
|
2147
2200
|
}, { ...auth, timeoutMs: 120_000 });
|
|
2148
2201
|
if (result.ok === false)
|
|
2149
|
-
return createAccountFundingGate(result, accountId, owner) || result;
|
|
2202
|
+
return (await createAccountFundingGate(result, accountId, owner)) || result;
|
|
2150
2203
|
context.saveCheckpoint("platform-gas:arc_home_activation", {
|
|
2151
2204
|
status: nonEmptyString(result.status) || "unknown", attempt,
|
|
2152
2205
|
});
|
|
@@ -2177,6 +2230,576 @@ async function createAccountArcHome(workflowKey, context, accountId, ownerKey, l
|
|
|
2177
2230
|
return createAccountArcError(error);
|
|
2178
2231
|
}
|
|
2179
2232
|
}
|
|
2233
|
+
async function resolveArcDepositTarget(a) {
|
|
2234
|
+
if (a.account_id !== undefined) {
|
|
2235
|
+
const bad = validateUuid(a, "account_id");
|
|
2236
|
+
if (bad)
|
|
2237
|
+
return bad;
|
|
2238
|
+
}
|
|
2239
|
+
if (isHostedTransport()) {
|
|
2240
|
+
return clientError("local_signer_unavailable", "Deposit addresses are checked against the account's own owner key, which the hosted transport never holds.", "Run Felix MCP locally over stdio, or deposit in the Felix app.", { money_moved: false });
|
|
2241
|
+
}
|
|
2242
|
+
const accountId = nonEmptyString(a.account_id) || runtimeManagedAccountId;
|
|
2243
|
+
if (accountId && !API_KEY_RE.test(START_KEY)) {
|
|
2244
|
+
return clientError("launcher_key_required", "A child account's deposit needs the local launcher credential.", "Restart Felix MCP with the launcher key, then retry.", { money_moved: false });
|
|
2245
|
+
}
|
|
2246
|
+
try {
|
|
2247
|
+
const ownerKey = await arcHomeOwnerKeyFor(accountId);
|
|
2248
|
+
if (!EVM_PRIVATE_KEY_RE.test(ownerKey)) {
|
|
2249
|
+
return clientError("client_signature_required", "This account's owner key is not available on this machine, so its Arc home cannot be verified.", "Use the trusted local launcher that created the account. Nothing was created.", { money_moved: false });
|
|
2250
|
+
}
|
|
2251
|
+
return { accountId, owner: ownerAddressForPrivateKey(ownerKey), authKey: accountId ? START_KEY : undefined };
|
|
2252
|
+
}
|
|
2253
|
+
catch (error) {
|
|
2254
|
+
return clientError("account_owner_unavailable", safeClientErrorMessage(error, "The account owner could not be resolved."), "Retry shortly. Nothing was created.", { money_moved: false });
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
function isArcDepositTarget(value) {
|
|
2258
|
+
return typeof value.owner === "string" && value.ok !== false;
|
|
2259
|
+
}
|
|
2260
|
+
async function readRelayCurrencies(target) {
|
|
2261
|
+
const response = await call("GET", "/v1/arc-home/relay-deposits/currencies", undefined, { authKey: target.authKey, timeoutMs: 30_000 });
|
|
2262
|
+
if (response.ok === false)
|
|
2263
|
+
return response;
|
|
2264
|
+
try {
|
|
2265
|
+
return parseRelayCurrencies(response);
|
|
2266
|
+
}
|
|
2267
|
+
catch (error) {
|
|
2268
|
+
return arcDepositClientError(error, "Retry shortly. Nothing was created.");
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
function depositAmountArg(value) {
|
|
2272
|
+
const amount = typeof value === "string" && /^[0-9]+(\.[0-9]+)?$/.test(value.trim()) ? Number(value)
|
|
2273
|
+
: typeof value === "number" ? value : NaN;
|
|
2274
|
+
return Number.isFinite(amount) && amount > 0 && amount < RELAY_DEPOSIT_MAX_FROM_AMOUNT ? amount : undefined;
|
|
2275
|
+
}
|
|
2276
|
+
async function readArcHomeState(target) {
|
|
2277
|
+
const account = await call("GET", `/v1/arc-home/account${qs({ account_id: target.accountId })}`, undefined, { authKey: target.authKey, timeoutMs: 30_000 });
|
|
2278
|
+
if (account.ok === false)
|
|
2279
|
+
return { error: account };
|
|
2280
|
+
try {
|
|
2281
|
+
const parsed = parseArcHomeAccount(account, target.owner);
|
|
2282
|
+
if (parsed.registered && parsed.verified && parsed.safe && parsed.chain_id === ARC_MAINNET_CHAIN_ID) {
|
|
2283
|
+
return { ready: true, safe: parsed.safe };
|
|
2284
|
+
}
|
|
2285
|
+
if (parsed.registered) {
|
|
2286
|
+
return { error: clientError("arc_home_verification_incomplete", "This account's Arc home is registered but not verified yet. Nothing was created.", "Retry shortly; if this persists, resume create_account with its idempotency_key.", { money_moved: false }) };
|
|
2287
|
+
}
|
|
2288
|
+
const read = await readArcFunding(target.accountId, target.owner, target.authKey);
|
|
2289
|
+
if (read.response) {
|
|
2290
|
+
const error = isRecord(read.response.error) ? read.response.error : {};
|
|
2291
|
+
if (finiteNumber(read.response._meta?.http_status) === 404
|
|
2292
|
+
&& error.message !== "Not Found") {
|
|
2293
|
+
return { error: clientError("account_owner_not_bound", "No device owner is bound to this account yet, so it has no Arc home to deposit into.", "Run create_account; it binds the owner first and then returns the deposit steps. Nothing was created.", { account_id: target.accountId ?? null, money_moved: false }) };
|
|
2294
|
+
}
|
|
2295
|
+
return { error: { ...read.response, money_moved: false } };
|
|
2296
|
+
}
|
|
2297
|
+
return { ready: false, funding: read.funding };
|
|
2298
|
+
}
|
|
2299
|
+
catch (error) {
|
|
2300
|
+
return { error: arcDepositClientError(error, "Do not send funds. Retry shortly.") };
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
async function getArcDepositView(a) {
|
|
2304
|
+
const target = await resolveArcDepositTarget(a);
|
|
2305
|
+
if (!isArcDepositTarget(target))
|
|
2306
|
+
return target;
|
|
2307
|
+
const accountRef = target.accountId ? { account_id: target.accountId } : {};
|
|
2308
|
+
if (a.list_currencies === true) {
|
|
2309
|
+
const currencies = await readRelayCurrencies(target);
|
|
2310
|
+
if (!Array.isArray(currencies))
|
|
2311
|
+
return currencies;
|
|
2312
|
+
return { ok: true, provider: "relay", settles_into: { chain: "arc", token: "USDC" }, currencies,
|
|
2313
|
+
next: "Pass one key as from_currency to get_deposit_address (preview) or create_deposit (payment address)." };
|
|
2314
|
+
}
|
|
2315
|
+
if (a.request_id !== undefined) {
|
|
2316
|
+
if (!isRequestId(a.request_id)) {
|
|
2317
|
+
return clientError("invalid_argument", "request_id must be the 0x-prefixed 64-hex request_id from create_deposit.");
|
|
2318
|
+
}
|
|
2319
|
+
const requestId = String(a.request_id).toLowerCase();
|
|
2320
|
+
const response = await call("GET", `/v1/arc-home/relay-deposits/${enc(requestId)}${qs({ account_id: target.accountId })}`, undefined, { authKey: target.authKey, timeoutMs: 30_000 });
|
|
2321
|
+
if (response.ok === false)
|
|
2322
|
+
return { ...response, money_moved: false };
|
|
2323
|
+
let status;
|
|
2324
|
+
try {
|
|
2325
|
+
status = parseRelayDepositStatus(response, requestId);
|
|
2326
|
+
}
|
|
2327
|
+
catch (error) {
|
|
2328
|
+
return arcDepositClientError(error, "Retry shortly.");
|
|
2329
|
+
}
|
|
2330
|
+
const home = await readArcHomeState(target);
|
|
2331
|
+
const arcHome = "error" in home ? null : home.ready
|
|
2332
|
+
? { status: "ready", arc_home_safe: home.safe }
|
|
2333
|
+
: { status: "not_set_up", arc_home_safe: home.funding.safe, funded: home.funding.funded,
|
|
2334
|
+
minimum_deposit_usd: home.funding.minimum_deposit_usd,
|
|
2335
|
+
observed_balance_usd: home.funding.observed_balance_usd,
|
|
2336
|
+
additional_required_usd: home.funding.additional_required_usd };
|
|
2337
|
+
const next = status.status === "finished"
|
|
2338
|
+
? (arcHome && arcHome.status === "not_set_up"
|
|
2339
|
+
? (arcHome.funded ? "Funded. Retry create_account with its original idempotency_key to finish setup."
|
|
2340
|
+
: "This deposit finished but the Arc home still needs more before setup. Make another deposit.")
|
|
2341
|
+
: "Credited to your Arc home.")
|
|
2342
|
+
: ["refunded", "failed", "expired"].includes(status.status)
|
|
2343
|
+
? "This deposit did not complete. Create a new one with create_deposit if you still want to deposit."
|
|
2344
|
+
: "Still in progress. Check again in a minute.";
|
|
2345
|
+
return { ok: true, ...status, arc_home: arcHome, next, money_moved: false };
|
|
2346
|
+
}
|
|
2347
|
+
if (a.from_currency !== undefined || a.from_amount !== undefined) {
|
|
2348
|
+
const currency = normalizeCurrencyKey(a.from_currency);
|
|
2349
|
+
const amount = depositAmountArg(a.from_amount);
|
|
2350
|
+
if (!currency || amount === undefined) {
|
|
2351
|
+
return clientError("invalid_argument", "from_currency (a key from list_currencies) and a positive from_amount are both required for a preview.");
|
|
2352
|
+
}
|
|
2353
|
+
const response = await call("POST", "/v1/arc-home/relay-deposits/estimate", { ...accountRef, from_currency: currency, from_amount: amount }, { authKey: target.authKey, timeoutMs: 30_000 });
|
|
2354
|
+
if (response.ok === false)
|
|
2355
|
+
return { ...response, money_moved: false };
|
|
2356
|
+
try {
|
|
2357
|
+
const estimate = parseRelayEstimate(response, amount);
|
|
2358
|
+
return { ok: true, preview: true, from_currency: currency, ...estimate,
|
|
2359
|
+
settles_into: { chain: "arc", token: "USDC" },
|
|
2360
|
+
next: { tool: "create_deposit",
|
|
2361
|
+
arguments: { ...accountRef, from_currency: currency, from_amount: amount, idempotency_key: "<new unique key>" } },
|
|
2362
|
+
money_moved: false };
|
|
2363
|
+
}
|
|
2364
|
+
catch (error) {
|
|
2365
|
+
return arcDepositClientError(error, "Retry shortly.");
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
const home = await readArcHomeState(target);
|
|
2369
|
+
if ("error" in home)
|
|
2370
|
+
return home.error;
|
|
2371
|
+
const safe = home.ready ? home.safe : home.funding.safe;
|
|
2372
|
+
return {
|
|
2373
|
+
ok: true,
|
|
2374
|
+
home_chain: "arc",
|
|
2375
|
+
...accountRef,
|
|
2376
|
+
arc_home: home.ready
|
|
2377
|
+
? { status: "ready", safe, verified: true }
|
|
2378
|
+
: { status: "not_set_up", safe, verified: false, counterfactual: true,
|
|
2379
|
+
funded: home.funding.funded,
|
|
2380
|
+
minimum_deposit_usd: home.funding.minimum_deposit_usd,
|
|
2381
|
+
observed_balance_usd: home.funding.observed_balance_usd,
|
|
2382
|
+
additional_required_usd: home.funding.additional_required_usd,
|
|
2383
|
+
next: home.funding.funded
|
|
2384
|
+
? "Funded. Retry create_account with its original idempotency_key to finish setup."
|
|
2385
|
+
: "Deposit with create_deposit, then retry create_account with its original idempotency_key." },
|
|
2386
|
+
deposit_flow: arcDepositSteps(target.accountId, home.ready ? undefined : home.funding),
|
|
2387
|
+
direct_arc_usdc: { network: "Arc", chain_id: ARC_MAINNET_CHAIN_ID, token: "USDC", address: safe,
|
|
2388
|
+
note: "Only USDC already on Arc may be sent here directly. Every other token or network uses create_deposit." },
|
|
2389
|
+
verified_locally: "The Arc home Safe address was re-derived from this account's own owner key.",
|
|
2390
|
+
};
|
|
2391
|
+
}
|
|
2392
|
+
async function createArcDeposit(a) {
|
|
2393
|
+
const target = await resolveArcDepositTarget(a);
|
|
2394
|
+
if (!isArcDepositTarget(target))
|
|
2395
|
+
return target;
|
|
2396
|
+
const workflowKey = requiredWorkflowKey(a);
|
|
2397
|
+
const currencyKey = normalizeCurrencyKey(a.from_currency);
|
|
2398
|
+
const amount = depositAmountArg(a.from_amount);
|
|
2399
|
+
if (!workflowKey) {
|
|
2400
|
+
return clientError("invalid_argument", "idempotency_key is required and must be 1-128 printable ASCII characters.");
|
|
2401
|
+
}
|
|
2402
|
+
if (!currencyKey || amount === undefined) {
|
|
2403
|
+
return clientError("invalid_argument", "from_currency (a key from get_deposit_address list_currencies) and a positive from_amount are required.");
|
|
2404
|
+
}
|
|
2405
|
+
const currencies = await readRelayCurrencies(target);
|
|
2406
|
+
if (!Array.isArray(currencies))
|
|
2407
|
+
return currencies;
|
|
2408
|
+
const currency = currencies.find((row) => row.key === currencyKey);
|
|
2409
|
+
if (!currency) {
|
|
2410
|
+
return clientError("relay_source_currency_unsupported", `${currencyKey} is not an accepted deposit token.`, "Call get_deposit_address with list_currencies:true for the accepted keys.", { money_moved: false });
|
|
2411
|
+
}
|
|
2412
|
+
const home = await readArcHomeState(target);
|
|
2413
|
+
if ("error" in home)
|
|
2414
|
+
return home.error;
|
|
2415
|
+
const accountRef = target.accountId ? { account_id: target.accountId } : {};
|
|
2416
|
+
const response = await call("POST", "/v1/arc-home/relay-deposits", { ...accountRef, from_currency: currencyKey, from_amount: amount }, { authKey: target.authKey, idempotencyKey: workflowStageKey(workflowKey, "arc-relay-deposit"),
|
|
2417
|
+
timeoutMs: 60_000 });
|
|
2418
|
+
if (response.ok === false)
|
|
2419
|
+
return { ...response, money_moved: false };
|
|
2420
|
+
let instruction;
|
|
2421
|
+
try {
|
|
2422
|
+
instruction = parseRelayDeposit(response, { owner: target.owner, currency, fromAmount: amount,
|
|
2423
|
+
firstDeposit: !home.ready });
|
|
2424
|
+
}
|
|
2425
|
+
catch (error) {
|
|
2426
|
+
const code = error instanceof ArcDepositError ? error.code : "";
|
|
2427
|
+
return arcDepositClientError(error, code === "relay_deposit_below_minimum"
|
|
2428
|
+
? "Do not send funds. Create a new deposit with a larger amount and a new idempotency_key."
|
|
2429
|
+
: code === "relay_deposit_expired"
|
|
2430
|
+
? "Do not send funds. Create a new deposit with a new idempotency_key."
|
|
2431
|
+
: "Do not send funds to any address from this answer. Retry later; if it repeats, contact Felix support.");
|
|
2432
|
+
}
|
|
2433
|
+
if (instruction.replayed) {
|
|
2434
|
+
// The engine returns the saved instruction on replay. Pay details are shown again only while Relay still
|
|
2435
|
+
// reports it unpaid; otherwise this is tracking, never a second payment request.
|
|
2436
|
+
const current = await call("GET", `/v1/arc-home/relay-deposits/${enc(instruction.request_id)}${qs({ account_id: target.accountId })}`, undefined, { authKey: target.authKey, timeoutMs: 30_000 });
|
|
2437
|
+
let tracked;
|
|
2438
|
+
try {
|
|
2439
|
+
tracked = current.ok === false ? undefined : parseRelayDepositStatus(current, instruction.request_id);
|
|
2440
|
+
}
|
|
2441
|
+
catch {
|
|
2442
|
+
tracked = undefined;
|
|
2443
|
+
}
|
|
2444
|
+
if (!tracked || tracked.status !== "waiting" || tracked.payment_seen) {
|
|
2445
|
+
return {
|
|
2446
|
+
ok: true,
|
|
2447
|
+
status: tracked ? tracked.status : "status_unavailable",
|
|
2448
|
+
request_id: instruction.request_id,
|
|
2449
|
+
replayed: true,
|
|
2450
|
+
...(tracked ? { tracking: tracked } : {}),
|
|
2451
|
+
settles_into: instruction.settles_into,
|
|
2452
|
+
next: tracked
|
|
2453
|
+
? "This deposit already exists and is no longer waiting for payment. Do not pay it again; track it with get_deposit_address request_id."
|
|
2454
|
+
: "This deposit already exists but its status could not be read. Do not pay until get_deposit_address request_id shows it is still waiting.",
|
|
2455
|
+
money_moved: false,
|
|
2456
|
+
};
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
return {
|
|
2460
|
+
ok: true,
|
|
2461
|
+
status: "awaiting_payment",
|
|
2462
|
+
request_id: instruction.request_id,
|
|
2463
|
+
pay: {
|
|
2464
|
+
send_exactly: `${instruction.from_amount} ${instruction.ticker}`,
|
|
2465
|
+
token: instruction.ticker,
|
|
2466
|
+
network: instruction.chain_name,
|
|
2467
|
+
to: instruction.pay_to,
|
|
2468
|
+
before: instruction.payment_expires_at,
|
|
2469
|
+
},
|
|
2470
|
+
delivers: {
|
|
2471
|
+
expected_usdc: instruction.to_amount,
|
|
2472
|
+
minimum_usdc: instruction.minimum_to_amount,
|
|
2473
|
+
settles_into: instruction.settles_into,
|
|
2474
|
+
estimated_seconds: instruction.estimated_seconds,
|
|
2475
|
+
},
|
|
2476
|
+
first_deposit: !home.ready,
|
|
2477
|
+
replayed: instruction.replayed,
|
|
2478
|
+
rules: [
|
|
2479
|
+
`Send only ${instruction.ticker} on ${instruction.chain_name}, from a wallet you control.`,
|
|
2480
|
+
"Pay before the window ends; an unpaid instruction expires. A refund goes back to the sending wallet.",
|
|
2481
|
+
"Use this address for this deposit only.",
|
|
2482
|
+
],
|
|
2483
|
+
next: !home.ready
|
|
2484
|
+
? "Track with get_deposit_address request_id. When it reports funded, retry create_account with its original idempotency_key."
|
|
2485
|
+
: "Track with get_deposit_address request_id.",
|
|
2486
|
+
cancel: { tool: "cancel_deposit", arguments: { ...accountRef, request_id: instruction.request_id },
|
|
2487
|
+
note: "Only while unpaid." },
|
|
2488
|
+
money_moved: false,
|
|
2489
|
+
};
|
|
2490
|
+
}
|
|
2491
|
+
async function cancelArcDeposit(a) {
|
|
2492
|
+
const target = await resolveArcDepositTarget(a);
|
|
2493
|
+
if (!isArcDepositTarget(target))
|
|
2494
|
+
return target;
|
|
2495
|
+
if (!isRequestId(a.request_id)) {
|
|
2496
|
+
return clientError("invalid_argument", "request_id must be the 0x-prefixed 64-hex request_id from create_deposit.");
|
|
2497
|
+
}
|
|
2498
|
+
const requestId = String(a.request_id).toLowerCase();
|
|
2499
|
+
const response = await call("POST", `/v1/arc-home/relay-deposits/${enc(requestId)}/cancel`, target.accountId ? { account_id: target.accountId } : {}, { authKey: target.authKey, timeoutMs: 30_000, retryOnError: false });
|
|
2500
|
+
if (response.ok === false)
|
|
2501
|
+
return { ...response, money_moved: false };
|
|
2502
|
+
if (response.cancelled !== true) {
|
|
2503
|
+
return clientError("deposit_cancel_unconfirmed", "Felix did not confirm the cancellation. Treat the deposit as open.", "Check it with get_deposit_address request_id before sending anything.", { money_moved: false });
|
|
2504
|
+
}
|
|
2505
|
+
return { ok: true, request_id: requestId, cancelled: true, status: "expired",
|
|
2506
|
+
note: "Do not send funds to that payment address.", money_moved: false };
|
|
2507
|
+
}
|
|
2508
|
+
// MANUAL_POLICY_MCP_20261117 (owner decision 2026-11-17): the account owner's Manual trading policy, the app's
|
|
2509
|
+
// "device trading policy", set up and renewed by the MCP so an owner never has to visit the site. Every manual
|
|
2510
|
+
// order and fund-from-Home order runs under it. The text is verified line by line before the local owner signs.
|
|
2511
|
+
const manualPolicyReadyUntil = new Map();
|
|
2512
|
+
const MANUAL_POLICY_READY_TTL_MS = 10 * 60_000;
|
|
2513
|
+
const MANUAL_POLICY_RENEW_SECONDS = 3 * 86_400;
|
|
2514
|
+
let tradingPolicyAskServer;
|
|
2515
|
+
const declinedTradingPolicyTerms = new Set();
|
|
2516
|
+
const approvedTradingPolicyTerms = new Set();
|
|
2517
|
+
// Terms whose question was handed to the agent to relay (the client could not show it): a relayed yes for them
|
|
2518
|
+
// always re-checks, even inside the readiness cache (Opus QA r10).
|
|
2519
|
+
const relayedTradingPolicyTerms = new Set();
|
|
2520
|
+
// One signature + submit per set of terms at a time; concurrent orders share it (Opus QA r9).
|
|
2521
|
+
const tradingPolicySubmitsInFlight = new Map();
|
|
2522
|
+
/** Whether the client can show a FORM question (MCP elicitation form mode; a bare {} means form). URL-only clients
|
|
2523
|
+
* cannot, so they use the relayed question (Opus QA r7 F2). */
|
|
2524
|
+
function clientCanAskTradingPolicyForm() {
|
|
2525
|
+
const server = tradingPolicyAskServer;
|
|
2526
|
+
if (!server || isHostedTransport())
|
|
2527
|
+
return false;
|
|
2528
|
+
const elicitation = server.getClientCapabilities()?.elicitation;
|
|
2529
|
+
if (!elicitation || typeof elicitation !== "object")
|
|
2530
|
+
return false;
|
|
2531
|
+
return Object.keys(elicitation).length === 0 || isRecord(elicitation.form);
|
|
2532
|
+
}
|
|
2533
|
+
// One owner question at a time per set of terms; concurrent orders share the same answer (Opus QA r7).
|
|
2534
|
+
const tradingPolicyQuestionsInFlight = new Map();
|
|
2535
|
+
// The owner may need a few minutes to read the fee terms (the SDK default is 60 s).
|
|
2536
|
+
const TRADING_POLICY_QUESTION_TIMEOUT_MS = 10 * 60_000;
|
|
2537
|
+
async function askOwnerForTradingPolicy(question) {
|
|
2538
|
+
const server = tradingPolicyAskServer;
|
|
2539
|
+
if (!server || !clientCanAskTradingPolicyForm())
|
|
2540
|
+
return "unavailable";
|
|
2541
|
+
try {
|
|
2542
|
+
const answer = await server.elicitInput({
|
|
2543
|
+
message: question,
|
|
2544
|
+
requestedSchema: {
|
|
2545
|
+
type: "object",
|
|
2546
|
+
properties: {
|
|
2547
|
+
accept_trading_policy: {
|
|
2548
|
+
type: "boolean",
|
|
2549
|
+
title: "I allow this trading policy",
|
|
2550
|
+
description: "Felix MCP signs this account's trading policy with your owner key. Signing moves no money.",
|
|
2551
|
+
},
|
|
2552
|
+
},
|
|
2553
|
+
required: ["accept_trading_policy"],
|
|
2554
|
+
},
|
|
2555
|
+
}, { timeout: TRADING_POLICY_QUESTION_TIMEOUT_MS });
|
|
2556
|
+
if (answer.action === "accept") {
|
|
2557
|
+
return answer.content?.accept_trading_policy === true ? "yes" : "no";
|
|
2558
|
+
}
|
|
2559
|
+
// An explicit decline is a "no"; closing the dialog is not an answer (asked again next time).
|
|
2560
|
+
return answer.action === "decline" ? "no" : "closed";
|
|
2561
|
+
}
|
|
2562
|
+
catch (error) {
|
|
2563
|
+
// Opus QA r8 F1: only a client that cannot show the question at all falls back to the relayed yes. A question
|
|
2564
|
+
// that was delivered but timed out or failed is "not answered": no relayed fallback, the owner is asked again.
|
|
2565
|
+
const code = error instanceof McpError ? error.code : undefined;
|
|
2566
|
+
return code === ErrorCode.MethodNotFound ? "unavailable" : "closed";
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
async function ensureManualTradingPolicy(accountId, ownerKey, authKey, consent = {}) {
|
|
2570
|
+
const cacheKey = accountId || `self:${(authKey || getKey()).slice(0, 12)}`;
|
|
2571
|
+
// A call carrying the owner's relayed yes always re-checks (it may be the yes for a pending renewal).
|
|
2572
|
+
const relayedYes = consent.accepted === true
|
|
2573
|
+
&& (!clientCanAskTradingPolicyForm() || (consent.termsId !== undefined && relayedTradingPolicyTerms.has(consent.termsId)));
|
|
2574
|
+
if (!relayedYes && (manualPolicyReadyUntil.get(cacheKey) || 0) > Date.now()) {
|
|
2575
|
+
return { ok: true, status: "ready", cached: true };
|
|
2576
|
+
}
|
|
2577
|
+
if (!EVM_PRIVATE_KEY_RE.test(ownerKey)) {
|
|
2578
|
+
return clientError("client_signature_required", "The account owner's key is not on this machine, so its trading policy cannot be signed.", "Use the trusted local launcher that created the account. No order was sent.", { money_moved: false });
|
|
2579
|
+
}
|
|
2580
|
+
let resolvedAccount = accountId;
|
|
2581
|
+
if (!resolvedAccount) {
|
|
2582
|
+
const subscription = await currentSubscriptionSnapshot();
|
|
2583
|
+
const access = isRecord(subscription.key_access) ? subscription.key_access : {};
|
|
2584
|
+
resolvedAccount = nonEmptyString(access.account_id);
|
|
2585
|
+
}
|
|
2586
|
+
if (!resolvedAccount || !UUID_RE.test(resolvedAccount)) {
|
|
2587
|
+
return clientError("account_unresolved", "Felix could not confirm which account this trading policy is for.", "Retry shortly. No order was sent.", { money_moved: false });
|
|
2588
|
+
}
|
|
2589
|
+
const auth = { authKey, retryOnError: false, timeoutMs: 30_000 };
|
|
2590
|
+
const status = await call("GET", `/v1/manual/trading-policy${qs({ account_id: accountId })}`, undefined, auth);
|
|
2591
|
+
if (status.ok === false)
|
|
2592
|
+
return status;
|
|
2593
|
+
const ownerAddress = ownerAddressForPrivateKey(ownerKey).toLowerCase();
|
|
2594
|
+
if (status.account_id !== resolvedAccount
|
|
2595
|
+
|| (status.owner !== undefined && String(status.owner).toLowerCase() !== ownerAddress)) {
|
|
2596
|
+
return clientError("trading_policy_status_invalid", "Felix returned a trading-policy status for another account or owner. Nothing was signed.", "Retry shortly. No order was sent.", { money_moved: false });
|
|
2597
|
+
}
|
|
2598
|
+
const policy = isRecord(status.public_policy) ? status.public_policy : {};
|
|
2599
|
+
const expiresAt = finiteNumber(policy.mandate_expires_at);
|
|
2600
|
+
const now = Math.floor(Date.now() / 1000);
|
|
2601
|
+
const ready = status.ready === true && status.registered === true
|
|
2602
|
+
&& status.lighter_integrator_consent_required !== true && status.fast_custody_upgrade_available !== true;
|
|
2603
|
+
if (ready && expiresAt !== undefined && expiresAt > now + MANUAL_POLICY_RENEW_SECONDS) {
|
|
2604
|
+
manualPolicyReadyUntil.set(cacheKey, Math.min(Date.now() + MANUAL_POLICY_READY_TTL_MS, (expiresAt - MANUAL_POLICY_RENEW_SECONDS) * 1_000));
|
|
2605
|
+
return { ok: true, status: "ready", mandate_expires_at: expiresAt };
|
|
2606
|
+
}
|
|
2607
|
+
const renewal = ready;
|
|
2608
|
+
// Opus QA r9: an existing policy that is still valid but needs the Lighter consent or fast-custody upgrade keeps
|
|
2609
|
+
// trading while the upgrade waits for the owner (the engine itself gates only what the upgrade adds).
|
|
2610
|
+
const upgrade = !ready && status.ready === true && status.registered === true
|
|
2611
|
+
&& expiresAt !== undefined && expiresAt > now;
|
|
2612
|
+
const keepsTrading = renewal || upgrade;
|
|
2613
|
+
const prepared = await call("POST", "/v1/manual/trading-policy/prepare", { ...(accountId ? { account_id: accountId } : {}), ...(renewal ? { renew: true } : {}) }, { ...auth, timeoutMs: 60_000 });
|
|
2614
|
+
if (prepared.ok === false)
|
|
2615
|
+
return prepared;
|
|
2616
|
+
if (typeof prepared.message !== "string") {
|
|
2617
|
+
// Status instead of a draft: already ready (or a renewal is not due yet).
|
|
2618
|
+
if (prepared.ready === true) {
|
|
2619
|
+
manualPolicyReadyUntil.set(cacheKey, Date.now() + MANUAL_POLICY_READY_TTL_MS);
|
|
2620
|
+
return { ok: true, status: "ready" };
|
|
2621
|
+
}
|
|
2622
|
+
return clientError("trading_policy_unavailable", "Felix did not return a trading policy to sign.", "Retry shortly. No order was sent.", { money_moved: false });
|
|
2623
|
+
}
|
|
2624
|
+
let verified;
|
|
2625
|
+
try {
|
|
2626
|
+
verified = verifyManualTradingPolicy(prepared, {
|
|
2627
|
+
accountId: resolvedAccount, ownerPrivateKey: ownerKey,
|
|
2628
|
+
renewalOf: renewal ? (expiresAt ?? -1) : null,
|
|
2629
|
+
});
|
|
2630
|
+
}
|
|
2631
|
+
catch (error) {
|
|
2632
|
+
return clientError(error instanceof ManualPolicyError ? error.code : "trading_policy_unverified", safeClientErrorMessage(error, "Felix's trading policy could not be verified."), "Nothing was signed and no order was sent. Retry shortly; contact Felix support if it repeats.", { money_moved: false });
|
|
2633
|
+
}
|
|
2634
|
+
const question = tradingPolicyQuestion(verified.summary);
|
|
2635
|
+
const termsId = verified.summary.terms_id;
|
|
2636
|
+
const { terms_id: _hiddenTermsId, ...summaryWithoutId } = verified.summary;
|
|
2637
|
+
void _hiddenTermsId;
|
|
2638
|
+
// Opus QA r6 F1: when the client can ask the owner, only the owner's answer counts (a relayed flag is ignored), and
|
|
2639
|
+
// a "no" to these exact terms is remembered for this process and never overridden by the agent.
|
|
2640
|
+
// A renewal while the current policy is still valid never blocks trading: without a yes the order goes ahead under
|
|
2641
|
+
// the current policy and the renewal stays pending (Opus QA r7).
|
|
2642
|
+
const renewalPending = (reason) => {
|
|
2643
|
+
// Never cache "ready" past the current policy's own expiry (Opus QA r10).
|
|
2644
|
+
manualPolicyReadyUntil.set(cacheKey, Math.min(Date.now() + MANUAL_POLICY_READY_TTL_MS, expiresAt !== undefined ? expiresAt * 1_000 : 0));
|
|
2645
|
+
if (reason === "consent_required")
|
|
2646
|
+
relayedTradingPolicyTerms.add(termsId);
|
|
2647
|
+
return renewalPendingResult(reason);
|
|
2648
|
+
};
|
|
2649
|
+
const renewalPendingResult = (reason) => ({
|
|
2650
|
+
ok: true, status: "ready_renewal_pending", renewal_status: reason, mandate_expires_at: expiresAt,
|
|
2651
|
+
pending_kind: renewal ? "renewal" : "upgrade",
|
|
2652
|
+
...(reason === "consent_required" ? { renewal_question: question, renewal_terms_id: termsId } : {}),
|
|
2653
|
+
note: renewal
|
|
2654
|
+
? "The current trading policy is still valid; its renewal needs the owner's yes before it expires."
|
|
2655
|
+
: "The current trading policy is still valid; its update (new venue terms) needs the owner's yes.",
|
|
2656
|
+
money_moved: false,
|
|
2657
|
+
});
|
|
2658
|
+
if (declinedTradingPolicyTerms.has(termsId) && keepsTrading)
|
|
2659
|
+
return renewalPending("declined");
|
|
2660
|
+
if (declinedTradingPolicyTerms.has(termsId)) {
|
|
2661
|
+
return clientError("trading_policy_declined", "The owner declined this trading policy. Nothing was signed.", "The owner said no to these terms in this session. They are asked again after the MCP client restarts; "
|
|
2662
|
+
+ "do not retry on their behalf.", { money_moved: false, trading_policy: summaryWithoutId });
|
|
2663
|
+
}
|
|
2664
|
+
let allowed = false;
|
|
2665
|
+
if (clientCanAskTradingPolicyForm()) {
|
|
2666
|
+
// Only the owner's own answer counts; a relayed flag is ignored.
|
|
2667
|
+
let pending = approvedTradingPolicyTerms.has(termsId)
|
|
2668
|
+
? Promise.resolve("yes") : tradingPolicyQuestionsInFlight.get(termsId);
|
|
2669
|
+
if (!pending) {
|
|
2670
|
+
pending = askOwnerForTradingPolicy(question).finally(() => tradingPolicyQuestionsInFlight.delete(termsId));
|
|
2671
|
+
tradingPolicyQuestionsInFlight.set(termsId, pending);
|
|
2672
|
+
}
|
|
2673
|
+
const answer = await pending;
|
|
2674
|
+
if (answer === "no")
|
|
2675
|
+
declinedTradingPolicyTerms.add(termsId);
|
|
2676
|
+
if (answer === "yes")
|
|
2677
|
+
approvedTradingPolicyTerms.add(termsId);
|
|
2678
|
+
if (declinedTradingPolicyTerms.has(termsId)) {
|
|
2679
|
+
if (keepsTrading)
|
|
2680
|
+
return renewalPending("declined");
|
|
2681
|
+
return clientError("trading_policy_declined", "The owner did not allow the trading policy. Nothing was signed.", "Manual orders need it; the owner can be asked again in a new session if they change their mind.", { money_moved: false, trading_policy: summaryWithoutId });
|
|
2682
|
+
}
|
|
2683
|
+
if (answer === "closed") {
|
|
2684
|
+
if (keepsTrading)
|
|
2685
|
+
return renewalPending("not_answered");
|
|
2686
|
+
return clientError("trading_policy_not_answered", "The owner closed the trading-policy question without answering. Nothing was signed.", "Call again when the owner wants to trade; they will be asked again.", { money_moved: false, trading_policy: summaryWithoutId });
|
|
2687
|
+
}
|
|
2688
|
+
allowed = answer === "yes";
|
|
2689
|
+
}
|
|
2690
|
+
if (!allowed && !declinedTradingPolicyTerms.has(termsId)) {
|
|
2691
|
+
// No form question (or it could not be shown): the relayed yes for exactly these terms.
|
|
2692
|
+
allowed = consent.accepted === true && consent.termsId === termsId;
|
|
2693
|
+
}
|
|
2694
|
+
if (!allowed && keepsTrading)
|
|
2695
|
+
return renewalPending("consent_required");
|
|
2696
|
+
if (!allowed) {
|
|
2697
|
+
relayedTradingPolicyTerms.add(termsId);
|
|
2698
|
+
return clientError("trading_policy_consent_required", "The owner must allow this account's trading policy before Felix MCP signs it. Nothing was signed.", "Ask the owner exactly `question`. Only if they answer yes, call the same tool again with "
|
|
2699
|
+
+ "accept_trading_policy:true and trading_policy_terms_id. Never answer for the owner.", { money_moved: false, question, trading_policy_terms_id: verified.summary.terms_id,
|
|
2700
|
+
trading_policy: verified.summary });
|
|
2701
|
+
}
|
|
2702
|
+
const shared = tradingPolicySubmitsInFlight.get(termsId);
|
|
2703
|
+
if (shared)
|
|
2704
|
+
return await shared;
|
|
2705
|
+
const submitting = (async () => {
|
|
2706
|
+
const signed = {
|
|
2707
|
+
signature: await privateKeyToAccount(ownerKey).signMessage({ message: verified.message }),
|
|
2708
|
+
summary: verified.summary,
|
|
2709
|
+
};
|
|
2710
|
+
const submitted = await call("POST", "/v1/manual/trading-policy/submit", {
|
|
2711
|
+
...(accountId ? { account_id: accountId } : {}),
|
|
2712
|
+
policy_token: prepared.policy_token, owner_signature: signed.signature,
|
|
2713
|
+
...(renewal ? { renewal: true } : {}),
|
|
2714
|
+
}, { ...auth, timeoutMs: 60_000 });
|
|
2715
|
+
if (submitted.ok === false)
|
|
2716
|
+
return submitted;
|
|
2717
|
+
if (submitted.ready !== true || (submitted.account_id !== undefined && submitted.account_id !== resolvedAccount)) {
|
|
2718
|
+
return clientError("trading_policy_unconfirmed", "Felix did not confirm the signed trading policy for this account. No order was sent.", "Retry shortly; the same signed policy is reused.", { money_moved: false });
|
|
2719
|
+
}
|
|
2720
|
+
manualPolicyReadyUntil.set(cacheKey, Date.now() + MANUAL_POLICY_READY_TTL_MS);
|
|
2721
|
+
// The remembered yes only covers retrying a failed submit: once signed, any later draft asks the owner again.
|
|
2722
|
+
approvedTradingPolicyTerms.delete(termsId);
|
|
2723
|
+
relayedTradingPolicyTerms.delete(termsId);
|
|
2724
|
+
return { ok: true, status: renewal ? "renewed" : "ready", policy: signed.summary, money_moved: false };
|
|
2725
|
+
})().finally(() => tradingPolicySubmitsInFlight.delete(termsId));
|
|
2726
|
+
tradingPolicySubmitsInFlight.set(termsId, submitting);
|
|
2727
|
+
return await submitting;
|
|
2728
|
+
}
|
|
2729
|
+
function manualTradingPolicyNotSupported(response) {
|
|
2730
|
+
return engineRouteMissing(response);
|
|
2731
|
+
}
|
|
2732
|
+
/** The account's verified Arc home Safe, re-derived from this owner (CREATE2) and confirmed registered and verified
|
|
2733
|
+
* on chain 5042 through /v1/arc-home/account. Opus QA r5: /v1/deposit-address answers 409 for an Arc-only (new)
|
|
2734
|
+
* account, so the Arc home money tools resolve the Safe here instead. */
|
|
2735
|
+
async function verifiedArcHomeSafe(owner, accountId) {
|
|
2736
|
+
const account = await call("GET", `/v1/arc-home/account${qs({ account_id: accountId })}`, undefined, { timeoutMs: 30_000, ...(accountId && API_KEY_RE.test(START_KEY) ? { authKey: START_KEY } : {}) });
|
|
2737
|
+
if (account.ok === false)
|
|
2738
|
+
throw new Error("The selected account's Arc home could not be read.");
|
|
2739
|
+
const parsed = parseArcHomeAccount(account, owner);
|
|
2740
|
+
if (!parsed.registered || !parsed.verified || !parsed.safe || parsed.chain_id !== ARC_MAINNET_CHAIN_ID) {
|
|
2741
|
+
throw new Error("The selected account has no verified Arc home Safe for this owner.");
|
|
2742
|
+
}
|
|
2743
|
+
return parsed.safe;
|
|
2744
|
+
}
|
|
2745
|
+
// PM_FUNDING_APP_ROUTE_20261117: dependencies for the app's Arc home -> Polymarket route (src/arc-polygon-funding.ts).
|
|
2746
|
+
export function buildArcPolygonDeps(workflowKey, context, accountId, policy) {
|
|
2747
|
+
const ownerKey = () => {
|
|
2748
|
+
if (isHostedTransport())
|
|
2749
|
+
throw new Error("Local signing is disabled for the hosted multi-tenant transport.");
|
|
2750
|
+
const key = getRuntimeOwnerPrivateKey();
|
|
2751
|
+
if (!EVM_PRIVATE_KEY_RE.test(key || ""))
|
|
2752
|
+
throw new Error("A local owner key is required to sign this funding.");
|
|
2753
|
+
return key;
|
|
2754
|
+
};
|
|
2755
|
+
let owner = "";
|
|
2756
|
+
try {
|
|
2757
|
+
owner = privateKeyToAccount(ownerKey()).address;
|
|
2758
|
+
}
|
|
2759
|
+
catch {
|
|
2760
|
+
owner = "";
|
|
2761
|
+
}
|
|
2762
|
+
return {
|
|
2763
|
+
call: (method, path, body, opts) => call(method, path, body, opts),
|
|
2764
|
+
accountId,
|
|
2765
|
+
owner,
|
|
2766
|
+
// The verified Arc home Safe, re-derived from this owner (CREATE2) and confirmed registered and verified.
|
|
2767
|
+
expectedSafe: async () => verifiedArcHomeSafe(privateKeyToAccount(ownerKey()).address, accountId),
|
|
2768
|
+
// The account's Polymarket deposit wallet, accepted only when Felix binds it to THIS local owner key.
|
|
2769
|
+
expectedPmWallet: async () => {
|
|
2770
|
+
const wallet = await call("GET", `/v1/wallet/polymarket${qs({ account_id: accountId })}`, undefined, { timeoutMs: 30_000 });
|
|
2771
|
+
const localOwner = privateKeyToAccount(ownerKey()).address.toLowerCase();
|
|
2772
|
+
if (wallet.ok === false || String(wallet.owner_address || "").toLowerCase() !== localOwner
|
|
2773
|
+
|| typeof wallet.deposit_wallet !== "string") {
|
|
2774
|
+
throw new Error("The selected account's Polymarket wallet is not bound to this owner.");
|
|
2775
|
+
}
|
|
2776
|
+
return wallet.deposit_wallet;
|
|
2777
|
+
},
|
|
2778
|
+
signSafeTx: (typedData) => signArcHomeSafeTx(typedData, ownerKey()),
|
|
2779
|
+
signGasGrant: (prepared) => signGasSponsorship(prepared, ownerKey()),
|
|
2780
|
+
executePredictionFund: (prepared, amountUsd, callbacks, options) => executeFundingIntent(prepared, { operation: "prediction_fund", amountUsd, approvalAlreadySent: options.approvalAlreadySent }, fundingRpcAccess(accountId), callbacks),
|
|
2781
|
+
pmApprovalReady: (prepared) => predictionFundApprovalReady(prepared, fundingRpcAccess(accountId)),
|
|
2782
|
+
policy: policy ?? polygonFundingAppPolicy(),
|
|
2783
|
+
getCheckpoint: (name) => context.getCheckpoint(name),
|
|
2784
|
+
saveCheckpoint: (name, value) => context.saveCheckpoint(name, value),
|
|
2785
|
+
stageKey: (stage) => workflowStageKey(workflowKey, stage),
|
|
2786
|
+
now: () => Date.now(),
|
|
2787
|
+
sleep: async (ms) => { await sleep(ms); },
|
|
2788
|
+
pollBudgetMs: 45_000,
|
|
2789
|
+
};
|
|
2790
|
+
}
|
|
2791
|
+
export async function executeArcPolygonFunding(amountUsd, minimumUsd, workflowKey, context, accountId) {
|
|
2792
|
+
const toUnits = (value) => {
|
|
2793
|
+
const u = Math.round(value * 1_000_000);
|
|
2794
|
+
return Number.isSafeInteger(u) && Math.abs(u / 1_000_000 - value) <= 1e-9 ? BigInt(u) : null;
|
|
2795
|
+
};
|
|
2796
|
+
const amount = toUnits(amountUsd);
|
|
2797
|
+
const minimum = minimumUsd === undefined ? null : toUnits(minimumUsd);
|
|
2798
|
+
if (amount === null || (minimumUsd !== undefined && minimum === null)) {
|
|
2799
|
+
return markMoneyNotStarted(clientError("invalid_amount", "Amounts must be exact USDC with at most six decimals."));
|
|
2800
|
+
}
|
|
2801
|
+
return driveArcPolygonFunding({ amount_units: amount, minimum_credit_units: minimum }, buildArcPolygonDeps(workflowKey, context, accountId));
|
|
2802
|
+
}
|
|
2180
2803
|
// ARC_HOME_MONEY_2026_09_24: Arc home Safe money paths, ported from the held
|
|
2181
2804
|
// 2.0.115 client (ARC_HOME_2026_09_17) and re-checked against the current
|
|
2182
2805
|
// engine contract. The engine prepares; this client verifies every payload
|
|
@@ -2195,7 +2818,7 @@ const ARC_HOME_RECONCILE_POLL_MS = 5_000;
|
|
|
2195
2818
|
const ARC_HOME_VENUES = ["polymarket"];
|
|
2196
2819
|
const ARC_HOME_VENUE_CHAIN = { polymarket: "polygon" };
|
|
2197
2820
|
const ARC_HOME_UNSUPPORTED_VENUES = {
|
|
2198
|
-
hyperliquid: "
|
|
2821
|
+
hyperliquid: "This tool does not fund Hyperliquid. Use fund_hypercore_from_arc (5 to 25 USDC from the Arc home to the owner's own Hyperliquid perps).",
|
|
2199
2822
|
derive: "Arc home -> Derive funding is not executable in this release.",
|
|
2200
2823
|
};
|
|
2201
2824
|
function arcHomeFailure(error, operationId, moneyMoved) {
|
|
@@ -2215,7 +2838,9 @@ async function arcHomeOwnerKeyFor(accountId) {
|
|
|
2215
2838
|
return getRuntimeOwnerPrivateKey() || START_OWNER_KEY;
|
|
2216
2839
|
}
|
|
2217
2840
|
async function arcHomeCall(method, path, body, opts = {}) {
|
|
2218
|
-
|
|
2841
|
+
// A child session's Arc home money calls go out on the launcher credential for that child (Astra mcploop r2:
|
|
2842
|
+
// the child's read/trade key got 403 'transfer' on an implicit arc_home_withdraw).
|
|
2843
|
+
const accountId = opts.accountId || activeChildAccountId();
|
|
2219
2844
|
const targetPath = accountId && method === "GET" ? withTargetAccountQuery(path, accountId) : path;
|
|
2220
2845
|
const targetBody = accountId && method === "POST" ? { ...(body || {}), account_id: accountId } : body;
|
|
2221
2846
|
return call(method, targetPath, targetBody, {
|
|
@@ -2225,8 +2850,15 @@ async function arcHomeCall(method, path, body, opts = {}) {
|
|
|
2225
2850
|
...(accountId && API_KEY_RE.test(START_KEY) ? { authKey: START_KEY } : {}),
|
|
2226
2851
|
});
|
|
2227
2852
|
}
|
|
2853
|
+
function activeChildAccountId() {
|
|
2854
|
+
if (isHostedTransport() || !API_KEY_RE.test(START_KEY))
|
|
2855
|
+
return undefined;
|
|
2856
|
+
return runtimeManagedAccountId && UUID_RE.test(runtimeManagedAccountId) && getKey() !== START_KEY
|
|
2857
|
+
? runtimeManagedAccountId : undefined;
|
|
2858
|
+
}
|
|
2228
2859
|
/** Every Arc home read is statically a GET, so a read tool can never mutate. */
|
|
2229
|
-
async function arcHomeGet(path,
|
|
2860
|
+
async function arcHomeGet(path, requestedAccountId) {
|
|
2861
|
+
const accountId = requestedAccountId || activeChildAccountId();
|
|
2230
2862
|
return call("GET", accountId ? withTargetAccountQuery(path, accountId) : path, undefined, {
|
|
2231
2863
|
retryOnError: false,
|
|
2232
2864
|
timeoutMs: 30_000,
|
|
@@ -2936,16 +3568,13 @@ async function executeArcHomeHlReturnTool(a) {
|
|
|
2936
3568
|
const n = normalizedArcHomeHlReturnArgs(a);
|
|
2937
3569
|
const key = String(n.idempotency_key);
|
|
2938
3570
|
const units = BigInt(Math.round(Number(n.amount_usd) * 1_000_000)).toString();
|
|
2939
|
-
const home = await call("GET", "/v1/deposit-address", undefined, { timeoutMs: 30_000 });
|
|
2940
|
-
if (home.ok === false)
|
|
2941
|
-
return markMoneyNotStarted(home);
|
|
2942
3571
|
const local = settlementOwnerAddress();
|
|
2943
3572
|
if (!local) {
|
|
2944
3573
|
return markMoneyNotStarted(clientError("owner_key_mismatch", "The local owner key is unavailable.", "Nothing was prepared or signed."));
|
|
2945
3574
|
}
|
|
2946
3575
|
let safe;
|
|
2947
3576
|
try {
|
|
2948
|
-
safe =
|
|
3577
|
+
safe = await verifiedArcHomeSafe(local, runtimeManagedAccountId);
|
|
2949
3578
|
}
|
|
2950
3579
|
catch {
|
|
2951
3580
|
return markMoneyNotStarted(clientError("arc_home_destination_mismatch", "This account's Arc home Safe does not match the local owner key.", "Nothing was prepared or signed."));
|
|
@@ -3080,6 +3709,82 @@ function fundingRpcAccess(targetAccountId) {
|
|
|
3080
3709
|
...(managingChild ? { account_id: selectedAccountId } : {}),
|
|
3081
3710
|
};
|
|
3082
3711
|
}
|
|
3712
|
+
// Opus QA r12: engine refusals that a new (Arc home) account reaches, mapped to the tool that works for it.
|
|
3713
|
+
const FUND_VENUE_FROM_ARC_HINT = "Fund the venue from the Arc home with fund_polymarket_from_arc (5 to 25 USDC plus a disclosed 1.00 USDC "
|
|
3714
|
+
+ "network fee) or fund_hypercore_from_arc (Hyperliquid), then place the order. Nothing was signed and no money moved.";
|
|
3715
|
+
const FEE_CREDIT_TOOLS = new Set(["top_up_fee_balance", "preview_fee_top_up", "settle_fees", "preview_fee_settlement"]);
|
|
3716
|
+
const VENUE_FUNDING_TOOLS = new Set([
|
|
3717
|
+
"start_home_funding", "start_capital_move", "prepare_venue_bootstrap", "submit_venue_bootstrap",
|
|
3718
|
+
"arc_home_fund_venue", "fund_market", "start_fund_market",
|
|
3719
|
+
]);
|
|
3720
|
+
export function withNewAccountNextStep(name, out, args = {}) {
|
|
3721
|
+
if (out.ok !== false || !isRecord(out.error))
|
|
3722
|
+
return out;
|
|
3723
|
+
// Never rewrite a result whose money may have moved or that needs reconciling (Opus QA r13).
|
|
3724
|
+
const moneyMaybeMoved = (record) => record.money_moved === true
|
|
3725
|
+
|| record.money_moved === "unknown" || record.user_funds_moved === true || record.reconciliation_required === true
|
|
3726
|
+
|| record.outcome_unknown === true;
|
|
3727
|
+
if ([out, out.error, out.result, out.workflow].some((record) => isRecord(record) && moneyMaybeMoved(record)))
|
|
3728
|
+
return out;
|
|
3729
|
+
if (isRecord(out.result) && isRecord(out.result.error) && isRecord(out.result.result)
|
|
3730
|
+
&& moneyMaybeMoved(out.result.result))
|
|
3731
|
+
return out;
|
|
3732
|
+
const error = out.error;
|
|
3733
|
+
const codes = [error.code, error.reason, out.reason].map((value) => nonEmptyString(value) ?? "");
|
|
3734
|
+
const message = typeof error.message === "string" ? error.message : "";
|
|
3735
|
+
// The mapped hint replaces every copy of the old one (an async operation repeats it at the top level and in result).
|
|
3736
|
+
const next = (hint, nextTools, extra = {}) => ({
|
|
3737
|
+
...out, ...extra,
|
|
3738
|
+
...(typeof out.hint === "string" ? { hint } : {}),
|
|
3739
|
+
...(isRecord(out.result) && isRecord(out.result.error)
|
|
3740
|
+
? { result: { ...out.result, error: { ...out.result.error, hint } } } : {}),
|
|
3741
|
+
error: { ...error, hint }, next_tools: nextTools,
|
|
3742
|
+
});
|
|
3743
|
+
if (codes.includes("arc_home_venue_wallet_unavailable")) {
|
|
3744
|
+
return next(FUND_VENUE_FROM_ARC_HINT, ["fund_polymarket_from_arc", "fund_hypercore_from_arc"]);
|
|
3745
|
+
}
|
|
3746
|
+
if (codes.includes("polygon_safe_hub_retired")) {
|
|
3747
|
+
return next("This Polygon Safe tool is retired: the account's wallet is its Arc home Safe. See it with get_balances, "
|
|
3748
|
+
+ "fund it with create_deposit, fund a venue with fund_polymarket_from_arc or fund_hypercore_from_arc, and stop "
|
|
3749
|
+
+ "all trading with panic.", ["get_balances", "create_deposit", "fund_polymarket_from_arc", "fund_hypercore_from_arc", "panic"]);
|
|
3750
|
+
}
|
|
3751
|
+
if (codes.includes("venue_return_prepare_not_launch_enabled")) {
|
|
3752
|
+
// Opus QA r14: new venue returns via bring_home are not enabled; name what works instead of a raw route.
|
|
3753
|
+
const venue = String(error.venue ?? out.venue ?? args.venue ?? "").toLowerCase();
|
|
3754
|
+
const already = " A return you already started keeps going: retry it with its original idempotency_key, and see "
|
|
3755
|
+
+ "balances with get_money_map.";
|
|
3756
|
+
if (venue === "crypto" || venue === "hyperliquid") {
|
|
3757
|
+
return next("Bring Hyperliquid perps money home with arc_home_hypercore_return (5 to 25 USDC to the Arc home). "
|
|
3758
|
+
+ "No return was created and no money moved." + already, ["arc_home_hypercore_return", "get_money_map"], { retryable: false });
|
|
3759
|
+
}
|
|
3760
|
+
return next("Bringing money home from this venue is not available from the MCP in this release; use Wallet in the "
|
|
3761
|
+
+ "Felix app. No return was created and no money moved." + already, ["get_money_map"], { retryable: false });
|
|
3762
|
+
}
|
|
3763
|
+
if (codes.includes("fee_credit_topup_not_ready") && FEE_CREDIT_TOOLS.has(name)) {
|
|
3764
|
+
return next("Not needed: Felix charges its fee from the trading account as each order fills, so no prepaid fee "
|
|
3765
|
+
+ "credit is required to trade. Nothing was signed and no money moved.", ["preview_order", "place_manual_order"], { fee_credit_required: false });
|
|
3766
|
+
}
|
|
3767
|
+
if (VENUE_FUNDING_TOOLS.has(name) && /lacks the '(?:transfer|manage)' scope/.test(message)) {
|
|
3768
|
+
const venue = String(args.venue ?? "").toLowerCase();
|
|
3769
|
+
// Only name routes that work from an account session (Opus QA r14: bring_home's new returns are not enabled).
|
|
3770
|
+
if (args.direction === "bring_home") {
|
|
3771
|
+
if (venue === "hyperliquid") {
|
|
3772
|
+
return next("Bring Hyperliquid perps money home with arc_home_hypercore_return (5 to 25 USDC to the Arc home). "
|
|
3773
|
+
+ "Nothing was signed and no money moved.", ["arc_home_hypercore_return"]);
|
|
3774
|
+
}
|
|
3775
|
+
return next("Bringing money home from this venue is not available from the MCP in this release; use Wallet in the "
|
|
3776
|
+
+ "Felix app. Nothing was signed and no money moved.", []);
|
|
3777
|
+
}
|
|
3778
|
+
if (venue === "lighter") {
|
|
3779
|
+
return next("Funding Lighter from the MCP is not available in this release; use Wallet in the Felix app. Nothing "
|
|
3780
|
+
+ "was signed and no money moved.", []);
|
|
3781
|
+
}
|
|
3782
|
+
if (venue === "" || venue === "hyperliquid" || venue === "polymarket" || venue === "prediction_market") {
|
|
3783
|
+
return next(FUND_VENUE_FROM_ARC_HINT, ["fund_polymarket_from_arc", "fund_hypercore_from_arc"]);
|
|
3784
|
+
}
|
|
3785
|
+
}
|
|
3786
|
+
return out;
|
|
3787
|
+
}
|
|
3083
3788
|
function isChildManagementRequest(method, path) {
|
|
3084
3789
|
const pathname = path.split("?", 1)[0];
|
|
3085
3790
|
if (method === "GET" || method === "DELETE") {
|
|
@@ -3091,9 +3796,15 @@ function isChildManagementRequest(method, path) {
|
|
|
3091
3796
|
// key); the child is named by account_id (engine _target_context).
|
|
3092
3797
|
|| (method === "GET" && isArcHomeManageRoute(pathname));
|
|
3093
3798
|
}
|
|
3799
|
+
// Opus QA r12 F3: the portfolio mandate needs "manage" (routes_quant_desk.py update_mandate), which the account's
|
|
3800
|
+
// read/trade key lacks; the engine targets the account via body.account_id (_target_context).
|
|
3801
|
+
if (method === "PUT")
|
|
3802
|
+
return pathname === "/v1/portfolio/mandate";
|
|
3094
3803
|
if (method !== "POST")
|
|
3095
3804
|
return false;
|
|
3096
3805
|
return pathname === "/v1/referrals"
|
|
3806
|
+
// Owner-signed venue bootstrap (routes_agent_capital.py: require("manage"), money_context(account_id)).
|
|
3807
|
+
|| pathname.startsWith("/v1/agent-capital/venue-bootstrap/")
|
|
3097
3808
|
|| pathname === "/v1/fund"
|
|
3098
3809
|
|| pathname === "/v1/bring-home"
|
|
3099
3810
|
|| pathname === "/v1/withdraw"
|
|
@@ -3566,6 +4277,13 @@ async function fundMarketPrecheck(venue, amountUsd, resuming, autoSwapNativeUsdc
|
|
|
3566
4277
|
balances = await call("GET", "/v1/wallet/funding/balances");
|
|
3567
4278
|
}
|
|
3568
4279
|
if (balances.ok === false) {
|
|
4280
|
+
const error = isRecord(balances.error) ? balances.error : {};
|
|
4281
|
+
const status = finiteNumber(isRecord(balances._meta) ? balances._meta.http_status : undefined);
|
|
4282
|
+
if (status === 409 && ["onboarding_required", "wallet_onboarding_required"].includes(String(error.code))) {
|
|
4283
|
+
// ARC_TRADE_KEY_FUNDING_20261117: an Arc-home account has no Polygon owner wallet to fund from. Its money
|
|
4284
|
+
// is in the Arc home, and the app funds a venue from there as part of the order.
|
|
4285
|
+
return markMoneyNotStarted(clientError("arc_home_funding_required", "This account's money is in its Arc home, not a Polygon owner wallet, so fund_market cannot move it.", "Move money from the Arc home with fund_hypercore_from_arc (Hyperliquid) or fund_polymarket_from_arc (Polymarket), then trade. Nothing was reserved or moved.", { venue, money_moved: false }));
|
|
4286
|
+
}
|
|
3569
4287
|
return markMoneyNotStarted(clientError("funding_precheck_unavailable", "The owner source balance could not be verified, so no funding workflow was started.", "Retry in a moment; nothing was reserved or moved."));
|
|
3570
4288
|
}
|
|
3571
4289
|
const polygonAvailable = Number(balances.polygon_usdce);
|
|
@@ -6626,6 +7344,12 @@ async function call(method, path, body, opts = {}) {
|
|
|
6626
7344
|
&& runtimeManagedAccountId
|
|
6627
7345
|
&& UUID_RE.test(runtimeManagedAccountId)
|
|
6628
7346
|
&& isChildManagementRequest(method, path)) {
|
|
7347
|
+
const explicitAccount = isRecord(requestBody) ? requestBody.account_id
|
|
7348
|
+
: new URLSearchParams(path.split("?", 2)[1] ?? "").get("account_id") ?? undefined;
|
|
7349
|
+
if (explicitAccount !== undefined && explicitAccount !== null
|
|
7350
|
+
&& String(explicitAccount).toLowerCase() !== runtimeManagedAccountId.toLowerCase()) {
|
|
7351
|
+
return clientError("account_mismatch", "This session is working on a different account than the account_id you passed. Nothing was sent.", "Omit account_id to act on the selected account, or call use_child_account with the other account first.", { selected_account_id: runtimeManagedAccountId, money_moved: false });
|
|
7352
|
+
}
|
|
6629
7353
|
key = START_KEY;
|
|
6630
7354
|
const pathname = path.split("?", 1)[0];
|
|
6631
7355
|
const targetInQuery = method === "GET"
|
|
@@ -6642,7 +7366,7 @@ async function call(method, path, body, opts = {}) {
|
|
|
6642
7366
|
}
|
|
6643
7367
|
}
|
|
6644
7368
|
if (!key && !opts.public) {
|
|
6645
|
-
return clientError("missing_api_key", "Set FELIX_API_KEY to a Felix fk_ key.", "
|
|
7369
|
+
return clientError("missing_api_key", "Set FELIX_API_KEY to a Felix fk_ key.", "Call the onboard tool (no restart needed). It creates the local identity and encrypted recovery file automatically.");
|
|
6646
7370
|
}
|
|
6647
7371
|
const idempotencyKey = opts.idempotencyKey || (opts.idempotent ? randomUUID() : undefined);
|
|
6648
7372
|
const transportAttempts = opts.retryOnError === false ? 1 : (method === "GET" || idempotencyKey ? 2 : 1);
|
|
@@ -6876,8 +7600,44 @@ async function readCustodyProof(accountId, authKey) {
|
|
|
6876
7600
|
let result = {};
|
|
6877
7601
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
6878
7602
|
result = await call("GET", `/v1/wallet/custody-proof${qs({ account_id: accountId })}`, undefined, { authKey, retryOnError: false, timeoutMs: 60_000 });
|
|
6879
|
-
if (result.ok !== false)
|
|
7603
|
+
if (result.ok !== false) {
|
|
7604
|
+
// Astra mcploop r2 R2-F2: a proof for another account, an unknown chain, or an unverified proof never
|
|
7605
|
+
// reaches a signature.
|
|
7606
|
+
const chainIds = { arc: ARC_MAINNET_CHAIN_ID, polygon: 137 };
|
|
7607
|
+
const positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
7608
|
+
const arcModules = Array.isArray(result.enabled_modules) ? result.enabled_modules : [];
|
|
7609
|
+
if (result.account_id !== accountId || typeof result.chain !== "string"
|
|
7610
|
+
|| !Object.prototype.hasOwnProperty.call(chainIds, result.chain)
|
|
7611
|
+
|| typeof result.chain_id !== "number" || result.chain_id !== chainIds[result.chain]
|
|
7612
|
+
|| result.verified_on_chain !== true
|
|
7613
|
+
|| typeof result.account_archived !== "boolean"
|
|
7614
|
+
|| (result.safe_threshold !== undefined && result.safe_threshold !== 1)
|
|
7615
|
+
|| !positive(result.max_operation_usd) || !positive(result.daily_limit_usd)
|
|
7616
|
+
|| (result.chain === "arc" && (result.safe_threshold !== 1
|
|
7617
|
+
|| typeof result.module !== "string" || !EVM_ADDRESS_RE.test(result.module)
|
|
7618
|
+
|| /^0x0{40}$/i.test(result.module) || arcModules.length !== 1
|
|
7619
|
+
|| String(arcModules[0]).toLowerCase() !== result.module.toLowerCase()))) {
|
|
7620
|
+
return clientError("custody_proof_invalid", "Felix returned a custody proof that is not a verified proof for this account. Nothing was signed.", "Retry shortly; do not trade or fund this account until custody verifies.", { account_id: accountId, money_moved: false });
|
|
7621
|
+
}
|
|
7622
|
+
// ARC_CUSTODY_PROOF_20261117: an Arc-only account's proof is its Arc home. Its Safe must be the CREATE2 Safe
|
|
7623
|
+
// of the reported owner (callers then match that owner to the locally derived one).
|
|
7624
|
+
if (result.chain === "arc") {
|
|
7625
|
+
const safeOwner = nonEmptyString(result.safe_owner);
|
|
7626
|
+
let matches = false;
|
|
7627
|
+
try {
|
|
7628
|
+
matches = Boolean(safeOwner) && EVM_ADDRESS_RE.test(safeOwner)
|
|
7629
|
+
&& nonEmptyString(result.safe)?.toLowerCase() === predictArcHomeSafe(safeOwner).toLowerCase()
|
|
7630
|
+
&& result.deposit_address === undefined;
|
|
7631
|
+
}
|
|
7632
|
+
catch {
|
|
7633
|
+
matches = false;
|
|
7634
|
+
}
|
|
7635
|
+
if (!matches) {
|
|
7636
|
+
return clientError("arc_home_safe_mismatch", "Felix's Arc custody proof names a Safe this account's owner does not control. Nothing was changed.", "Do not trade or fund this account until custody verifies; contact Felix support.", { account_id: accountId, money_moved: false });
|
|
7637
|
+
}
|
|
7638
|
+
}
|
|
6880
7639
|
return result;
|
|
7640
|
+
}
|
|
6881
7641
|
const error = isRecord(result.error) ? result.error : {};
|
|
6882
7642
|
const code = nonEmptyString(error.code);
|
|
6883
7643
|
const meta = isRecord(result._meta) ? result._meta : {};
|
|
@@ -9533,14 +10293,7 @@ export function buildPmArcReturnDeps(workflowKey, context) {
|
|
|
9533
10293
|
return "";
|
|
9534
10294
|
}
|
|
9535
10295
|
},
|
|
9536
|
-
expectedSafe: async () =>
|
|
9537
|
-
const home = await call("GET", "/v1/deposit-address", undefined, { timeoutMs: 30_000 });
|
|
9538
|
-
if (home.ok === false) {
|
|
9539
|
-
throw new Error("The selected account has no verified Arc home Safe for this owner.");
|
|
9540
|
-
}
|
|
9541
|
-
const owner = privateKeyToAccount(ownerKey()).address;
|
|
9542
|
-
return arcHomeSafeFromDepositResponse(home, owner);
|
|
9543
|
-
},
|
|
10296
|
+
expectedSafe: async () => verifiedArcHomeSafe(privateKeyToAccount(ownerKey()).address, runtimeManagedAccountId),
|
|
9544
10297
|
// signReturnContext re-checks the pinned factory, implementation, deadline
|
|
9545
10298
|
// window, owner and exact calls before it signs.
|
|
9546
10299
|
signVenueBatch: (batch, amountUnits) => signReturnContext({
|
|
@@ -11027,7 +11780,8 @@ const TOOL_RISK_GROUPS = {
|
|
|
11027
11780
|
],
|
|
11028
11781
|
local_credential: ["set_api_key", "reload_launcher_key"],
|
|
11029
11782
|
account: [
|
|
11030
|
-
"prepare_venue_bootstrap", "request_withdrawal_confirmation", "verify_withdrawal_confirmation", "use_child_account", "derive_api_key", "create_account", "archive_account", "onboard"
|
|
11783
|
+
"prepare_venue_bootstrap", "request_withdrawal_confirmation", "verify_withdrawal_confirmation", "use_child_account", "derive_api_key", "create_account", "archive_account", "onboard",
|
|
11784
|
+
"create_deposit", "cancel_deposit"
|
|
11031
11785
|
],
|
|
11032
11786
|
trading: [
|
|
11033
11787
|
"place_order", "place_batch_orders", "cancel_order", "close_position",
|
|
@@ -11043,6 +11797,7 @@ const TOOL_RISK_GROUPS = {
|
|
|
11043
11797
|
"resolve_network_fee", "swap_native_usdc", "fund_market",
|
|
11044
11798
|
"start_fund_market", "bring_home", "start_bring_home", "resume_money_operation",
|
|
11045
11799
|
"start_arc_home_hl_return", "fund_hypercore_from_arc", "arc_home_hypercore_return", "invalidate_safe_nonce",
|
|
11800
|
+
"fund_polymarket_from_arc",
|
|
11046
11801
|
"return_prediction_market_to_arc",
|
|
11047
11802
|
"fund_polymarket_agent_wallet",
|
|
11048
11803
|
"prepare_arc_transfer", "submit_arc_transfer",
|
|
@@ -11129,12 +11884,7 @@ export function buildHypercoreDeps(workflowKey, context, accountId, policy) {
|
|
|
11129
11884
|
call: (method, path, body, opts) => call(method, path, body, opts),
|
|
11130
11885
|
accountId,
|
|
11131
11886
|
owner,
|
|
11132
|
-
expectedSafe: async () =>
|
|
11133
|
-
const home = await call("GET", "/v1/deposit-address", undefined, { timeoutMs: 30_000 });
|
|
11134
|
-
if (home.ok === false)
|
|
11135
|
-
throw new Error("The selected account has no verified Arc home Safe for this owner.");
|
|
11136
|
-
return arcHomeSafeFromDepositResponse(home, privateKeyToAccount(ownerKey()).address);
|
|
11137
|
-
},
|
|
11887
|
+
expectedSafe: async () => verifiedArcHomeSafe(privateKeyToAccount(ownerKey()).address, accountId),
|
|
11138
11888
|
// Signs the CLIENT-BUILT typed data with the canonical SafeTx types only.
|
|
11139
11889
|
signSafeTx: (typedData) => signArcHomeSafeTx(typedData, ownerKey()),
|
|
11140
11890
|
hyperliquid: {
|
|
@@ -11236,12 +11986,7 @@ export function buildHypercoreReturnDeps(workflowKey, context, accountId, policy
|
|
|
11236
11986
|
call: (method, path, body, opts) => call(method, path, body, opts),
|
|
11237
11987
|
accountId,
|
|
11238
11988
|
owner,
|
|
11239
|
-
expectedSafe: async () =>
|
|
11240
|
-
const home = await call("GET", "/v1/deposit-address", undefined, { timeoutMs: 30_000 });
|
|
11241
|
-
if (home.ok === false)
|
|
11242
|
-
throw new Error("The selected account has no verified Arc home Safe for this owner.");
|
|
11243
|
-
return arcHomeSafeFromDepositResponse(home, privateKeyToAccount(ownerKey()).address);
|
|
11244
|
-
},
|
|
11989
|
+
expectedSafe: async () => verifiedArcHomeSafe(privateKeyToAccount(ownerKey()).address, accountId),
|
|
11245
11990
|
// Only the two client-built payload kinds are ever signed here.
|
|
11246
11991
|
signTypedData: (typedData) => {
|
|
11247
11992
|
if (typedData.primaryType !== "NonceMapping" && typedData.primaryType !== "HyperliquidTransaction:SendAsset") {
|
|
@@ -11300,12 +12045,7 @@ export function buildSafeInvalidationDeps(workflowKey, context, accountId, polic
|
|
|
11300
12045
|
call: (method, path, body, opts) => call(method, path, body, opts),
|
|
11301
12046
|
accountId,
|
|
11302
12047
|
owner,
|
|
11303
|
-
expectedSafe: async () =>
|
|
11304
|
-
const home = await call("GET", "/v1/deposit-address", undefined, { timeoutMs: 30_000 });
|
|
11305
|
-
if (home.ok === false)
|
|
11306
|
-
throw new Error("The selected account has no verified Arc home Safe for this owner.");
|
|
11307
|
-
return arcHomeSafeFromDepositResponse(home, privateKeyToAccount(ownerKey()).address);
|
|
11308
|
-
},
|
|
12048
|
+
expectedSafe: async () => verifiedArcHomeSafe(privateKeyToAccount(ownerKey()).address, accountId),
|
|
11309
12049
|
signSafeTx: (typedData) => signArcHomeSafeTx(typedData, ownerKey()),
|
|
11310
12050
|
// Astra BLOCK 2026-11-15: never Felix-attested; refuses until a verified chain check exists.
|
|
11311
12051
|
policy: policy ?? SHIPPED_INVALIDATION_POLICY,
|
|
@@ -11331,7 +12071,7 @@ const LIVE_MONEY_TOOLS = new Set([
|
|
|
11331
12071
|
"place_manual_order", "close_manual_position", "modify_order_price",
|
|
11332
12072
|
"swap_native_usdc", "fund_market", "start_fund_market",
|
|
11333
12073
|
"bring_home", "start_bring_home", "resume_money_operation", "resolve_network_fee",
|
|
11334
|
-
"start_arc_home_hl_return", "fund_hypercore_from_arc", "arc_home_hypercore_return",
|
|
12074
|
+
"start_arc_home_hl_return", "fund_hypercore_from_arc", "arc_home_hypercore_return", "fund_polymarket_from_arc",
|
|
11335
12075
|
"return_prediction_market_to_arc",
|
|
11336
12076
|
"fund_polymarket_agent_wallet", "submit_arc_transfer",
|
|
11337
12077
|
"arc_home_withdraw", "arc_home_deposit", "arc_home_fund_venue",
|
|
@@ -11423,7 +12163,7 @@ const manualOrderFields = {
|
|
|
11423
12163
|
expected_position_id: stringProp("With reduce_only, the position this order reduces.", undefined, { pattern: UUID_RE.source }),
|
|
11424
12164
|
outcome: stringProp("Polymarket outcome name (e.g. Yes, No, a team, Draw)."),
|
|
11425
12165
|
time_in_force: stringProp("Polymarket only: FAK (default, fill what is there now) or GTC (rest on the book; limit only).", ["FAK", "GTC"]),
|
|
11426
|
-
funding: objectProp("Fund this order from Home: {max_source_units, max_fee_units, expires_at}. Needs the transfer scope."),
|
|
12166
|
+
funding: objectProp("Fund this order's venue from the account's Home: {max_source_units, max_fee_units, expires_at}, integers (USDC 6-decimal units; expires_at in Unix seconds). Needs a key with the 'transfer' scope (the launcher's own account). A child account's trading key cannot: fund the venue first (fund_hypercore_from_arc for Hyperliquid), then order without funding."),
|
|
11427
12167
|
};
|
|
11428
12168
|
const quantLimitFields = {
|
|
11429
12169
|
risk_per_trade_pct: numberProp("Maximum account value risked at invalidation on one trade.", 0.05, 10),
|
|
@@ -11761,7 +12501,7 @@ const TOOLS = [
|
|
|
11761
12501
|
},
|
|
11762
12502
|
{
|
|
11763
12503
|
name: "preview_order",
|
|
11764
|
-
description: "Preview an order before placing it. No money moves; returns estimated fill, fees, live minimum, collateral, selected venue, and projected Hyperliquid leverage. fee_credit_check reports the
|
|
12504
|
+
description: "Preview an order before placing it. No money moves; returns estimated fill, fees, live minimum, collateral, selected venue, and projected Hyperliquid leverage. fee_credit_check reports how the Felix fee is collected: it is charged from the trading account after each fill and never blocks an order, so no prepaid fee credit or top-up is needed. Derive options also return exact quote-sized signed delta plus venue-native gamma, theta, and vega impact; missing Greeks remain unavailable, never zero. Set auto_fund:true to include the exact owner-to-venue funding plan without executing it.",
|
|
11765
12505
|
inputSchema: schema({
|
|
11766
12506
|
...orderFields,
|
|
11767
12507
|
auto_fund: booleanProp("Include a read-only funding plan when venue collateral is short. This preview never moves money."),
|
|
@@ -11984,8 +12724,10 @@ const TOOLS = [
|
|
|
11984
12724
|
},
|
|
11985
12725
|
{
|
|
11986
12726
|
name: "place_manual_order",
|
|
11987
|
-
description: "Place a LIVE manual order exactly like the app's ticket: market or limit, post-only, resting (Polymarket time_in_force GTC), reduce-only, leverage up to the venue maximum. This moves real money. Opening orders stay within this key's max_order_usd and max_daily_usd and the account's portfolio mandate.
|
|
11988
|
-
inputSchema: schema({ ...manualOrderFields, idempotency_key: stringProp("Retry-safety key; reuse it for retries of the same order. Auto-generated when omitted.")
|
|
12727
|
+
description: "Place a LIVE manual order exactly like the app's ticket: market or limit, post-only, resting (Polymarket time_in_force GTC), reduce-only, leverage up to the venue maximum. This moves real money. Opening orders stay within this key's max_order_usd and max_daily_usd and the account's portfolio mandate. An account's own key does not fund from Home: fund the venue first with fund_hypercore_from_arc or fund_polymarket_from_arc. If the account owner's trading policy (the app's device trading policy) is missing or within 3 days of expiry, it is signed locally first and returned in trading_policy (it includes Lighter Premium and Felix partner-fee consent). Reuse the same idempotency_key to retry safely; read the outcome with get_manual_order_receipt.",
|
|
12728
|
+
inputSchema: schema({ ...manualOrderFields, idempotency_key: stringProp("Retry-safety key; reuse it for retries of the same order. Auto-generated when omitted."),
|
|
12729
|
+
accept_trading_policy: booleanProp("Only after the owner answered yes to the trading_policy question this tool returned."),
|
|
12730
|
+
trading_policy_terms_id: stringProp("The trading_policy_terms_id from that question.") }, ["instrument", "side", "size_usd"]),
|
|
11989
12731
|
},
|
|
11990
12732
|
{
|
|
11991
12733
|
name: "get_manual_order_receipt",
|
|
@@ -12286,8 +13028,32 @@ const TOOLS = [
|
|
|
12286
13028
|
},
|
|
12287
13029
|
{
|
|
12288
13030
|
name: "get_deposit_address",
|
|
12289
|
-
description: "
|
|
12290
|
-
inputSchema: schema({
|
|
13031
|
+
description: "How to deposit, exactly like app.felix.trade: money settles as USDC in the account's Arc home Safe (re-derived locally from the account's own owner key). With no arguments: the Arc home, whether a new account's home is funded enough to finish create_account, and the deposit steps. list_currencies:true lists accepted tokens; from_currency + from_amount previews what a deposit delivers; request_id tracks a deposit from create_deposit. Read-only: creates nothing.",
|
|
13032
|
+
inputSchema: schema({
|
|
13033
|
+
account_id: stringProp("Optional owned child account UUID (for example the one create_account returned). Omit for the active account.", undefined, { pattern: UUID_RE.source }),
|
|
13034
|
+
list_currencies: booleanProp("List the accepted deposit tokens and their keys."),
|
|
13035
|
+
from_currency: stringProp("Deposit token key for a preview, for example usdc_base, usdc_arbitrum, eth, btc, sol."),
|
|
13036
|
+
from_amount: numberProp("Amount of from_currency for a preview.", 0),
|
|
13037
|
+
request_id: stringProp("request_id from create_deposit, to track that deposit.", undefined, { pattern: "^0x[0-9a-fA-F]{64}$" }),
|
|
13038
|
+
}),
|
|
13039
|
+
},
|
|
13040
|
+
{
|
|
13041
|
+
name: "create_deposit",
|
|
13042
|
+
description: "Get a one-time payment address for a deposit into the account's Arc home, the same Relay deposit app.felix.trade uses (also a brand-new account's first deposit before its Arc home is set up). Pay exactly from_amount of from_currency on that token's own network before the window ends; it arrives as USDC in the Arc home Safe, which this client re-derives from the owner key and checks before showing any address. Moves no money itself. A first deposit must deliver at least $5.",
|
|
13043
|
+
inputSchema: schema({
|
|
13044
|
+
from_currency: stringProp("Deposit token key from get_deposit_address list_currencies, for example usdc_base."),
|
|
13045
|
+
from_amount: numberProp("Amount of from_currency you will send.", 0),
|
|
13046
|
+
idempotency_key: stringProp("Required. Reuse it after a timeout to get the same instruction back, never a second one."),
|
|
13047
|
+
account_id: stringProp("Optional owned child account UUID. Omit for the active account.", undefined, { pattern: UUID_RE.source }),
|
|
13048
|
+
}, ["from_currency", "from_amount", "idempotency_key"]),
|
|
13049
|
+
},
|
|
13050
|
+
{
|
|
13051
|
+
name: "cancel_deposit",
|
|
13052
|
+
description: "Close an unpaid deposit instruction from create_deposit. Refused once any payment was seen. Moves no money.",
|
|
13053
|
+
inputSchema: schema({
|
|
13054
|
+
request_id: stringProp("request_id from create_deposit.", undefined, { pattern: "^0x[0-9a-fA-F]{64}$" }),
|
|
13055
|
+
account_id: stringProp("Optional owned child account UUID. Omit for the active account.", undefined, { pattern: UUID_RE.source }),
|
|
13056
|
+
}, ["request_id"]),
|
|
12291
13057
|
},
|
|
12292
13058
|
{
|
|
12293
13059
|
name: "preview_funding_route",
|
|
@@ -12452,6 +13218,16 @@ const TOOLS = [
|
|
|
12452
13218
|
idempotency_key: stringProp("Required workflow replay key. Reuse it to resume this exact return."),
|
|
12453
13219
|
}, ["amount_usd", "idempotency_key"]),
|
|
12454
13220
|
}, {
|
|
13221
|
+
// PM_FUNDING_APP_ROUTE_20261117: the app's Arc home -> Polymarket route (app.felix.trade fundPredictionFromArc).
|
|
13222
|
+
name: "fund_polymarket_from_arc",
|
|
13223
|
+
description: "Fund Polymarket from the account's Arc home, exactly like app.felix.trade: move 5 to 25 USDC from the verified Arc home Safe to the SAME owner's Polygon wallet via Relay, then into the account's own Polymarket wallet as pUSD. The Safe must also hold a separate 1.00 USDC Felix network fee, paid atomically in the same owner-signed transaction; it is not refunded if Relay later returns the principal. Before signing, the client verifies the Relay order, solver, amounts, refunds and the exact Safe calls, then journals its signature. Select the account with use_child_account first. Reuse the same idempotency_key after a timeout; never start a new funding to work around an uncertain outcome.",
|
|
13224
|
+
inputSchema: schema({
|
|
13225
|
+
amount_usd: numberProp("Exact transfer principal, 5 to 25 USDC, at most six decimals. Excludes the additional 1.00 USDC Felix fee.", 5, 25),
|
|
13226
|
+
minimum_credit_usd: numberProp("Optional: refuse unless Relay signs at least this Polygon USDC.e credit.", 0.000001, 25),
|
|
13227
|
+
idempotency_key: stringProp("Required workflow replay key. Reuse it to resume this exact funding."),
|
|
13228
|
+
}, ["amount_usd", "idempotency_key"]),
|
|
13229
|
+
},
|
|
13230
|
+
{
|
|
12455
13231
|
name: "invalidate_safe_nonce",
|
|
12456
13232
|
description: "Not available in this build: refuses before any request (it needs an independent chain proof that the no-op executed, which this client does not have). Release a stuck Safe nonce in the Felix app (Wallet) instead. Release this account's Arc home Safe nonce that an earlier Felix operation reserved but never executed (an expired, cancelled or observe-only HyperCore or Polymarket funding, or a same-chain Arc withdrawal). While such a nonce is reserved, every later Felix Safe move is refused. The owner signs ONE no-op Safe transaction (a call to the owner's own address, value 0, no data) at that nonce: it moves no funds, and once it executes the original can never execute. Before signing, the client rebuilds the no-op itself, checks it is for this account's Safe at the original's nonce, and proves the Safe's current nonce on its own private Arc quorum (FELIX_ARC_PROOF_RPC_URLS). Completion requires the engine's proof, this client's own proof that exactly this no-op executed, and Felix closing the original operation. If the original executed first, nothing is closed; resume the original instead. Use the exact original_writer and original_operation_id from the next_action of the tool that reported the reserved nonce. Felix keeps ONE invalidation per Safe nonce: when one already exists (next_action complete_invalidation), pass its invalidation_id to complete it instead of preparing a new one. Never use this tool while the blocking operation's next_action is reconcile_blocking_operation: its Safe transaction may still execute. Reuse the same idempotency_key after a timeout; nothing is signed twice.",
|
|
12457
13233
|
inputSchema: schema({
|
|
@@ -12500,9 +13276,9 @@ const TOOLS = [
|
|
|
12500
13276
|
},
|
|
12501
13277
|
{
|
|
12502
13278
|
name: "arc_home_fund_venue",
|
|
12503
|
-
description: "
|
|
13279
|
+
description: "LEGACY: for accounts that still have a Polygon owner wallet record. A new account funds Polymarket with fund_polymarket_from_arc and Hyperliquid with fund_hypercore_from_arc instead (this tool answers arc_home_venue_wallet_unavailable for them). Stages Polymarket funding from the Arc home Safe: an owner-signed Circle Gateway withdrawal whose destination Felix resolves to this account's own Polygon owner wallet (the client refuses any other destination before signing). Completion is native USDC in the Polygon owner wallet, NOT Polymarket collateral: the result sets venue_funded=false and returns next_action fund_market(venue=prediction_market), a separate owner-signed call. Hyperliquid and Derive are refused before anything is prepared. Not live-certified on this release.",
|
|
12504
13280
|
inputSchema: schema({
|
|
12505
|
-
venue: stringProp("Destination venue. Only polymarket is supported by this
|
|
13281
|
+
venue: stringProp("Destination venue. Only polymarket is supported by this tool; for Hyperliquid use fund_hypercore_from_arc."),
|
|
12506
13282
|
amount_usd: numberProp("USDC to deliver to the Polygon owner wallet, at most six decimals.", 0.000001, ARC_HOME_MAX_AMOUNT_USD),
|
|
12507
13283
|
max_fee_usd: numberProp("Owner-paid Circle Gateway fee ceiling. Defaults to 0.05.", 0.000001, ARC_HOME_MAX_FEE_USD),
|
|
12508
13284
|
submit_destination_mint: booleanProp("Also broadcast the final Polygon mint into the owner wallet with the owner key through your own FELIX_POLYGON_RPC_URL. Defaults to true; that gas is owner paid."),
|
|
@@ -12571,12 +13347,12 @@ const TOOLS = [
|
|
|
12571
13347
|
},
|
|
12572
13348
|
{
|
|
12573
13349
|
name: "get_fee_balance",
|
|
12574
|
-
description: "Read prepaid execution-fee credit.
|
|
13350
|
+
description: "Read any prepaid execution-fee credit left from earlier releases. New orders do not need it: Felix's fee is charged from the trading account after each fill and never blocks an order. Withdrawals never collect trading fees.",
|
|
12575
13351
|
inputSchema: schema({}),
|
|
12576
13352
|
},
|
|
12577
13353
|
{
|
|
12578
13354
|
name: "preview_fee_top_up",
|
|
12579
|
-
description: "Preview an owner-signed execution-fee credit top-up without signing or exposing Felix's collection address. Nothing moves until top_up_fee_balance is called.",
|
|
13355
|
+
description: "Legacy, not needed to trade (Felix's fee is charged after each fill). Preview an owner-signed execution-fee credit top-up without signing or exposing Felix's collection address. Nothing moves until top_up_fee_balance is called.",
|
|
12580
13356
|
inputSchema: schema({
|
|
12581
13357
|
amount_usd: numberProp("USDC.e amount to prepay for future live execution fees.", 0.1, 10_000),
|
|
12582
13358
|
idempotency_key: stringProp("Required workflow replay key. Reuse this exact key for top_up_fee_balance."),
|
|
@@ -12584,7 +13360,7 @@ const TOOLS = [
|
|
|
12584
13360
|
},
|
|
12585
13361
|
{
|
|
12586
13362
|
name: "top_up_fee_balance",
|
|
12587
|
-
description: "
|
|
13363
|
+
description: "Legacy: sign one bounded USDC.e transfer locally and credit it as prepaid execution-fee credit (accounts with a Polygon owner wallet only). Not needed to trade: Felix's fee is charged from the trading account after each fill and never blocks an order.",
|
|
12588
13364
|
inputSchema: schema({
|
|
12589
13365
|
amount_usd: numberProp("USDC.e amount to prepay for future live execution fees.", 0.1, 10_000),
|
|
12590
13366
|
idempotency_key: stringProp("Required workflow replay key. Reuse it after any timeout or restart."),
|
|
@@ -12593,7 +13369,7 @@ const TOOLS = [
|
|
|
12593
13369
|
},
|
|
12594
13370
|
{
|
|
12595
13371
|
name: "preview_fee_settlement",
|
|
12596
|
-
description: "Deprecated compatibility alias for preview_fee_top_up. It previews prepaid execution-fee credit and never exposes the collection address.",
|
|
13372
|
+
description: "Legacy, not needed to trade. Deprecated compatibility alias for preview_fee_top_up. It previews prepaid execution-fee credit and never exposes the collection address.",
|
|
12597
13373
|
inputSchema: schema({
|
|
12598
13374
|
amount_usd: numberProp("USDC.e amount to prepay for future live execution fees.", 0.1, 10_000),
|
|
12599
13375
|
idempotency_key: stringProp("Required workflow replay key. Reuse this exact key for settle_fees."),
|
|
@@ -12601,7 +13377,7 @@ const TOOLS = [
|
|
|
12601
13377
|
},
|
|
12602
13378
|
{
|
|
12603
13379
|
name: "settle_fees",
|
|
12604
|
-
description: "Deprecated compatibility alias for top_up_fee_balance. It adds prepaid credit; it does not settle debt and is never called by withdrawals.",
|
|
13380
|
+
description: "Legacy, not needed to trade. Deprecated compatibility alias for top_up_fee_balance. It adds prepaid credit; it does not settle debt and is never called by withdrawals.",
|
|
12605
13381
|
inputSchema: schema({
|
|
12606
13382
|
amount_usd: numberProp("USDC.e amount to prepay for future live execution fees.", 0.1, 10_000),
|
|
12607
13383
|
idempotency_key: stringProp("Required workflow replay key. Reuse it after any timeout or restart."),
|
|
@@ -12689,7 +13465,7 @@ const TOOLS = [
|
|
|
12689
13465
|
},
|
|
12690
13466
|
{
|
|
12691
13467
|
name: "init_wallet_onboarding",
|
|
12692
|
-
description: `Start advanced client-owned Safe onboarding. The owner key must be generated and retained outside Felix; only public addresses are sent. Read ${GETTING_STARTED_GUIDE_URI} before implementing the signing flow.`,
|
|
13468
|
+
description: `RETIRED: Polygon Safe wallets are retired and Felix answers 410 polygon_safe_hub_retired; every account's wallet is its Arc home Safe (fund it with create_deposit; stop all trading with panic). Start advanced client-owned Safe onboarding. The owner key must be generated and retained outside Felix; only public addresses are sent. Read ${GETTING_STARTED_GUIDE_URI} before implementing the signing flow.`,
|
|
12693
13469
|
inputSchema: schema({
|
|
12694
13470
|
owner_address: stringProp("Client-owned EVM address.", undefined, { pattern: EVM_ADDRESS_RE.source }),
|
|
12695
13471
|
home_address: stringProp("Optional fixed sweep-home address. Defaults to owner.", undefined, { pattern: EVM_ADDRESS_RE.source }),
|
|
@@ -12703,7 +13479,7 @@ const TOOLS = [
|
|
|
12703
13479
|
},
|
|
12704
13480
|
{
|
|
12705
13481
|
name: "deploy_wallet_onboarding",
|
|
12706
|
-
description: `Verify the owner's locally validated personal-sign challenge and activate the Safe policy wallet. Accepts a signature, never the owner key. Follow ${GETTING_STARTED_GUIDE_URI}.`,
|
|
13482
|
+
description: `RETIRED: Polygon Safe wallets are retired and Felix answers 410 polygon_safe_hub_retired; every account's wallet is its Arc home Safe (fund it with create_deposit; stop all trading with panic). Verify the owner's locally validated personal-sign challenge and activate the Safe policy wallet. Accepts a signature, never the owner key. Follow ${GETTING_STARTED_GUIDE_URI}.`,
|
|
12707
13483
|
inputSchema: schema({
|
|
12708
13484
|
onboarding_id: stringProp("Onboarding UUID.", undefined, { pattern: UUID_RE.source }),
|
|
12709
13485
|
proof_signature: stringProp("0x-prefixed 65-byte owner proof signature.", undefined, { pattern: EVM_SIGNATURE_RE.source }),
|
|
@@ -12713,7 +13489,7 @@ const TOOLS = [
|
|
|
12713
13489
|
},
|
|
12714
13490
|
{
|
|
12715
13491
|
name: "complete_wallet_onboarding",
|
|
12716
|
-
description: `Verify and relay the owner's locally validated exact Safe module-enable and fallback-handler signatures, then link the client-owned wallet. Follow ${GETTING_STARTED_GUIDE_URI}.`,
|
|
13492
|
+
description: `RETIRED: Polygon Safe wallets are retired and Felix answers 410 polygon_safe_hub_retired; every account's wallet is its Arc home Safe (fund it with create_deposit; stop all trading with panic). Verify and relay the owner's locally validated exact Safe module-enable and fallback-handler signatures, then link the client-owned wallet. Follow ${GETTING_STARTED_GUIDE_URI}.`,
|
|
12717
13493
|
inputSchema: schema({
|
|
12718
13494
|
onboarding_id: stringProp("Onboarding UUID.", undefined, { pattern: UUID_RE.source }),
|
|
12719
13495
|
enable_signature: stringProp("0x-prefixed 65-byte canonical Safe signature.", undefined, { pattern: EVM_SIGNATURE_RE.source }),
|
|
@@ -12732,7 +13508,7 @@ const TOOLS = [
|
|
|
12732
13508
|
},
|
|
12733
13509
|
{
|
|
12734
13510
|
name: "migrate_wallet_to_v3",
|
|
12735
|
-
description: "Migrate a caller-owned legacy Safe to Felix V3 in one resumable local workflow: prove ownership, deploy only the V3 policy, locally execute enable/fallback/disable-V2, and confirm atomic account promotion.",
|
|
13511
|
+
description: "RETIRED: Polygon Safe wallets are retired and Felix answers 410 polygon_safe_hub_retired; every account's wallet is its Arc home Safe (fund it with create_deposit; stop all trading with panic). Migrate a caller-owned legacy Safe to Felix V3 in one resumable local workflow: prove ownership, deploy only the V3 policy, locally execute enable/fallback/disable-V2, and confirm atomic account promotion.",
|
|
12736
13512
|
inputSchema: schema({
|
|
12737
13513
|
max_operation_usd: numberProp("Maximum autonomous operation size. Defaults to the legacy wallet limit.", 0),
|
|
12738
13514
|
daily_limit_usd: numberProp("Maximum autonomous daily total. Defaults to the legacy wallet limit.", 0),
|
|
@@ -12745,7 +13521,7 @@ const TOOLS = [
|
|
|
12745
13521
|
},
|
|
12746
13522
|
{
|
|
12747
13523
|
name: "prepare_wallet_policy",
|
|
12748
|
-
description: "Prepare an owner-signed Safe V3 pause, resume, renewal, or emergency lockdown. Lockdown atomically pauses the agent and revokes fixed Polymarket approvals.",
|
|
13524
|
+
description: "RETIRED: Polygon Safe wallets are retired and Felix answers 410 polygon_safe_hub_retired; every account's wallet is its Arc home Safe (fund it with create_deposit; stop all trading with panic). Prepare an owner-signed Safe V3 pause, resume, renewal, or emergency lockdown. Lockdown atomically pauses the agent and revokes fixed Polymarket approvals.",
|
|
12749
13525
|
inputSchema: schema({
|
|
12750
13526
|
action: stringProp("pause|resume|renew|lockdown.", ["pause", "resume", "renew", "lockdown"]),
|
|
12751
13527
|
delegation_days: integerProp("Renewal lifetime in days. Valid only for renew; maximum 90.", 1, 90),
|
|
@@ -12755,7 +13531,7 @@ const TOOLS = [
|
|
|
12755
13531
|
},
|
|
12756
13532
|
{
|
|
12757
13533
|
name: "submit_wallet_policy",
|
|
12758
|
-
description: "Relay an exact owner-signed Safe V3 policy transaction. Accepts only the sealed policy token and canonical Safe signature.",
|
|
13534
|
+
description: "RETIRED: Polygon Safe wallets are retired and Felix answers 410 polygon_safe_hub_retired; every account's wallet is its Arc home Safe (fund it with create_deposit; stop all trading with panic). Relay an exact owner-signed Safe V3 policy transaction. Accepts only the sealed policy token and canonical Safe signature.",
|
|
12759
13535
|
inputSchema: schema({
|
|
12760
13536
|
policy_token: stringProp("Opaque sealed policy intent returned by prepare_wallet_policy.", undefined, { minLength: 1, maxLength: 16000 }),
|
|
12761
13537
|
owner_signature: stringProp("0x-prefixed 65-byte canonical EIP-712 signature.", undefined, { pattern: EVM_SIGNATURE_RE.source }),
|
|
@@ -12765,7 +13541,7 @@ const TOOLS = [
|
|
|
12765
13541
|
},
|
|
12766
13542
|
{
|
|
12767
13543
|
name: "update_wallet_policy",
|
|
12768
|
-
description: "Locally verify, sign, and relay a Safe V3 pause, resume, renewal, or emergency lockdown in one replay-safe workflow. Lockdown also revokes fixed Polymarket approvals.",
|
|
13544
|
+
description: "RETIRED: Polygon Safe wallets are retired and Felix answers 410 polygon_safe_hub_retired; every account's wallet is its Arc home Safe (fund it with create_deposit; stop all trading with panic). Locally verify, sign, and relay a Safe V3 pause, resume, renewal, or emergency lockdown in one replay-safe workflow. Lockdown also revokes fixed Polymarket approvals.",
|
|
12769
13545
|
inputSchema: schema({
|
|
12770
13546
|
action: stringProp("pause|resume|renew|lockdown.", ["pause", "resume", "renew", "lockdown"]),
|
|
12771
13547
|
delegation_days: integerProp("Renewal lifetime in days. Valid only for renew; maximum 90.", 1, 90),
|
|
@@ -13210,13 +13986,15 @@ const TOOLS = [
|
|
|
13210
13986
|
},
|
|
13211
13987
|
{
|
|
13212
13988
|
name: "create_account",
|
|
13213
|
-
description: `Create a real-money Felix account. The first call reserves one isolated identity
|
|
13989
|
+
description: `Create a real-money Felix account, like app.felix.trade. The first call reserves one isolated identity, binds its owner, and (until the account's Arc home holds the $5 minimum) returns account_funding_required with deposit_flow: pay with create_deposit, then retry the exact same idempotency_key; it never hands out a Polygon address. Felix then sets up and verifies the Arc home Safe/module, signs the account owner's trading policy locally (the app's device trading policy: no risk limits, Hyperliquid fast-custody trade keys, and Lighter Premium with Felix partner fees, returned in trading_policy), and mints a live key. The $5 deposit does not fund a first live trade: fund the venue with fund_hypercore_from_arc or fund_polymarket_from_arc. No prepaid fee credit is needed; Felix's fee is charged after each fill. Emits progress every 15 seconds. Requires the registered local owner signer and launcher manage key. Cold start: ${GETTING_STARTED_GUIDE_URI}.`,
|
|
13214
13990
|
inputSchema: schema({
|
|
13215
13991
|
email: stringProp("Optional new email for the isolated child. Omit to generate an internal identity."),
|
|
13216
13992
|
label: stringProp("Optional account/live-key label."),
|
|
13217
13993
|
accept_terms: { type: "boolean", const: true, description: "Must be true to confirm acceptance of Felix Terms of Service, Privacy Policy, and Risk Disclosure." },
|
|
13218
13994
|
legal_version: { type: "string", const: FELIX_LEGAL_BUNDLE_VERSION, default: FELIX_LEGAL_BUNDLE_VERSION, description: "Current Felix legal bundle version. Omit to use the version bundled with this MCP build." },
|
|
13219
13995
|
idempotency_key: stringProp("Stable account-creation key. Reuse the exact value after any interruption."),
|
|
13996
|
+
accept_trading_policy: booleanProp("Only after the owner answered yes to the trading_policy_question this tool returned."),
|
|
13997
|
+
trading_policy_terms_id: stringProp("The trading_policy_terms_id from that question."),
|
|
13220
13998
|
max_order_usd: numberProp("Optional owner-authorized per-order safety ceiling. Defaults/maxes at the account's $10M operation limit.", 1, DEFAULT_WALLET_OPERATION_USD),
|
|
13221
13999
|
max_daily_usd: numberProp("Optional owner-authorized daily notional safety ceiling. Defaults/maxes at the account's $100M daily limit.", 1, DEFAULT_WALLET_DAILY_USD),
|
|
13222
14000
|
max_daily_loss_usd: numberProp("Optional owner-authorized daily loss safety ceiling. Defaults/maxes at $100M.", 1, DEFAULT_WALLET_DAILY_USD),
|
|
@@ -13447,6 +14225,7 @@ export function makeServer() {
|
|
|
13447
14225
|
contents: [{ uri: req.params.uri, mimeType: "text/markdown", text: content }],
|
|
13448
14226
|
};
|
|
13449
14227
|
});
|
|
14228
|
+
tradingPolicyAskServer = server;
|
|
13450
14229
|
server.setRequestHandler(CallToolRequestSchema, async (req) => withWorkflowBinding(req.params.name, req.params.arguments || {}, async () => {
|
|
13451
14230
|
const name = req.params.name;
|
|
13452
14231
|
const a = (req.params.arguments || {});
|
|
@@ -15055,21 +15834,82 @@ export function makeServer() {
|
|
|
15055
15834
|
case "place_manual_order": {
|
|
15056
15835
|
// Same local pre-send checks as place_order: the operator's local cap on opening orders, an explicit
|
|
15057
15836
|
// key for Home funding, and the durable live-mutation journal so a generated key survives a restart.
|
|
15837
|
+
let signedTradingPolicy;
|
|
15058
15838
|
const opening = a.reduce_only !== true
|
|
15059
15839
|
&& !(String(a.instrument || "").toLowerCase().startsWith("pm:") && String(a.side || "").toLowerCase() === "sell");
|
|
15060
15840
|
if (opening && Number(a.size_usd) > maxLocalLiveOrderUsd()) {
|
|
15061
15841
|
out = clientError("local_safety_cap", "Live order exceeds the local FELIX_MAX_LIVE_ORDER_USD safety cap.", "Raise the local cap only after reviewing the API key's durable server-side limits.");
|
|
15062
15842
|
break;
|
|
15063
15843
|
}
|
|
15844
|
+
if (a.funding !== undefined) {
|
|
15845
|
+
const funding = a.funding;
|
|
15846
|
+
const fields = ["max_source_units", "max_fee_units", "expires_at"];
|
|
15847
|
+
if (!isRecord(funding) || Object.keys(funding).length !== fields.length
|
|
15848
|
+
|| !fields.every((field) => Number.isSafeInteger(funding[field]) && Number(funding[field]) >= 0)
|
|
15849
|
+
|| Number(funding.max_source_units) <= 0) {
|
|
15850
|
+
out = clientError("invalid_argument", "funding must be {max_source_units, max_fee_units, expires_at} with whole-number values (USDC 6-decimal units; expires_at in Unix seconds).", "For example $10 is max_source_units: 10000000. Nothing was sent.");
|
|
15851
|
+
break;
|
|
15852
|
+
}
|
|
15853
|
+
}
|
|
15854
|
+
if (a.funding !== undefined && activeChildAccountId()) {
|
|
15855
|
+
// Release B is policy only (owner 2026-11-17): funding an order from Home needs a 'transfer'-scoped key, and
|
|
15856
|
+
// an account's trading key is read/trade. Fund the venue first, then place the order without funding.
|
|
15857
|
+
out = clientError("home_funding_needs_transfer_scope", "This account's trading key cannot fund an order from Home. Fund the venue first, then place the order without funding.", "Hyperliquid: fund_hypercore_from_arc; Polymarket: fund_polymarket_from_arc (5 to 25 USDC from the Arc home each), "
|
|
15858
|
+
+ "then place_manual_order without funding. Nothing was sent.", { money_moved: false, order_sent: false });
|
|
15859
|
+
break;
|
|
15860
|
+
}
|
|
15064
15861
|
if (a.funding !== undefined && !nonEmptyString(a.idempotency_key)) {
|
|
15065
15862
|
out = clientError("idempotency_key_required", "idempotency_key is required when the order carries funding from Home.", "Choose a stable key and reuse it for every retry and for get_manual_order_receipt.");
|
|
15066
15863
|
break;
|
|
15067
15864
|
}
|
|
15865
|
+
if (!isHostedTransport()) {
|
|
15866
|
+
const childId = activeChildAccountId();
|
|
15867
|
+
const ownerKey = await arcHomeOwnerKeyFor(childId);
|
|
15868
|
+
if (EVM_PRIVATE_KEY_RE.test(ownerKey)) {
|
|
15869
|
+
const policy = await ensureManualTradingPolicy(childId, ownerKey, childId ? START_KEY : undefined, {
|
|
15870
|
+
accepted: a.accept_trading_policy === true,
|
|
15871
|
+
termsId: nonEmptyString(a.trading_policy_terms_id),
|
|
15872
|
+
});
|
|
15873
|
+
if (policy.ok === false && !manualTradingPolicyNotSupported(policy)) {
|
|
15874
|
+
out = { ...policy, money_moved: false, order_sent: false };
|
|
15875
|
+
break;
|
|
15876
|
+
}
|
|
15877
|
+
if (policy.ok !== false && isRecord(policy.policy))
|
|
15878
|
+
signedTradingPolicy = policy.policy;
|
|
15879
|
+
if (policy.ok !== false && policy.status === "ready_renewal_pending") {
|
|
15880
|
+
signedTradingPolicy = {
|
|
15881
|
+
status: "renewal_pending", renewal_status: policy.renewal_status,
|
|
15882
|
+
current_policy_expires_at: policy.mandate_expires_at,
|
|
15883
|
+
...(policy.renewal_question ? { renewal_question: policy.renewal_question,
|
|
15884
|
+
renewal_terms_id: policy.renewal_terms_id } : {}),
|
|
15885
|
+
};
|
|
15886
|
+
}
|
|
15887
|
+
}
|
|
15888
|
+
}
|
|
15068
15889
|
liveMutation = beginLiveMutation("place_manual_order", a);
|
|
15069
15890
|
out = await call("POST", "/v1/manual/orders", manualOrderBody(a), {
|
|
15070
15891
|
idempotent: true, retryOnError: false, timeoutMs: 60_000,
|
|
15071
15892
|
idempotencyKey: nonEmptyString(a.idempotency_key) || undefined,
|
|
15072
15893
|
});
|
|
15894
|
+
if (out.ok === false) {
|
|
15895
|
+
// Opus QA r5: a 5xx, HTML, timeout or reset answer does not prove the order was not placed.
|
|
15896
|
+
const meta = isRecord(out._meta) ? out._meta : {};
|
|
15897
|
+
const status = finiteNumber(meta.http_status);
|
|
15898
|
+
const code = isRecord(out.error) ? nonEmptyString(out.error.code) : undefined;
|
|
15899
|
+
if ((status !== undefined && status >= 500)
|
|
15900
|
+
|| ["network_error", "timeout", "request_deadline_exceeded", "request_outcome_unknown"].includes(code || "")) {
|
|
15901
|
+
out = {
|
|
15902
|
+
...out, outcome_unknown: true, money_moved: "unknown",
|
|
15903
|
+
recovery: {
|
|
15904
|
+
read_tool: "get_manual_order_receipt",
|
|
15905
|
+
reuse_same_idempotency_key: true,
|
|
15906
|
+
note: "Read the outcome with get_manual_order_receipt and the same idempotency_key before retrying. Never retry with a new key.",
|
|
15907
|
+
},
|
|
15908
|
+
};
|
|
15909
|
+
}
|
|
15910
|
+
}
|
|
15911
|
+
if (signedTradingPolicy)
|
|
15912
|
+
out = { ...out, trading_policy: signedTradingPolicy };
|
|
15073
15913
|
break;
|
|
15074
15914
|
}
|
|
15075
15915
|
case "get_manual_order_receipt":
|
|
@@ -15747,7 +16587,13 @@ export function makeServer() {
|
|
|
15747
16587
|
break;
|
|
15748
16588
|
}
|
|
15749
16589
|
case "get_deposit_address":
|
|
15750
|
-
out = await
|
|
16590
|
+
out = await getArcDepositView(a);
|
|
16591
|
+
break;
|
|
16592
|
+
case "create_deposit":
|
|
16593
|
+
out = await createArcDeposit(a);
|
|
16594
|
+
break;
|
|
16595
|
+
case "cancel_deposit":
|
|
16596
|
+
out = await cancelArcDeposit(a);
|
|
15751
16597
|
break;
|
|
15752
16598
|
case "verify_custody":
|
|
15753
16599
|
out = (a.account_id !== undefined && validateUuid(a, "account_id"))
|
|
@@ -16121,9 +16967,10 @@ export function makeServer() {
|
|
|
16121
16967
|
}
|
|
16122
16968
|
case "arc_home_fund_venue": {
|
|
16123
16969
|
const venue = nonEmptyString(a.venue)?.toLowerCase();
|
|
16124
|
-
const unsupported = venue
|
|
16970
|
+
const unsupported = venue && Object.hasOwn(ARC_HOME_UNSUPPORTED_VENUES, venue)
|
|
16971
|
+
? ARC_HOME_UNSUPPORTED_VENUES[venue] : undefined;
|
|
16125
16972
|
const bad = (unsupported
|
|
16126
|
-
? clientError("arc_home_venue_unsupported", unsupported, "Nothing was prepared or signed.
|
|
16973
|
+
? clientError("arc_home_venue_unsupported", unsupported, "Nothing was prepared or signed. Fund Hyperliquid with fund_hypercore_from_arc and Polymarket with fund_polymarket_from_arc.", { venue, money_moved: false })
|
|
16127
16974
|
: undefined)
|
|
16128
16975
|
|| (!venue || !ARC_HOME_VENUES.includes(venue)
|
|
16129
16976
|
? clientError("invalid_argument", `venue must be one of ${ARC_HOME_VENUES.join(", ")}.`)
|
|
@@ -16182,6 +17029,29 @@ export function makeServer() {
|
|
|
16182
17029
|
out = await postArcHomeOperationTool(a, "mint-submitted", { mint_tx_hash: hash }, true);
|
|
16183
17030
|
break;
|
|
16184
17031
|
}
|
|
17032
|
+
case "fund_polymarket_from_arc": {
|
|
17033
|
+
const key = requiredWorkflowKey(a);
|
|
17034
|
+
const amount = finiteNumber(a.amount_usd);
|
|
17035
|
+
const minimum = a.minimum_credit_usd === undefined ? undefined : finiteNumber(a.minimum_credit_usd);
|
|
17036
|
+
if (!ARC_POLYGON_CLIENT_ENABLED) {
|
|
17037
|
+
out = markMoneyNotStarted(clientError("arc_polygon_not_launch_enabled", "The Arc home -> Polymarket route is not enabled in this Felix MCP build.", "Nothing was prepared or signed."));
|
|
17038
|
+
}
|
|
17039
|
+
else if (!key) {
|
|
17040
|
+
out = clientError("missing_argument", "idempotency_key is required (1-128 printable characters).");
|
|
17041
|
+
}
|
|
17042
|
+
else if (amount === undefined || amount < 5 || amount > 25
|
|
17043
|
+
|| (a.minimum_credit_usd !== undefined && (minimum === undefined || minimum <= 0 || minimum > amount))) {
|
|
17044
|
+
out = markMoneyNotStarted(clientError("invalid_argument", "amount_usd must be 5 to 25; minimum_credit_usd, when set, must be positive and at most amount_usd."));
|
|
17045
|
+
}
|
|
17046
|
+
else if (!runtimeManagedAccountId || !UUID_RE.test(runtimeManagedAccountId)) {
|
|
17047
|
+
out = markMoneyNotStarted(clientError("child_account_required", "Select the funding account with use_child_account first.", "Nothing was prepared or signed."));
|
|
17048
|
+
}
|
|
17049
|
+
else {
|
|
17050
|
+
const accountId = runtimeManagedAccountId;
|
|
17051
|
+
out = requireLocalSigner() || await runMoneyWorkflow(key, "arc_polygon_funding", { amount_usd: amount, minimum_credit_usd: minimum ?? null, account_id: accountId }, (context) => executeArcPolygonFunding(amount, minimum, key, context, accountId), { resumable: true });
|
|
17052
|
+
}
|
|
17053
|
+
break;
|
|
17054
|
+
}
|
|
16185
17055
|
case "fund_hypercore_from_arc": {
|
|
16186
17056
|
if (!HYPERCORE_DIRECT_CLIENT_ENABLED) {
|
|
16187
17057
|
out = markMoneyNotStarted(clientError("hypercore_direct_not_launch_enabled", "The direct Arc home -> HyperCore route is not enabled in this Felix MCP build.", "Nothing was prepared or signed."));
|
|
@@ -18050,8 +18920,63 @@ export function makeServer() {
|
|
|
18050
18920
|
lifetime_limit_usd: lifetimeLimitUsd,
|
|
18051
18921
|
delegation_days: delegationDays,
|
|
18052
18922
|
};
|
|
18053
|
-
async function
|
|
18923
|
+
async function mintAccountKeyOnly(accountId, accountOwnerKey, journal) {
|
|
18924
|
+
const keyLabel = nonEmptyString(a.label) || "primary live key";
|
|
18925
|
+
// Opus QA r5 F1: the signed grant is journaled before it is submitted. A lost submit response is resumed
|
|
18926
|
+
// with the SAME signed grant (the engine answers a repeat with the minted key's id, which is revoked and
|
|
18927
|
+
// reminted below), never with a fresh grant that would leave the first key active.
|
|
18928
|
+
// A revoke answered not_found counts as done only once a fresh key list confirms the key is no longer
|
|
18929
|
+
// active on this account (fail closed: a list that cannot be read refuses).
|
|
18930
|
+
async function confirmKeyInactive(keyId) {
|
|
18931
|
+
const listed = await call("GET", `/v1/keys${qs({ account_id: accountId })}`, undefined, { authKey: START_KEY, timeoutMs: 30_000 });
|
|
18932
|
+
if (listed.ok === false)
|
|
18933
|
+
return listed;
|
|
18934
|
+
if (!Array.isArray(listed.keys)) {
|
|
18935
|
+
return clientError("live_key_revoke_unconfirmed", "Felix could not confirm the earlier live key was revoked. Nothing new was minted.", "Retry create_account with the same idempotency_key.", { money_moved: false });
|
|
18936
|
+
}
|
|
18937
|
+
const stillActive = listed.keys.some((key) => isRecord(key) && nonEmptyString(key.id) === keyId
|
|
18938
|
+
&& key.status !== "revoked" && key.status !== "deleted");
|
|
18939
|
+
return stillActive ? clientError("live_key_revoke_unconfirmed", "Felix says the earlier live key was not found, but it is still listed as active. Nothing new was minted.", "Retry create_account with the same idempotency_key.", { money_moved: false }) : undefined;
|
|
18940
|
+
}
|
|
18941
|
+
async function revokeWorkflowKeys() {
|
|
18942
|
+
const listed = await call("GET", `/v1/keys${qs({ account_id: accountId })}`, undefined, { authKey: START_KEY, timeoutMs: 30_000 });
|
|
18943
|
+
if (listed.ok === false || !Array.isArray(listed.keys))
|
|
18944
|
+
return listed.ok === false ? listed : undefined;
|
|
18945
|
+
for (const key of listed.keys) {
|
|
18946
|
+
if (!isRecord(key) || key.status !== "active" || key.label !== keyLabel || key.live_enabled === false)
|
|
18947
|
+
continue;
|
|
18948
|
+
const id = nonEmptyString(key.id);
|
|
18949
|
+
if (!id || !UUID_RE.test(id))
|
|
18950
|
+
continue;
|
|
18951
|
+
const revoked = await call("DELETE", `/v1/keys/${enc(id)}${qs({ account_id: accountId })}`, undefined, { authKey: START_KEY, retryOnError: false, timeoutMs: 30_000 });
|
|
18952
|
+
const code = isRecord(revoked.error) ? nonEmptyString(revoked.error.code) : undefined;
|
|
18953
|
+
if (revoked.ok === false && code !== "not_found")
|
|
18954
|
+
return revoked;
|
|
18955
|
+
if (revoked.ok === false) {
|
|
18956
|
+
const unconfirmed = await confirmKeyInactive(id);
|
|
18957
|
+
if (unconfirmed)
|
|
18958
|
+
return unconfirmed;
|
|
18959
|
+
}
|
|
18960
|
+
}
|
|
18961
|
+
return undefined;
|
|
18962
|
+
}
|
|
18054
18963
|
async function mintOnce() {
|
|
18964
|
+
const saved = journal?.getCheckpoint("account:live_key_grant");
|
|
18965
|
+
const savedExpires = finiteNumber(saved?.expires_at);
|
|
18966
|
+
if (saved && typeof saved.message === "string" && typeof saved.signature === "string"
|
|
18967
|
+
&& savedExpires !== undefined && savedExpires > Math.floor(Date.now() / 1000) + 30) {
|
|
18968
|
+
return call("POST", "/v1/keys/live/submit", {
|
|
18969
|
+
account_id: accountId, message: saved.message, signature: saved.signature, label: keyLabel,
|
|
18970
|
+
}, { retryOnError: false, timeoutMs: 60_000 });
|
|
18971
|
+
}
|
|
18972
|
+
if (saved) {
|
|
18973
|
+
// An expired grant may already have minted a key whose response was lost: revoke this workflow's keys
|
|
18974
|
+
// on this new account before minting the replacement.
|
|
18975
|
+
const cleanup = await revokeWorkflowKeys();
|
|
18976
|
+
if (cleanup)
|
|
18977
|
+
return cleanup;
|
|
18978
|
+
journal?.deleteCheckpoint("account:live_key_grant");
|
|
18979
|
+
}
|
|
18055
18980
|
const prepared = await call("POST", "/v1/keys/live/prepare", {
|
|
18056
18981
|
account_id: accountId,
|
|
18057
18982
|
scopes: ["read", "trade"],
|
|
@@ -18068,11 +18993,16 @@ export function makeServer() {
|
|
|
18068
18993
|
maxDailyUsd,
|
|
18069
18994
|
maxDailyLossUsd,
|
|
18070
18995
|
});
|
|
18996
|
+
const grantExpires = Number(String(prepared.message).match(/\nexpires_at:(\d+)/)?.[1]);
|
|
18997
|
+
journal?.saveCheckpoint("account:live_key_grant", {
|
|
18998
|
+
message: prepared.message, signature,
|
|
18999
|
+
expires_at: Number.isSafeInteger(grantExpires) ? grantExpires : Math.floor(Date.now() / 1000) + 300,
|
|
19000
|
+
});
|
|
18071
19001
|
return call("POST", "/v1/keys/live/submit", {
|
|
18072
19002
|
account_id: accountId,
|
|
18073
19003
|
message: prepared.message,
|
|
18074
19004
|
signature,
|
|
18075
|
-
label:
|
|
19005
|
+
label: keyLabel,
|
|
18076
19006
|
}, { retryOnError: false, timeoutMs: 60_000 });
|
|
18077
19007
|
}
|
|
18078
19008
|
let minted = await mintOnce();
|
|
@@ -18082,8 +19012,15 @@ export function makeServer() {
|
|
|
18082
19012
|
throw new Error("Felix did not return a usable live key or revocable key id.");
|
|
18083
19013
|
}
|
|
18084
19014
|
const revoked = await call("DELETE", `/v1/keys/${enc(lostKeyId)}${qs({ account_id: accountId })}`);
|
|
18085
|
-
|
|
19015
|
+
const revokeCode = isRecord(revoked.error) ? nonEmptyString(revoked.error.code) : undefined;
|
|
19016
|
+
if (revoked.ok === false && revokeCode !== "not_found")
|
|
18086
19017
|
return revoked;
|
|
19018
|
+
if (revoked.ok === false) {
|
|
19019
|
+
const unconfirmed = await confirmKeyInactive(lostKeyId);
|
|
19020
|
+
if (unconfirmed)
|
|
19021
|
+
return unconfirmed;
|
|
19022
|
+
}
|
|
19023
|
+
journal?.deleteCheckpoint("account:live_key_grant");
|
|
18087
19024
|
minted = await mintOnce();
|
|
18088
19025
|
}
|
|
18089
19026
|
if (minted.ok === false)
|
|
@@ -18093,7 +19030,12 @@ export function makeServer() {
|
|
|
18093
19030
|
if (!apiKey || !API_KEY_RE.test(apiKey) || !keyId || !UUID_RE.test(keyId)) {
|
|
18094
19031
|
throw new Error("Felix returned an invalid owner-authorized live key.");
|
|
18095
19032
|
}
|
|
18096
|
-
|
|
19033
|
+
return { api_key: apiKey, key_id: keyId, prefix: minted.prefix };
|
|
19034
|
+
}
|
|
19035
|
+
// Astra mcploop r4 F1: a live key is minted once per workflow and saved before its mandate is registered;
|
|
19036
|
+
// retries register the mandate for that same key instead of minting another (20-key cap).
|
|
19037
|
+
async function registerLiveKeyMandate(accountId, accountOwnerKey, keyId) {
|
|
19038
|
+
return ensureOwnerRiskMandate({
|
|
18097
19039
|
accountId,
|
|
18098
19040
|
apiKeyId: keyId,
|
|
18099
19041
|
ownerPrivateKey: accountOwnerKey,
|
|
@@ -18104,15 +19046,28 @@ export function makeServer() {
|
|
|
18104
19046
|
authKey: START_KEY,
|
|
18105
19047
|
idempotencyKey: workflowStageKey(workflowKey, "owner-risk-mandate"),
|
|
18106
19048
|
});
|
|
18107
|
-
|
|
19049
|
+
}
|
|
19050
|
+
async function liveKeyActive(accountId, keyId) {
|
|
19051
|
+
const listed = await call("GET", `/v1/keys${qs({ account_id: accountId })}`, undefined, { authKey: START_KEY, timeoutMs: 30_000 });
|
|
19052
|
+
if (listed.ok === false || !Array.isArray(listed.keys))
|
|
19053
|
+
return undefined;
|
|
19054
|
+
return listed.keys.some((key) => isRecord(key) && key.id === keyId && key.status === "active");
|
|
19055
|
+
}
|
|
19056
|
+
async function revokeLiveKey(accountId, keyId) {
|
|
19057
|
+
await call("DELETE", `/v1/keys/${enc(keyId)}${qs({ account_id: accountId })}`, undefined, { authKey: START_KEY, retryOnError: false, timeoutMs: 30_000 }).catch(() => undefined);
|
|
19058
|
+
}
|
|
19059
|
+
async function mintAccountLiveKey(accountId, accountOwnerKey) {
|
|
19060
|
+
const minted = await mintAccountKeyOnly(accountId, accountOwnerKey);
|
|
19061
|
+
if (minted.ok === false)
|
|
19062
|
+
return minted;
|
|
19063
|
+
const keyId = String(minted.key_id);
|
|
19064
|
+
const mandate = await registerLiveKeyMandate(accountId, accountOwnerKey, keyId);
|
|
19065
|
+
if (mandate.ok === false) {
|
|
19066
|
+
// Never leave an unregistered key behind: it would count against the account's live-key cap.
|
|
19067
|
+
await revokeLiveKey(accountId, keyId);
|
|
18108
19068
|
return mandate;
|
|
18109
|
-
|
|
18110
|
-
|
|
18111
|
-
key_id: keyId,
|
|
18112
|
-
prefix: minted.prefix,
|
|
18113
|
-
mandate_id: mandate.mandate_id,
|
|
18114
|
-
mandate_version: mandate.mandate_version,
|
|
18115
|
-
};
|
|
19069
|
+
}
|
|
19070
|
+
return { ...minted, mandate_id: mandate.mandate_id, mandate_version: mandate.mandate_version };
|
|
18116
19071
|
}
|
|
18117
19072
|
const accountProgress = {
|
|
18118
19073
|
"account:created": 1,
|
|
@@ -18198,6 +19153,31 @@ export function makeServer() {
|
|
|
18198
19153
|
|| !confirmedArcHome.modules.some((module) => module.toLowerCase() === expectedArcModule.toLowerCase())) {
|
|
18199
19154
|
return clientError("arc_home_verification_incomplete", "The Arc home Safe and signed module are not verified for this owner.", "Retry create_account with the same idempotency_key; do not create another account.", { account_id: accountId, arc_home_status: "onboarding_incomplete" });
|
|
18200
19155
|
}
|
|
19156
|
+
// MANUAL_POLICY_MCP_20261117: the owner's Manual trading policy, so manual and fund-from-Home orders
|
|
19157
|
+
// work without visiting the site. Non-fatal: place_manual_order retries it before the first order.
|
|
19158
|
+
let manualPolicy = context.getCheckpoint("manual_policy:ready");
|
|
19159
|
+
if (!manualPolicy) {
|
|
19160
|
+
const policy = await ensureManualTradingPolicy(accountId, accountOwnerKey, START_KEY, {
|
|
19161
|
+
accepted: a.accept_trading_policy === true,
|
|
19162
|
+
termsId: nonEmptyString(a.trading_policy_terms_id),
|
|
19163
|
+
});
|
|
19164
|
+
if (policy.ok !== false) {
|
|
19165
|
+
manualPolicy = { status: "ready", ...(isRecord(policy.policy) ? { policy: policy.policy } : {}) };
|
|
19166
|
+
context.saveCheckpoint("manual_policy:ready", manualPolicy);
|
|
19167
|
+
}
|
|
19168
|
+
else {
|
|
19169
|
+
const error = isRecord(policy.error) ? policy.error : {};
|
|
19170
|
+
const code = nonEmptyString(error.code) || "trading_policy_unavailable";
|
|
19171
|
+
manualPolicy = code === "trading_policy_consent_required" || code === "trading_policy_declined"
|
|
19172
|
+
? { status: code === "trading_policy_declined" ? "declined" : "consent_required", code,
|
|
19173
|
+
question: policy.question, trading_policy_terms_id: policy.trading_policy_terms_id,
|
|
19174
|
+
policy: policy.trading_policy }
|
|
19175
|
+
: code === "trading_policy_not_answered"
|
|
19176
|
+
? { status: "not_answered", code, policy: policy.trading_policy,
|
|
19177
|
+
next: "The owner did not answer the trading-policy question; place_manual_order asks again." }
|
|
19178
|
+
: { status: "setup_pending", code };
|
|
19179
|
+
}
|
|
19180
|
+
}
|
|
18201
19181
|
// Onboard Polymarket as part of account creation so live trading is
|
|
18202
19182
|
// ready before the workflow reports success. Incomplete checkpoints
|
|
18203
19183
|
// from older clients must be retried rather than treated as durable.
|
|
@@ -18375,9 +19355,33 @@ export function makeServer() {
|
|
|
18375
19355
|
deriveReady = deferDerive("not_completed");
|
|
18376
19356
|
let liveKey = context.getCheckpoint("account:live_key");
|
|
18377
19357
|
if (!liveKey) {
|
|
18378
|
-
|
|
18379
|
-
|
|
18380
|
-
|
|
19358
|
+
let minted = context.getCheckpoint("account:live_key_minted");
|
|
19359
|
+
const mintedKeyId = nonEmptyString(minted?.key_id);
|
|
19360
|
+
if (minted && mintedKeyId && UUID_RE.test(mintedKeyId)) {
|
|
19361
|
+
const active = await liveKeyActive(accountId, mintedKeyId);
|
|
19362
|
+
if (active === undefined) {
|
|
19363
|
+
return clientError("live_key_status_unavailable", "Felix could not confirm this account's saved live key, so no new key was minted.", "Retry create_account with the same idempotency_key.", { account_id: accountId, money_moved: false });
|
|
19364
|
+
}
|
|
19365
|
+
if (!active) {
|
|
19366
|
+
context.deleteCheckpoint("account:live_key_minted");
|
|
19367
|
+
minted = undefined;
|
|
19368
|
+
}
|
|
19369
|
+
}
|
|
19370
|
+
else {
|
|
19371
|
+
minted = undefined;
|
|
19372
|
+
}
|
|
19373
|
+
if (!minted) {
|
|
19374
|
+
minted = await mintAccountKeyOnly(accountId, accountOwnerKey, context);
|
|
19375
|
+
if (minted.ok === false)
|
|
19376
|
+
return minted;
|
|
19377
|
+
context.saveCheckpoint("account:live_key_minted", minted);
|
|
19378
|
+
// Only after the minted key is durable: drop its (now redundant) signed grant.
|
|
19379
|
+
context.deleteCheckpoint("account:live_key_grant");
|
|
19380
|
+
}
|
|
19381
|
+
const mandate = await registerLiveKeyMandate(accountId, accountOwnerKey, String(minted.key_id));
|
|
19382
|
+
if (mandate.ok === false)
|
|
19383
|
+
return { ...mandate, account_id: accountId };
|
|
19384
|
+
liveKey = { ...minted, mandate_id: mandate.mandate_id, mandate_version: mandate.mandate_version };
|
|
18381
19385
|
context.saveCheckpoint("account:live_key", liveKey);
|
|
18382
19386
|
}
|
|
18383
19387
|
const apiKey = nonEmptyString(liveKey.api_key);
|
|
@@ -18433,10 +19437,8 @@ export function makeServer() {
|
|
|
18433
19437
|
account_id: accountId,
|
|
18434
19438
|
wallet_status: "ready",
|
|
18435
19439
|
custody: "non_custodial",
|
|
18436
|
-
//
|
|
18437
|
-
//
|
|
18438
|
-
deposit_address: legacyWallet ? legacyWallet.deposit_address : accountOwnerAddress,
|
|
18439
|
-
deposit_address_role: "client_held_account_owner_eoa",
|
|
19440
|
+
// ARC_FIRST_DEPOSIT_MCP_20261117: every account funds its Arc home (create_deposit); the owner EOA is
|
|
19441
|
+
// reported only as the owner, never as a deposit address.
|
|
18440
19442
|
account_owner_address: accountOwnerAddress,
|
|
18441
19443
|
account_owner_derivation: "hkdf-sha256/felix-account-owner-v1",
|
|
18442
19444
|
safe: legacyWallet ? legacyWallet.safe : confirmedArcHome.safe,
|
|
@@ -18453,6 +19455,15 @@ export function makeServer() {
|
|
|
18453
19455
|
polymarket_agent_status: polymarketAgentReady.status,
|
|
18454
19456
|
polymarket_agent_wallet: polymarketAgentReady.agent_wallet,
|
|
18455
19457
|
polymarket_agent_approvals_ready: polymarketAgentReady.approvals_ready,
|
|
19458
|
+
manual_trading_status: manualPolicy.status,
|
|
19459
|
+
...(isRecord(manualPolicy.policy) ? { trading_policy: manualPolicy.policy } : {}),
|
|
19460
|
+
...(manualPolicy.status === "consent_required" ? {
|
|
19461
|
+
trading_policy_question: manualPolicy.question,
|
|
19462
|
+
trading_policy_terms_id: manualPolicy.trading_policy_terms_id,
|
|
19463
|
+
trading_policy_next: "Manual orders need the owner's yes: ask trading_policy_question, then pass "
|
|
19464
|
+
+ "accept_trading_policy:true and trading_policy_terms_id to place_manual_order.",
|
|
19465
|
+
} : {}),
|
|
19466
|
+
...(manualPolicy.status === "not_answered" ? { trading_policy_next: manualPolicy.next } : {}),
|
|
18456
19467
|
hyperliquid_status: hyperliquidReady.status,
|
|
18457
19468
|
hyperliquid_agent_address: hyperliquidReady.agent_address,
|
|
18458
19469
|
derive_status: deriveReady.status,
|
|
@@ -18600,14 +19611,20 @@ export function makeServer() {
|
|
|
18600
19611
|
});
|
|
18601
19612
|
if (out.ok !== false) {
|
|
18602
19613
|
const deriveDeferred = out.derive_status === "onboarding_deferred";
|
|
19614
|
+
// Journals completed by older clients stored the owner EOA as deposit_address: never replay it.
|
|
19615
|
+
const { deposit_address: _legacyDepositAddress, deposit_address_role: _legacyDepositRole, funding: _legacyFunding, ...completed } = out;
|
|
19616
|
+
void _legacyDepositAddress;
|
|
19617
|
+
void _legacyDepositRole;
|
|
19618
|
+
void _legacyFunding;
|
|
19619
|
+
const completedAccountId = nonEmptyString(completed.account_id);
|
|
19620
|
+
const arcHomeSafe = nonEmptyString(completed.arc_home_safe);
|
|
18603
19621
|
out = {
|
|
18604
|
-
...
|
|
19622
|
+
...completed,
|
|
18605
19623
|
funding: {
|
|
18606
|
-
chain: "
|
|
18607
|
-
|
|
18608
|
-
|
|
18609
|
-
|
|
18610
|
-
note: "Send either Polygon native USDC or bridged USDC.e. fund_market converts only the native USDC it needs into USDC.e.",
|
|
19624
|
+
chain: "arc",
|
|
19625
|
+
...(arcHomeSafe ? { arc_home_safe: arcHomeSafe } : {}),
|
|
19626
|
+
...arcDepositSteps(completedAccountId, undefined),
|
|
19627
|
+
note: "Deposits settle as USDC in this account's Arc home Safe. Use create_deposit for any listed token; USDC already on Arc may be sent to arc_home_safe directly.",
|
|
18611
19628
|
},
|
|
18612
19629
|
recovery: {
|
|
18613
19630
|
retry_tool: "create_account",
|
|
@@ -18616,7 +19633,7 @@ export function makeServer() {
|
|
|
18616
19633
|
},
|
|
18617
19634
|
next_actions: [
|
|
18618
19635
|
"Call get_custody_recovery_status and require ready:true before depositing meaningful funds.",
|
|
18619
|
-
"
|
|
19636
|
+
"Deposit with create_deposit (pay the one-time address it returns), track it with get_deposit_address request_id, then call get_money_map.",
|
|
18620
19637
|
...(deriveDeferred ? [
|
|
18621
19638
|
"No manual Derive setup is required: the first fund_market call for options completes owner-signed onboarding before moving venue funds.",
|
|
18622
19639
|
] : []),
|
|
@@ -18940,6 +19957,7 @@ export function makeServer() {
|
|
|
18940
19957
|
}
|
|
18941
19958
|
: {});
|
|
18942
19959
|
}
|
|
19960
|
+
out = withNewAccountNextStep(name, out, a);
|
|
18943
19961
|
if (liveMutation) {
|
|
18944
19962
|
out = { ...out, idempotency_key: liveMutation.key };
|
|
18945
19963
|
try {
|