@avalabs/fusion-sdk 0.20.0 → 0.22.0
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/dist/mod.cjs +1 -1
- package/dist/mod.d.cts +5 -1
- package/dist/mod.d.ts +5 -1
- package/dist/mod.js +1 -1
- package/dist/transfer-manager.cjs +1 -1
- package/dist/transfer-manager.cjs.map +1 -1
- package/dist/transfer-manager.js +1 -1
- package/dist/transfer-manager.js.map +1 -1
- package/dist/transfer-service/_evm-approval.cjs +2 -0
- package/dist/transfer-service/_evm-approval.cjs.map +1 -0
- package/dist/transfer-service/_evm-approval.d.cts +23 -0
- package/dist/transfer-service/_evm-approval.d.ts +23 -0
- package/dist/transfer-service/_evm-approval.js +2 -0
- package/dist/transfer-service/_evm-approval.js.map +1 -0
- package/dist/transfer-service/_utils.cjs +1 -1
- package/dist/transfer-service/_utils.cjs.map +1 -1
- package/dist/transfer-service/_utils.d.ts +1 -0
- package/dist/transfer-service/_utils.js +1 -1
- package/dist/transfer-service/_utils.js.map +1 -1
- package/dist/transfer-service/avalanche-cct/_handlers/estimate-native-fee.cjs +1 -1
- package/dist/transfer-service/avalanche-cct/_handlers/estimate-native-fee.js +1 -1
- package/dist/transfer-service/avalanche-cct/_handlers/track-transfer.cjs +1 -1
- package/dist/transfer-service/avalanche-cct/_handlers/track-transfer.js +1 -1
- package/dist/transfer-service/avalanche-cct/_handlers/transfer-asset.cjs +1 -1
- package/dist/transfer-service/avalanche-cct/_handlers/transfer-asset.js +1 -1
- package/dist/transfer-service/avalanche-cct/_utils/fees.cjs +1 -1
- package/dist/transfer-service/avalanche-cct/_utils/fees.js +1 -1
- package/dist/transfer-service/avalanche-cct/_utils/polling.cjs +1 -1
- package/dist/transfer-service/avalanche-cct/_utils/polling.js +1 -1
- package/dist/transfer-service/avalanche-evm/_handlers/estimate-native-fee.cjs +1 -1
- package/dist/transfer-service/avalanche-evm/_handlers/estimate-native-fee.js +1 -1
- package/dist/transfer-service/markr/_api.cjs +1 -1
- package/dist/transfer-service/markr/_api.cjs.map +1 -1
- package/dist/transfer-service/markr/_api.js +1 -1
- package/dist/transfer-service/markr/_api.js.map +1 -1
- package/dist/transfer-service/markr/_handlers/estimate-native-fee.cjs +1 -1
- package/dist/transfer-service/markr/_handlers/estimate-native-fee.cjs.map +1 -1
- package/dist/transfer-service/markr/_handlers/estimate-native-fee.js +1 -1
- package/dist/transfer-service/markr/_handlers/estimate-native-fee.js.map +1 -1
- package/dist/transfer-service/markr/_handlers/stream-quotes.cjs +1 -1
- package/dist/transfer-service/markr/_handlers/stream-quotes.cjs.map +1 -1
- package/dist/transfer-service/markr/_handlers/stream-quotes.js +1 -1
- package/dist/transfer-service/markr/_handlers/stream-quotes.js.map +1 -1
- package/dist/transfer-service/markr/_handlers/transfer-asset.cjs +1 -1
- package/dist/transfer-service/markr/_handlers/transfer-asset.cjs.map +1 -1
- package/dist/transfer-service/markr/_handlers/transfer-asset.js +1 -1
- package/dist/transfer-service/markr/_handlers/transfer-asset.js.map +1 -1
- package/dist/transfer-service/markr/_schema.cjs +1 -1
- package/dist/transfer-service/markr/_schema.cjs.map +1 -1
- package/dist/transfer-service/markr/_schema.js +1 -1
- package/dist/transfer-service/markr/_schema.js.map +1 -1
- package/dist/transfer-service/markr/_utils.cjs +1 -1
- package/dist/transfer-service/markr/_utils.cjs.map +1 -1
- package/dist/transfer-service/markr/_utils.js +1 -1
- package/dist/transfer-service/markr/_utils.js.map +1 -1
- package/dist/transfer-service/markr/markr-service.cjs +1 -1
- package/dist/transfer-service/markr/markr-service.cjs.map +1 -1
- package/dist/transfer-service/markr/markr-service.d.cts +26 -0
- package/dist/transfer-service/markr/markr-service.d.ts +26 -0
- package/dist/transfer-service/markr/markr-service.js +1 -1
- package/dist/transfer-service/markr/markr-service.js.map +1 -1
- package/dist/transfer-service/markr/recurring/_api.cjs +2 -0
- package/dist/transfer-service/markr/recurring/_api.cjs.map +1 -0
- package/dist/transfer-service/markr/recurring/_api.js +2 -0
- package/dist/transfer-service/markr/recurring/_api.js.map +1 -0
- package/dist/transfer-service/markr/recurring/_chain-info.cjs +2 -0
- package/dist/transfer-service/markr/recurring/_chain-info.cjs.map +1 -0
- package/dist/transfer-service/markr/recurring/_chain-info.js +2 -0
- package/dist/transfer-service/markr/recurring/_chain-info.js.map +1 -0
- package/dist/transfer-service/markr/recurring/_eligibility.cjs +2 -0
- package/dist/transfer-service/markr/recurring/_eligibility.cjs.map +1 -0
- package/dist/transfer-service/markr/recurring/_eligibility.js +2 -0
- package/dist/transfer-service/markr/recurring/_eligibility.js.map +1 -0
- package/dist/transfer-service/markr/recurring/_frequency.cjs +2 -0
- package/dist/transfer-service/markr/recurring/_frequency.cjs.map +1 -0
- package/dist/transfer-service/markr/recurring/_frequency.d.cts +17 -0
- package/dist/transfer-service/markr/recurring/_frequency.d.ts +17 -0
- package/dist/transfer-service/markr/recurring/_frequency.js +2 -0
- package/dist/transfer-service/markr/recurring/_frequency.js.map +1 -0
- package/dist/transfer-service/markr/recurring/_namespace.cjs +2 -0
- package/dist/transfer-service/markr/recurring/_namespace.cjs.map +1 -0
- package/dist/transfer-service/markr/recurring/_namespace.js +2 -0
- package/dist/transfer-service/markr/recurring/_namespace.js.map +1 -0
- package/dist/transfer-service/markr/recurring/_schema.cjs +2 -0
- package/dist/transfer-service/markr/recurring/_schema.cjs.map +1 -0
- package/dist/transfer-service/markr/recurring/_schema.js +2 -0
- package/dist/transfer-service/markr/recurring/_schema.js.map +1 -0
- package/dist/transfer-service/markr/recurring/index.d.ts +2 -0
- package/dist/transfer-service/markr/recurring/types.cjs +2 -0
- package/dist/transfer-service/markr/recurring/types.cjs.map +1 -0
- package/dist/transfer-service/markr/recurring/types.d.cts +439 -0
- package/dist/transfer-service/markr/recurring/types.d.ts +439 -0
- package/dist/transfer-service/markr/recurring/types.js +2 -0
- package/dist/transfer-service/markr/recurring/types.js.map +1 -0
- package/dist/transfer-service/wrap-unwrap/_handlers/transfer-asset.cjs +1 -1
- package/dist/transfer-service/wrap-unwrap/_handlers/transfer-asset.js +1 -1
- package/dist/types/quote.d.cts +9 -0
- package/dist/types/quote.d.ts +9 -0
- package/dist/types/transfer-manager.d.cts +16 -0
- package/dist/types/transfer-manager.d.ts +16 -0
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_api.cjs","names":["AbortedError","InvalidParamsError","combineUrlPathnames","fetchJson","getAuthHeaders","RecurringQuoteResponseSchema","ResponseValidationError","WrappedSwapTransactionResponseSchema","ListRecurringOrdersResponseSchema"],"sources":["../../../../src/transfer-service/markr/recurring/_api.ts"],"sourcesContent":["import { AbortedError, InvalidParamsError, ResponseValidationError } from '../../../errors';\nimport { combineUrlPathnames, fetchJson } from '../../fetch-utilities';\nimport { WrappedSwapTransactionResponseSchema, type WrappedSwapTransactionResponse } from '../_schema';\nimport { getAuthHeaders, type ApiOptions } from '../_api';\nimport { ListRecurringOrdersResponseSchema, RecurringQuoteResponseSchema } from './_schema';\nimport {\n RECURRING_UNLIMITED_ORDERS_SENTINEL,\n type ListRecurringOrdersParams,\n type ListRecurringOrdersResponse,\n type RecurringOrderActionApiParams,\n type RecurringQuoteParams,\n type RecurringQuoteResponse,\n type RecurringSwapParams,\n} from './types';\n\n/** bytes32 hex — same regex as `RecurringOrderSchema.orderId`. */\nconst ORDER_ID_REGEX = /^0x[0-9a-fA-F]{64}$/;\n\n/**\n * Retry policy for `/recurring/swap` and the order-action endpoints\n * (`/recurring/orders/{}/cancel`, `/recurring/orders/{}/pause`,\n * `/recurring/orders/{}/unpause`) — Markr documents all of them as\n * idempotent on the same params, so transient network / 5xx failures are\n * safe to replay. Mirrors the `markrGetCrossChainStatus` pattern but admits\n * POST (whereas the GET variant only whitelists safe verbs) and does NOT\n * retry 404 (for these endpoints, 404 means the resource genuinely doesn't\n * exist).\n */\nconst IDEMPOTENT_POST_RETRY_COUNT = 3;\n\nfunction retryIdempotentPost(ctx: { error?: unknown; response?: Response }): boolean {\n if (ctx.error) {\n if (ctx.error instanceof AbortedError) return false;\n return true;\n }\n const status = ctx.response?.status ?? 0;\n return status === 408 || status === 425 || status === 429 || (status >= 500 && status <= 599);\n}\n\n/**\n * Translate the SDK-public `numberOfOrders` value into Markr's wire shape:\n * - `Infinity` or `-1` → wire sentinel `-1` (unlimited).\n * - Integer in `[2, 365]` → passthrough (matches Markr's documented bounds).\n * - Anything else (`NaN`, `0`, `1`, negatives other than `-1`, non-integers,\n * values > 365, `-Infinity`) → `InvalidParamsError` at the SDK boundary.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1recurring~1quote/post — Markr's\n * `numberOfOrders` spec: `-1` for infinite, or integer 2-365 inclusive.\n */\nfunction translateNumberOfOrders(input: number): number {\n if (input === Infinity || input === RECURRING_UNLIMITED_ORDERS_SENTINEL) {\n return RECURRING_UNLIMITED_ORDERS_SENTINEL;\n }\n\n if (!Number.isInteger(input) || input < 2 || input > 365) {\n throw new InvalidParamsError(\n 'Invalid numberOfOrders',\n `Expected an integer in [2, 365], Infinity, or -1 (unlimited). Got: ${String(input)}`,\n );\n }\n\n return input;\n}\n\nexport async function markrRecurringQuote(\n { apiBaseUrl, apiToken, fetch: customFetch }: ApiOptions,\n params: RecurringQuoteParams,\n): Promise<RecurringQuoteResponse> {\n const endpoint = '/recurring/quote';\n const url = combineUrlPathnames(apiBaseUrl, endpoint);\n\n const body = {\n appId: params.appId,\n chainId: params.chainId,\n tokenIn: params.tokenIn,\n tokenInDecimals: params.tokenInDecimals,\n tokenOut: params.tokenOut,\n tokenOutDecimals: params.tokenOutDecimals,\n // Inline `.toString()` — `JSON.stringify` cannot serialize bigint, so the\n // wire shape stays a decimal string.\n amount: params.amount.toString(),\n numberOfOrders: translateNumberOfOrders(params.numberOfOrders),\n frequency: params.frequency,\n slippage: params.slippage,\n };\n\n const rawJson = await fetchJson(url, {\n body: JSON.stringify(body),\n fetch: customFetch,\n headers: getAuthHeaders(apiToken),\n method: 'POST',\n });\n\n const parsed = RecurringQuoteResponseSchema.safeParse(rawJson);\n\n if (!parsed.success) {\n throw new ResponseValidationError(\n `Invalid response from Markr \"${endpoint}\" endpoint.`,\n parsed.error.issues,\n rawJson,\n );\n }\n\n return parsed.data;\n}\n\n/**\n * Fetches the first-fill swap calldata for a previously quoted recurring swap.\n *\n * Allowance must already cover `totalAmountIn` from the quote. The returned\n * `WrappedSwapTransactionResponse` is signed and broadcast by the caller (the\n * SDK does not sign on the recurring path).\n *\n * Idempotent on the same `uuid` per the Markr docs — retried on transient\n * network / 5xx failures via `retryIdempotentPost`.\n */\nexport async function markrRecurringSwap(\n { apiBaseUrl, apiToken, fetch: customFetch }: ApiOptions,\n params: RecurringSwapParams,\n): Promise<WrappedSwapTransactionResponse> {\n const endpoint = '/recurring/swap';\n const url = combineUrlPathnames(apiBaseUrl, endpoint);\n\n const rawJson = await fetchJson(url, {\n body: JSON.stringify(params),\n fetch: customFetch,\n headers: getAuthHeaders(apiToken),\n method: 'POST',\n retries: IDEMPOTENT_POST_RETRY_COUNT,\n retryOn: retryIdempotentPost,\n });\n\n const parsed = WrappedSwapTransactionResponseSchema.safeParse(rawJson);\n\n if (!parsed.success) {\n throw new ResponseValidationError(\n `Invalid response from Markr \"${endpoint}\" endpoint.`,\n parsed.error.issues,\n rawJson,\n );\n }\n\n return parsed.data;\n}\n\nexport async function markrListRecurringOrders(\n { apiBaseUrl, apiToken, fetch: customFetch }: ApiOptions,\n params: ListRecurringOrdersParams,\n): Promise<ListRecurringOrdersResponse> {\n // `URLSearchParams` URL-encodes each value — defense-in-depth against a\n // caller reaching from JS (no TS brand check) and passing an `address` like\n // `0x…&adminKey=x` that would otherwise inject extra query params.\n const searchParams = new URLSearchParams({ address: params.address });\n if (params.chainId !== undefined) searchParams.set('chainId', String(params.chainId));\n if (params.status !== undefined) searchParams.set('status', params.status);\n\n const endpoint = `/recurring/orders?${searchParams.toString()}`;\n const url = combineUrlPathnames(apiBaseUrl, endpoint);\n\n const rawJson = await fetchJson(url, { headers: getAuthHeaders(apiToken), fetch: customFetch });\n\n const parsed = ListRecurringOrdersResponseSchema.safeParse(rawJson);\n\n if (!parsed.success) {\n throw new ResponseValidationError(\n `Invalid response from Markr \"/recurring/orders\" endpoint.`,\n parsed.error.issues,\n rawJson,\n );\n }\n\n return parsed.data;\n}\n\n/**\n * Shared implementation for the three calldata-returning order-action\n * endpoints (`cancel`, `pause`, `unpause`). All three share:\n * - identical body shape `{ address, chainId }`\n * - identical response shape (`WrappedSwapTransactionResponse`)\n * - identical bytes32 `orderId` validation (path-traversal defense before\n * URL interpolation — catches stale UUIDs / malformed values as a clear\n * `InvalidParamsError` at the SDK boundary rather than an opaque 404\n * from the orchestrator)\n * - identical idempotent-POST retry policy\n *\n * Kept private so all three exported helpers go through the same wire\n * contract — adding a new field (or tightening a check) is a one-place\n * change here.\n */\nasync function postRecurringOrderAction(\n { apiBaseUrl, apiToken, fetch: customFetch }: ApiOptions,\n action: 'cancel' | 'pause' | 'unpause',\n params: { orderId: `0x${string}`; address: string; chainId: number },\n): Promise<WrappedSwapTransactionResponse> {\n if (!ORDER_ID_REGEX.test(params.orderId)) {\n throw new InvalidParamsError(\n 'Invalid recurring orderId',\n `Expected 0x-prefixed bytes32 hex (66 chars). Got: ${JSON.stringify(params.orderId)}`,\n );\n }\n\n const endpoint = `/recurring/orders/${encodeURIComponent(params.orderId)}/${action}`;\n const url = combineUrlPathnames(apiBaseUrl, endpoint);\n\n const rawJson = await fetchJson(url, {\n body: JSON.stringify({ address: params.address, chainId: params.chainId }),\n fetch: customFetch,\n headers: getAuthHeaders(apiToken),\n method: 'POST',\n retries: IDEMPOTENT_POST_RETRY_COUNT,\n retryOn: retryIdempotentPost,\n });\n\n const parsed = WrappedSwapTransactionResponseSchema.safeParse(rawJson);\n\n if (!parsed.success) {\n throw new ResponseValidationError(\n `Invalid response from Markr \"${endpoint}\" endpoint.`,\n parsed.error.issues,\n rawJson,\n );\n }\n\n return parsed.data;\n}\n\n/**\n * Fetches the calldata to cancel the recurring schedule identified by\n * `orderId`. The returned `WrappedSwapTransactionResponse` is signed and\n * broadcast on-chain by the caller — cancellation only takes effect after\n * the TX confirms, at which point Markr transitions the order's `status`\n * to `'cancelled'`.\n *\n * Only `'active'` and `'paused'` orders can be cancelled per the docs; an\n * attempt to cancel a `'completed'` (or otherwise non-cancellable) order\n * surfaces as `HttpError(400)` from the orchestrator.\n *\n * Idempotent on the same `(orderId, address, chainId)` triple per the Markr\n * docs — retried on transient network / 5xx failures via `retryIdempotentPost`.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1recurring~1orders~1{orderId}~1cancel/post\n */\nexport function markrPrepareCancellation(\n apiOptions: ApiOptions,\n params: RecurringOrderActionApiParams,\n): Promise<WrappedSwapTransactionResponse> {\n return postRecurringOrderAction(apiOptions, 'cancel', params);\n}\n\n/**\n * Fetches the calldata to pause the recurring schedule identified by\n * `orderId`. The returned `WrappedSwapTransactionResponse` is signed and\n * broadcast on-chain by the caller — the schedule only transitions to\n * `status: 'paused'` once the TX confirms and Markr observes the on-chain\n * event.\n *\n * Only `'active'` orders can be paused per the docs; an attempt to pause a\n * non-`'active'` order surfaces as `HttpError(400)` from the orchestrator.\n *\n * Pausing preserves the existing ERC-20 allowance — when the user later\n * unpauses, no re-approval is required and no new native schedule fee is\n * charged. This is the key UX benefit of pause over cancel-and-recreate.\n *\n * Idempotent on the same `(orderId, address, chainId)` triple — retried\n * on transient network / 5xx failures via `retryIdempotentPost`.\n *\n * @see https://orchestrator-docs.markr.io/#tag/Recurring-Swaps/paths/~1recurring~1orders~1{orderId}~1pause/post\n */\nexport function markrPreparePause(\n apiOptions: ApiOptions,\n params: RecurringOrderActionApiParams,\n): Promise<WrappedSwapTransactionResponse> {\n return postRecurringOrderAction(apiOptions, 'pause', params);\n}\n\n/**\n * Fetches the calldata to unpause (resume) the recurring schedule\n * identified by `orderId`. The returned `WrappedSwapTransactionResponse` is\n * signed and broadcast on-chain by the caller — the schedule only\n * transitions back to `status: 'active'` once the TX confirms and Markr\n * observes the on-chain event.\n *\n * Only `'paused'` orders can be unpaused per the docs; an attempt to\n * unpause a non-`'paused'` order surfaces as `HttpError(400)` from the\n * orchestrator.\n *\n * Resumes execution from where the schedule left off — remaining fills\n * continue on the original `frequency` cadence and the orchestrator\n * recomputes `nextExecutionAt` after the TX confirms.\n *\n * Idempotent on the same `(orderId, address, chainId)` triple — retried\n * on transient network / 5xx failures via `retryIdempotentPost`.\n *\n * @see https://orchestrator-docs.markr.io/#tag/Recurring-Swaps/paths/~1recurring~1orders~1{orderId}~1unpause/post\n */\nexport function markrPrepareUnpause(\n apiOptions: ApiOptions,\n params: RecurringOrderActionApiParams,\n): Promise<WrappedSwapTransactionResponse> {\n return postRecurringOrderAction(apiOptions, 'unpause', params);\n}\n"],"mappings":"2LAgBM,EAAiB,sBAcvB,SAAS,EAAoB,EAAwD,CACnF,GAAI,EAAI,MAEN,MADA,EAAI,EAAI,iBAAiBA,EAAAA,cAG3B,IAAM,EAAS,EAAI,UAAU,QAAU,EACvC,OAAO,IAAW,KAAO,IAAW,KAAO,IAAW,KAAQ,GAAU,KAAO,GAAU,IAa3F,SAAS,EAAwB,EAAuB,CACtD,GAAI,IAAU,KAAY,IAAA,GACxB,MAAA,GAGF,GAAI,CAAC,OAAO,UAAU,EAAM,EAAI,EAAQ,GAAK,EAAQ,IACnD,MAAM,IAAIC,EAAAA,mBACR,yBACA,sEAAsE,OAAO,EAAM,GACpF,CAGH,OAAO,EAGT,eAAsB,EACpB,CAAE,aAAY,WAAU,MAAO,GAC/B,EACiC,CACjC,IAAM,EAAW,mBACX,EAAMC,EAAAA,oBAAoB,EAAY,EAAS,CAE/C,EAAO,CACX,MAAO,EAAO,MACd,QAAS,EAAO,QAChB,QAAS,EAAO,QAChB,gBAAiB,EAAO,gBACxB,SAAU,EAAO,SACjB,iBAAkB,EAAO,iBAGzB,OAAQ,EAAO,OAAO,UAAU,CAChC,eAAgB,EAAwB,EAAO,eAAe,CAC9D,UAAW,EAAO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A,wBACR,4DACA,EAAO,MAAM,OACb,EACD,CAGH,OAAO,EAAO,KAkBhB,eAAe,EACb,CAAE,aAAY,WAAU,MAAO,GAC/B,EACA,EACyC,CACzC,GAAI,CAAC,EAAe,KAAK,EAAO,QAAQ,CACtC,MAAM,IAAIL,EAAAA,mBACR,4BACA,qDAAqD,KAAK,UAAU,EAAO,QAAQ,GACpF,CAGH,IAAM,EAAW,qBAAqB,mBAAmB,EAAO,QAAQ,CAAC,GAAG,IAGtE,EAAU,MAAME,EAAAA,UAFVD,EAAAA,oBAAoB,EAAY,EAAS,CAEhB,CACnC,KAAM,KAAK,UAAU,CAAE,QAAS,EAAO,QAAS,QAAS,EAAO,QAAS,CAAC,CAC1E,MAAO,EACP,QAASE,EAAAA,eAAe,EAAS,CACjC,OAAQ,OACR,QAAS,EACT,QAAS,EACV,CAAC,CAEI,EAASG,EAAAA,qCAAqC,UAAU,EAAQ,CAEtE,GAAI,CAAC,EAAO,QACV,MAAM,IAAID,EAAAA,wBACR,gCAAgC,EAAS,aACzC,EAAO,MAAM,OACb,EACD,CAGH,OAAO,EAAO,KAmBhB,SAAgB,EACd,EACA,EACyC,CACzC,OAAO,EAAyB,EAAY,SAAU,EAAO,CAsB/D,SAAgB,EACd,EACA,EACyC,CACzC,OAAO,EAAyB,EAAY,QAAS,EAAO,CAuB9D,SAAgB,EACd,EACA,EACyC,CACzC,OAAO,EAAyB,EAAY,UAAW,EAAO"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{AbortedError as e,InvalidParamsError as t,ResponseValidationError as n}from"../../../errors.js";import"./types.js";import{WrappedSwapTransactionResponseSchema as r}from"../_schema.js";import{combineUrlPathnames as i,fetchJson as a}from"../../fetch-utilities.js";import{getAuthHeaders as o}from"../_api.js";import{ListRecurringOrdersResponseSchema as s,RecurringQuoteResponseSchema as c}from"./_schema.js";const l=/^0x[0-9a-fA-F]{64}$/;function u(t){if(t.error)return!(t.error instanceof e);let n=t.response?.status??0;return n===408||n===425||n===429||n>=500&&n<=599}function d(e){if(e===1/0||e===-1)return-1;if(!Number.isInteger(e)||e<2||e>365)throw new t(`Invalid numberOfOrders`,`Expected an integer in [2, 365], Infinity, or -1 (unlimited). Got: ${String(e)}`);return e}async function f({apiBaseUrl:e,apiToken:t,fetch:r},s){let l=`/recurring/quote`,u=i(e,l),f={appId:s.appId,chainId:s.chainId,tokenIn:s.tokenIn,tokenInDecimals:s.tokenInDecimals,tokenOut:s.tokenOut,tokenOutDecimals:s.tokenOutDecimals,amount:s.amount.toString(),numberOfOrders:d(s.numberOfOrders),frequency:s.frequency,slippage:s.slippage},p=await a(u,{body:JSON.stringify(f),fetch:r,headers:o(t),method:`POST`}),m=c.safeParse(p);if(!m.success)throw new n(`Invalid response from Markr "${l}" endpoint.`,m.error.issues,p);return m.data}async function p({apiBaseUrl:e,apiToken:t,fetch:s},c){let l=`/recurring/swap`,d=await a(i(e,l),{body:JSON.stringify(c),fetch:s,headers:o(t),method:`POST`,retries:3,retryOn:u}),f=r.safeParse(d);if(!f.success)throw new n(`Invalid response from Markr "${l}" endpoint.`,f.error.issues,d);return f.data}async function m({apiBaseUrl:e,apiToken:t,fetch:r},c){let l=new URLSearchParams({address:c.address});c.chainId!==void 0&&l.set(`chainId`,String(c.chainId)),c.status!==void 0&&l.set(`status`,c.status);let u=await a(i(e,`/recurring/orders?${l.toString()}`),{headers:o(t),fetch:r}),d=s.safeParse(u);if(!d.success)throw new n(`Invalid response from Markr "/recurring/orders" endpoint.`,d.error.issues,u);return d.data}async function h({apiBaseUrl:e,apiToken:s,fetch:c},d,f){if(!l.test(f.orderId))throw new t(`Invalid recurring orderId`,`Expected 0x-prefixed bytes32 hex (66 chars). Got: ${JSON.stringify(f.orderId)}`);let p=`/recurring/orders/${encodeURIComponent(f.orderId)}/${d}`,m=await a(i(e,p),{body:JSON.stringify({address:f.address,chainId:f.chainId}),fetch:c,headers:o(s),method:`POST`,retries:3,retryOn:u}),h=r.safeParse(m);if(!h.success)throw new n(`Invalid response from Markr "${p}" endpoint.`,h.error.issues,m);return h.data}function g(e,t){return h(e,`cancel`,t)}function _(e,t){return h(e,`pause`,t)}function v(e,t){return h(e,`unpause`,t)}export{m as markrListRecurringOrders,g as markrPrepareCancellation,_ as markrPreparePause,v as markrPrepareUnpause,f as markrRecurringQuote,p as markrRecurringSwap};
|
|
2
|
+
//# sourceMappingURL=_api.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_api.js","names":[],"sources":["../../../../src/transfer-service/markr/recurring/_api.ts"],"sourcesContent":["import { AbortedError, InvalidParamsError, ResponseValidationError } from '../../../errors';\nimport { combineUrlPathnames, fetchJson } from '../../fetch-utilities';\nimport { WrappedSwapTransactionResponseSchema, type WrappedSwapTransactionResponse } from '../_schema';\nimport { getAuthHeaders, type ApiOptions } from '../_api';\nimport { ListRecurringOrdersResponseSchema, RecurringQuoteResponseSchema } from './_schema';\nimport {\n RECURRING_UNLIMITED_ORDERS_SENTINEL,\n type ListRecurringOrdersParams,\n type ListRecurringOrdersResponse,\n type RecurringOrderActionApiParams,\n type RecurringQuoteParams,\n type RecurringQuoteResponse,\n type RecurringSwapParams,\n} from './types';\n\n/** bytes32 hex — same regex as `RecurringOrderSchema.orderId`. */\nconst ORDER_ID_REGEX = /^0x[0-9a-fA-F]{64}$/;\n\n/**\n * Retry policy for `/recurring/swap` and the order-action endpoints\n * (`/recurring/orders/{}/cancel`, `/recurring/orders/{}/pause`,\n * `/recurring/orders/{}/unpause`) — Markr documents all of them as\n * idempotent on the same params, so transient network / 5xx failures are\n * safe to replay. Mirrors the `markrGetCrossChainStatus` pattern but admits\n * POST (whereas the GET variant only whitelists safe verbs) and does NOT\n * retry 404 (for these endpoints, 404 means the resource genuinely doesn't\n * exist).\n */\nconst IDEMPOTENT_POST_RETRY_COUNT = 3;\n\nfunction retryIdempotentPost(ctx: { error?: unknown; response?: Response }): boolean {\n if (ctx.error) {\n if (ctx.error instanceof AbortedError) return false;\n return true;\n }\n const status = ctx.response?.status ?? 0;\n return status === 408 || status === 425 || status === 429 || (status >= 500 && status <= 599);\n}\n\n/**\n * Translate the SDK-public `numberOfOrders` value into Markr's wire shape:\n * - `Infinity` or `-1` → wire sentinel `-1` (unlimited).\n * - Integer in `[2, 365]` → passthrough (matches Markr's documented bounds).\n * - Anything else (`NaN`, `0`, `1`, negatives other than `-1`, non-integers,\n * values > 365, `-Infinity`) → `InvalidParamsError` at the SDK boundary.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1recurring~1quote/post — Markr's\n * `numberOfOrders` spec: `-1` for infinite, or integer 2-365 inclusive.\n */\nfunction translateNumberOfOrders(input: number): number {\n if (input === Infinity || input === RECURRING_UNLIMITED_ORDERS_SENTINEL) {\n return RECURRING_UNLIMITED_ORDERS_SENTINEL;\n }\n\n if (!Number.isInteger(input) || input < 2 || input > 365) {\n throw new InvalidParamsError(\n 'Invalid numberOfOrders',\n `Expected an integer in [2, 365], Infinity, or -1 (unlimited). Got: ${String(input)}`,\n );\n }\n\n return input;\n}\n\nexport async function markrRecurringQuote(\n { apiBaseUrl, apiToken, fetch: customFetch }: ApiOptions,\n params: RecurringQuoteParams,\n): Promise<RecurringQuoteResponse> {\n const endpoint = '/recurring/quote';\n const url = combineUrlPathnames(apiBaseUrl, endpoint);\n\n const body = {\n appId: params.appId,\n chainId: params.chainId,\n tokenIn: params.tokenIn,\n tokenInDecimals: params.tokenInDecimals,\n tokenOut: params.tokenOut,\n tokenOutDecimals: params.tokenOutDecimals,\n // Inline `.toString()` — `JSON.stringify` cannot serialize bigint, so the\n // wire shape stays a decimal string.\n amount: params.amount.toString(),\n numberOfOrders: translateNumberOfOrders(params.numberOfOrders),\n frequency: params.frequency,\n slippage: params.slippage,\n };\n\n const rawJson = await fetchJson(url, {\n body: JSON.stringify(body),\n fetch: customFetch,\n headers: getAuthHeaders(apiToken),\n method: 'POST',\n });\n\n const parsed = RecurringQuoteResponseSchema.safeParse(rawJson);\n\n if (!parsed.success) {\n throw new ResponseValidationError(\n `Invalid response from Markr \"${endpoint}\" endpoint.`,\n parsed.error.issues,\n rawJson,\n );\n }\n\n return parsed.data;\n}\n\n/**\n * Fetches the first-fill swap calldata for a previously quoted recurring swap.\n *\n * Allowance must already cover `totalAmountIn` from the quote. The returned\n * `WrappedSwapTransactionResponse` is signed and broadcast by the caller (the\n * SDK does not sign on the recurring path).\n *\n * Idempotent on the same `uuid` per the Markr docs — retried on transient\n * network / 5xx failures via `retryIdempotentPost`.\n */\nexport async function markrRecurringSwap(\n { apiBaseUrl, apiToken, fetch: customFetch }: ApiOptions,\n params: RecurringSwapParams,\n): Promise<WrappedSwapTransactionResponse> {\n const endpoint = '/recurring/swap';\n const url = combineUrlPathnames(apiBaseUrl, endpoint);\n\n const rawJson = await fetchJson(url, {\n body: JSON.stringify(params),\n fetch: customFetch,\n headers: getAuthHeaders(apiToken),\n method: 'POST',\n retries: IDEMPOTENT_POST_RETRY_COUNT,\n retryOn: retryIdempotentPost,\n });\n\n const parsed = WrappedSwapTransactionResponseSchema.safeParse(rawJson);\n\n if (!parsed.success) {\n throw new ResponseValidationError(\n `Invalid response from Markr \"${endpoint}\" endpoint.`,\n parsed.error.issues,\n rawJson,\n );\n }\n\n return parsed.data;\n}\n\nexport async function markrListRecurringOrders(\n { apiBaseUrl, apiToken, fetch: customFetch }: ApiOptions,\n params: ListRecurringOrdersParams,\n): Promise<ListRecurringOrdersResponse> {\n // `URLSearchParams` URL-encodes each value — defense-in-depth against a\n // caller reaching from JS (no TS brand check) and passing an `address` like\n // `0x…&adminKey=x` that would otherwise inject extra query params.\n const searchParams = new URLSearchParams({ address: params.address });\n if (params.chainId !== undefined) searchParams.set('chainId', String(params.chainId));\n if (params.status !== undefined) searchParams.set('status', params.status);\n\n const endpoint = `/recurring/orders?${searchParams.toString()}`;\n const url = combineUrlPathnames(apiBaseUrl, endpoint);\n\n const rawJson = await fetchJson(url, { headers: getAuthHeaders(apiToken), fetch: customFetch });\n\n const parsed = ListRecurringOrdersResponseSchema.safeParse(rawJson);\n\n if (!parsed.success) {\n throw new ResponseValidationError(\n `Invalid response from Markr \"/recurring/orders\" endpoint.`,\n parsed.error.issues,\n rawJson,\n );\n }\n\n return parsed.data;\n}\n\n/**\n * Shared implementation for the three calldata-returning order-action\n * endpoints (`cancel`, `pause`, `unpause`). All three share:\n * - identical body shape `{ address, chainId }`\n * - identical response shape (`WrappedSwapTransactionResponse`)\n * - identical bytes32 `orderId` validation (path-traversal defense before\n * URL interpolation — catches stale UUIDs / malformed values as a clear\n * `InvalidParamsError` at the SDK boundary rather than an opaque 404\n * from the orchestrator)\n * - identical idempotent-POST retry policy\n *\n * Kept private so all three exported helpers go through the same wire\n * contract — adding a new field (or tightening a check) is a one-place\n * change here.\n */\nasync function postRecurringOrderAction(\n { apiBaseUrl, apiToken, fetch: customFetch }: ApiOptions,\n action: 'cancel' | 'pause' | 'unpause',\n params: { orderId: `0x${string}`; address: string; chainId: number },\n): Promise<WrappedSwapTransactionResponse> {\n if (!ORDER_ID_REGEX.test(params.orderId)) {\n throw new InvalidParamsError(\n 'Invalid recurring orderId',\n `Expected 0x-prefixed bytes32 hex (66 chars). Got: ${JSON.stringify(params.orderId)}`,\n );\n }\n\n const endpoint = `/recurring/orders/${encodeURIComponent(params.orderId)}/${action}`;\n const url = combineUrlPathnames(apiBaseUrl, endpoint);\n\n const rawJson = await fetchJson(url, {\n body: JSON.stringify({ address: params.address, chainId: params.chainId }),\n fetch: customFetch,\n headers: getAuthHeaders(apiToken),\n method: 'POST',\n retries: IDEMPOTENT_POST_RETRY_COUNT,\n retryOn: retryIdempotentPost,\n });\n\n const parsed = WrappedSwapTransactionResponseSchema.safeParse(rawJson);\n\n if (!parsed.success) {\n throw new ResponseValidationError(\n `Invalid response from Markr \"${endpoint}\" endpoint.`,\n parsed.error.issues,\n rawJson,\n );\n }\n\n return parsed.data;\n}\n\n/**\n * Fetches the calldata to cancel the recurring schedule identified by\n * `orderId`. The returned `WrappedSwapTransactionResponse` is signed and\n * broadcast on-chain by the caller — cancellation only takes effect after\n * the TX confirms, at which point Markr transitions the order's `status`\n * to `'cancelled'`.\n *\n * Only `'active'` and `'paused'` orders can be cancelled per the docs; an\n * attempt to cancel a `'completed'` (or otherwise non-cancellable) order\n * surfaces as `HttpError(400)` from the orchestrator.\n *\n * Idempotent on the same `(orderId, address, chainId)` triple per the Markr\n * docs — retried on transient network / 5xx failures via `retryIdempotentPost`.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1recurring~1orders~1{orderId}~1cancel/post\n */\nexport function markrPrepareCancellation(\n apiOptions: ApiOptions,\n params: RecurringOrderActionApiParams,\n): Promise<WrappedSwapTransactionResponse> {\n return postRecurringOrderAction(apiOptions, 'cancel', params);\n}\n\n/**\n * Fetches the calldata to pause the recurring schedule identified by\n * `orderId`. The returned `WrappedSwapTransactionResponse` is signed and\n * broadcast on-chain by the caller — the schedule only transitions to\n * `status: 'paused'` once the TX confirms and Markr observes the on-chain\n * event.\n *\n * Only `'active'` orders can be paused per the docs; an attempt to pause a\n * non-`'active'` order surfaces as `HttpError(400)` from the orchestrator.\n *\n * Pausing preserves the existing ERC-20 allowance — when the user later\n * unpauses, no re-approval is required and no new native schedule fee is\n * charged. This is the key UX benefit of pause over cancel-and-recreate.\n *\n * Idempotent on the same `(orderId, address, chainId)` triple — retried\n * on transient network / 5xx failures via `retryIdempotentPost`.\n *\n * @see https://orchestrator-docs.markr.io/#tag/Recurring-Swaps/paths/~1recurring~1orders~1{orderId}~1pause/post\n */\nexport function markrPreparePause(\n apiOptions: ApiOptions,\n params: RecurringOrderActionApiParams,\n): Promise<WrappedSwapTransactionResponse> {\n return postRecurringOrderAction(apiOptions, 'pause', params);\n}\n\n/**\n * Fetches the calldata to unpause (resume) the recurring schedule\n * identified by `orderId`. The returned `WrappedSwapTransactionResponse` is\n * signed and broadcast on-chain by the caller — the schedule only\n * transitions back to `status: 'active'` once the TX confirms and Markr\n * observes the on-chain event.\n *\n * Only `'paused'` orders can be unpaused per the docs; an attempt to\n * unpause a non-`'paused'` order surfaces as `HttpError(400)` from the\n * orchestrator.\n *\n * Resumes execution from where the schedule left off — remaining fills\n * continue on the original `frequency` cadence and the orchestrator\n * recomputes `nextExecutionAt` after the TX confirms.\n *\n * Idempotent on the same `(orderId, address, chainId)` triple — retried\n * on transient network / 5xx failures via `retryIdempotentPost`.\n *\n * @see https://orchestrator-docs.markr.io/#tag/Recurring-Swaps/paths/~1recurring~1orders~1{orderId}~1unpause/post\n */\nexport function markrPrepareUnpause(\n apiOptions: ApiOptions,\n params: RecurringOrderActionApiParams,\n): Promise<WrappedSwapTransactionResponse> {\n return postRecurringOrderAction(apiOptions, 'unpause', params);\n}\n"],"mappings":"4ZAgBA,MAAM,EAAiB,sBAcvB,SAAS,EAAoB,EAAwD,CACnF,GAAI,EAAI,MAEN,MADA,EAAI,EAAI,iBAAiB,GAG3B,IAAM,EAAS,EAAI,UAAU,QAAU,EACvC,OAAO,IAAW,KAAO,IAAW,KAAO,IAAW,KAAQ,GAAU,KAAO,GAAU,IAa3F,SAAS,EAAwB,EAAuB,CACtD,GAAI,IAAU,KAAY,IAAA,GACxB,MAAA,GAGF,GAAI,CAAC,OAAO,UAAU,EAAM,EAAI,EAAQ,GAAK,EAAQ,IACnD,MAAM,IAAI,EACR,yBACA,sEAAsE,OAAO,EAAM,GACpF,CAGH,OAAO,EAGT,eAAsB,EACpB,CAAE,aAAY,WAAU,MAAO,GAC/B,EACiC,CACjC,IAAM,EAAW,mBACX,EAAM,EAAoB,EAAY,EAAS,CAE/C,EAAO,CACX,MAAO,EAAO,MACd,QAAS,EAAO,QAChB,QAAS,EAAO,QAChB,gBAAiB,EAAO,gBACxB,SAAU,EAAO,SACjB,iBAAkB,EAAO,iBAGzB,OAAQ,EAAO,OAAO,UAAU,CAChC,eAAgB,EAAwB,EAAO,eAAe,CAC9D,UAAW,EAAO,UAClB,SAAU,EAAO,SAClB,CAEK,EAAU,MAAM,EAAU,EAAK,CACnC,KAAM,KAAK,UAAU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AAK,UAAU,EAAO,QAAQ,GACpF,CAGH,IAAM,EAAW,qBAAqB,mBAAmB,EAAO,QAAQ,CAAC,GAAG,IAGtE,EAAU,MAAM,EAFV,EAAoB,EAAY,EAAS,CAEhB,CACnC,KAAM,KAAK,UAAU,CAAE,QAAS,EAAO,QAAS,QAAS,EAAO,QAAS,CAAC,CAC1E,MAAO,EACP,QAAS,EAAe,EAAS,CACjC,OAAQ,OACR,QAAS,EACT,QAAS,EACV,CAAC,CAEI,EAAS,EAAqC,UAAU,EAAQ,CAEtE,GAAI,CAAC,EAAO,QACV,MAAM,IAAI,EACR,gCAAgC,EAAS,aACzC,EAAO,MAAM,OACb,EACD,CAGH,OAAO,EAAO,KAmBhB,SAAgB,EACd,EACA,EACyC,CACzC,OAAO,EAAyB,EAAY,SAAU,EAAO,CAsB/D,SAAgB,EACd,EACA,EACyC,CACzC,OAAO,EAAyB,EAAY,QAAS,EAAO,CAuB9D,SAAgB,EACd,EACA,EACyC,CACzC,OAAO,EAAyB,EAAY,UAAW,EAAO"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){let t=new Map;for(let n of e.values())typeof n.chainId!=`number`||!n.recurring||t.set(n.chainId,{minFrequencySeconds:n.recurring.minFrequencySeconds,supportedTokens:n.recurring.supportedTokens});return t}exports.deriveRecurringChainInfo=e;
|
|
2
|
+
//# sourceMappingURL=_chain-info.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_chain-info.cjs","names":[],"sources":["../../../../src/transfer-service/markr/recurring/_chain-info.ts"],"sourcesContent":["import type { SupportedChainsMap } from '../_utils';\nimport type { RecurringChainInfoEntry, RecurringChainInfoMap } from './types';\n\n/**\n * Derives a `RecurringChainInfoMap` (chainId → recurring metadata) from a\n * `SupportedChainsMap` already populated by `getSupportedChains`. Skips chains\n * that do not carry a `recurring` block in the `/info/chains` response.\n *\n * Pure function — no fetch. The original `/info/chains` response is the single\n * source for both maps (no second `/info/chains` call).\n */\nexport function deriveRecurringChainInfo(supportedChains: SupportedChainsMap): RecurringChainInfoMap {\n const recurringChainInfo: Map<number, RecurringChainInfoEntry> = new Map();\n\n for (const entry of supportedChains.values()) {\n if (typeof entry.chainId !== 'number' || !entry.recurring) {\n continue;\n }\n\n recurringChainInfo.set(entry.chainId, {\n minFrequencySeconds: entry.recurring.minFrequencySeconds,\n supportedTokens: entry.recurring.supportedTokens,\n });\n }\n\n return recurringChainInfo;\n}\n"],"mappings":"AAWA,SAAgB,EAAyB,EAA4D,CACnG,IAAM,EAA2D,IAAI,IAErE,IAAK,IAAM,KAAS,EAAgB,QAAQ,CACtC,OAAO,EAAM,SAAY,UAAY,CAAC,EAAM,WAIhD,EAAmB,IAAI,EAAM,QAAS,CACpC,oBAAqB,EAAM,UAAU,oBACrC,gBAAiB,EAAM,UAAU,gBAClC,CAAC,CAGJ,OAAO"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){let t=new Map;for(let n of e.values())typeof n.chainId!=`number`||!n.recurring||t.set(n.chainId,{minFrequencySeconds:n.recurring.minFrequencySeconds,supportedTokens:n.recurring.supportedTokens});return t}export{e as deriveRecurringChainInfo};
|
|
2
|
+
//# sourceMappingURL=_chain-info.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_chain-info.js","names":[],"sources":["../../../../src/transfer-service/markr/recurring/_chain-info.ts"],"sourcesContent":["import type { SupportedChainsMap } from '../_utils';\nimport type { RecurringChainInfoEntry, RecurringChainInfoMap } from './types';\n\n/**\n * Derives a `RecurringChainInfoMap` (chainId → recurring metadata) from a\n * `SupportedChainsMap` already populated by `getSupportedChains`. Skips chains\n * that do not carry a `recurring` block in the `/info/chains` response.\n *\n * Pure function — no fetch. The original `/info/chains` response is the single\n * source for both maps (no second `/info/chains` call).\n */\nexport function deriveRecurringChainInfo(supportedChains: SupportedChainsMap): RecurringChainInfoMap {\n const recurringChainInfo: Map<number, RecurringChainInfoEntry> = new Map();\n\n for (const entry of supportedChains.values()) {\n if (typeof entry.chainId !== 'number' || !entry.recurring) {\n continue;\n }\n\n recurringChainInfo.set(entry.chainId, {\n minFrequencySeconds: entry.recurring.minFrequencySeconds,\n supportedTokens: entry.recurring.supportedTokens,\n });\n }\n\n return recurringChainInfo;\n}\n"],"mappings":"AAWA,SAAgB,EAAyB,EAA4D,CACnG,IAAM,EAA2D,IAAI,IAErE,IAAK,IAAM,KAAS,EAAgB,QAAQ,CACtC,OAAO,EAAM,SAAY,UAAY,CAAC,EAAM,WAIhD,EAAmB,IAAI,EAAM,QAAS,CACpC,oBAAqB,EAAM,UAAU,oBACrC,gBAAiB,EAAM,UAAU,gBAClC,CAAC,CAGJ,OAAO"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
require(`../../../_virtual/_rolldown/runtime.cjs`);const e=require(`./types.cjs`);let t=require(`viem`);function n(n){let{recurringChainInfo:r,fromTokenAddress:i,toTokenAddress:a,sourceChainId:o,targetChainId:s,ownerAddress:c,amount:l}=n;if(!c)return{eligible:!1,reason:e.RecurringEligibilityReason.NoEvmAddress};if(o!==s)return{eligible:!1,reason:e.RecurringEligibilityReason.CrossChain};let u=r.get(o);if(!u||u.supportedTokens.length===0)return{eligible:!1,reason:e.RecurringEligibilityReason.UnsupportedSourceChain};let d=u.supportedTokens.find(e=>(0,t.isAddressEqual)(e.address,i));return!d||(0,t.isAddressEqual)(a,i)?{eligible:!1,reason:e.RecurringEligibilityReason.UnsupportedToken}:l!==void 0&&l<BigInt(d.minimumAmount)?{eligible:!1,reason:e.RecurringEligibilityReason.AmountBelowMinimum,minimumAmount:d.minimumAmount}:{eligible:!0,minimumAmount:d.minimumAmount,minIntervalSeconds:u.minFrequencySeconds}}exports.checkRecurringEligibility=n;
|
|
2
|
+
//# sourceMappingURL=_eligibility.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_eligibility.cjs","names":["RecurringEligibilityReason"],"sources":["../../../../src/transfer-service/markr/recurring/_eligibility.ts"],"sourcesContent":["import { isAddressEqual } from 'viem';\nimport { RecurringEligibilityReason } from './types';\nimport type { CheckRecurringEligibilityParams, RecurringChainInfoEntry, RecurringEligibility } from './types';\n\n/**\n * Pure check that a `(fromToken, toToken, ownerAddress)` triple is supported\n * for recurring swaps against a cached `/info/chains` response.\n *\n * Mirrors the branch order of the mobile `useRecurringEligibility` hook so the\n * `reason` codes returned here can drive UI strings unchanged.\n *\n * ## What this checks (static, no I/O)\n *\n * - Owner has an EVM address → `NoEvmAddress`\n * - Source and target chains match (same-chain only) → `CrossChain`\n * - Chain is in the cached recurring chain-info map → `UnsupportedSourceChain`\n * - `fromTokenAddress` is in the chain's supported list → `UnsupportedToken`\n * - `toTokenAddress` differs from `fromTokenAddress` → `UnsupportedToken`\n * - When `amount` is provided, `amount >= minimumAmount` → `AmountBelowMinimum`\n * (the failure variant carries `minimumAmount` so error UIs can say\n * \"Min is X\" without a second `getRecurringChainInfo()` lookup)\n *\n * ## What this does NOT check\n *\n * - **Wallet balance.** This helper has no wallet/RPC context — it cannot\n * compare `amount × numberOfOrders` against the user's `tokenIn` balance,\n * their native-gas balance for the first-fill TX, or any other on-chain\n * state. Balance checks are the **consumer's** responsibility, same as the\n * one-shot swap flow.\n * - **Post-fill failures** (e.g. a scheduled fill reverts because the user\n * later moved funds). These surface server-side via\n * `RecurringOrder.failures[].reasons: ReadonlyArray<string>` — open-ended\n * strings, NOT this enum. Markr emits literals like `\"Insufficient balance\"`\n * or `\"Slippage tolerance exceeded\"`; consumers substring-match per the\n * AC4 auto-cancel plan and call {@link RecurringNamespace.prepareCancellation}\n * when applicable. Kept as `string` (with `(string & NonNullable<unknown>)`\n * widening) so a new server-side reason doesn't brick already-shipped clients.\n * - **Server-side quote rejection** (slippage, target-token unsupported,\n * liquidity, etc.) — Markr decides at `/recurring/quote` time. Surface\n * those as `HttpError(400)` / `HttpError(422)` from\n * {@link RecurringNamespace.quote}.\n *\n * Net: this helper covers the \"can the user *attempt* a recurring swap with\n * this token pair at this size\" question. Anything that requires a wallet,\n * RPC, or live orchestrator round-trip lives elsewhere.\n */\nexport function checkRecurringEligibility(params: CheckRecurringEligibilityParams): RecurringEligibility {\n const { recurringChainInfo, fromTokenAddress, toTokenAddress, sourceChainId, targetChainId, ownerAddress, amount } =\n params;\n\n if (!ownerAddress) {\n return { eligible: false, reason: RecurringEligibilityReason.NoEvmAddress };\n }\n\n if (sourceChainId !== targetChainId) {\n return { eligible: false, reason: RecurringEligibilityReason.CrossChain };\n }\n\n const chain: RecurringChainInfoEntry | undefined = recurringChainInfo.get(sourceChainId);\n\n if (!chain || chain.supportedTokens.length === 0) {\n return { eligible: false, reason: RecurringEligibilityReason.UnsupportedSourceChain };\n }\n\n // `isAddressEqual` does a case-insensitive compare without per-call string\n // allocations (matches the established pattern in `markr/_utils.ts`). The\n // `EvmAddress` brand type guarantees the inputs are well-formed; if a JS\n // consumer reaches in with a malformed value, the resulting throw is the\n // right failure mode (loud > silently \"unsupported-token\").\n const supportedToken = chain.supportedTokens.find((token) => isAddressEqual(token.address, fromTokenAddress));\n\n if (!supportedToken) {\n return { eligible: false, reason: RecurringEligibilityReason.UnsupportedToken };\n }\n\n // The target token only needs to exist on the same chain; recurring swaps\n // are one-way (tokenIn → tokenOut) and Markr decides target eligibility\n // server-side at /recurring/quote time. Reject the obvious nonsense\n // (`toTokenAddress` matching `fromTokenAddress`) up front to fail fast.\n if (isAddressEqual(toTokenAddress, fromTokenAddress)) {\n return { eligible: false, reason: RecurringEligibilityReason.UnsupportedToken };\n }\n\n if (amount !== undefined && amount < BigInt(supportedToken.minimumAmount)) {\n return {\n eligible: false,\n reason: RecurringEligibilityReason.AmountBelowMinimum,\n minimumAmount: supportedToken.minimumAmount,\n };\n }\n\n return {\n eligible: true,\n minimumAmount: supportedToken.minimumAmount,\n minIntervalSeconds: chain.minFrequencySeconds,\n };\n}\n"],"mappings":"wGA8CA,SAAgB,EAA0B,EAA+D,CACvG,GAAM,CAAE,qBAAoB,mBAAkB,iBAAgB,gBAAe,gBAAe,eAAc,UACxG,EAEF,GAAI,CAAC,EACH,MAAO,CAAE,SAAU,GAAO,OAAQA,EAAAA,2BAA2B,aAAc,CAG7E,GAAI,IAAkB,EACpB,MAAO,CAAE,SAAU,GAAO,OAAQA,EAAAA,2BAA2B,WAAY,CAG3E,IAAM,EAA6C,EAAmB,IAAI,EAAc,CAExF,GAAI,CAAC,GAAS,EAAM,gBAAgB,SAAW,EAC7C,MAAO,CAAE,SAAU,GAAO,OAAQA,EAAAA,2BAA2B,uBAAwB,CAQvF,IAAM,EAAiB,EAAM,gBAAgB,KAAM,IAAA,EAAA,EAAA,gBAAyB,EAAM,QAAS,EAAiB,CAAC,CAsB7G,MApBI,CAAC,IAQL,EAAA,EAAA,gBAAmB,EAAgB,EAAiB,CAC3C,CAAE,SAAU,GAAO,OAAQA,EAAAA,2BAA2B,iBAAkB,CAG7E,IAAW,IAAA,IAAa,EAAS,OAAO,EAAe,cAAc,CAChE,CACL,SAAU,GACV,OAAQA,EAAAA,2BAA2B,mBACnC,cAAe,EAAe,cAC/B,CAGI,CACL,SAAU,GACV,cAAe,EAAe,cAC9B,mBAAoB,EAAM,oBAC3B"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{RecurringEligibilityReason as e}from"./types.js";import{isAddressEqual as t}from"viem";function n(n){let{recurringChainInfo:r,fromTokenAddress:i,toTokenAddress:a,sourceChainId:o,targetChainId:s,ownerAddress:c,amount:l}=n;if(!c)return{eligible:!1,reason:e.NoEvmAddress};if(o!==s)return{eligible:!1,reason:e.CrossChain};let u=r.get(o);if(!u||u.supportedTokens.length===0)return{eligible:!1,reason:e.UnsupportedSourceChain};let d=u.supportedTokens.find(e=>t(e.address,i));return!d||t(a,i)?{eligible:!1,reason:e.UnsupportedToken}:l!==void 0&&l<BigInt(d.minimumAmount)?{eligible:!1,reason:e.AmountBelowMinimum,minimumAmount:d.minimumAmount}:{eligible:!0,minimumAmount:d.minimumAmount,minIntervalSeconds:u.minFrequencySeconds}}export{n as checkRecurringEligibility};
|
|
2
|
+
//# sourceMappingURL=_eligibility.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_eligibility.js","names":[],"sources":["../../../../src/transfer-service/markr/recurring/_eligibility.ts"],"sourcesContent":["import { isAddressEqual } from 'viem';\nimport { RecurringEligibilityReason } from './types';\nimport type { CheckRecurringEligibilityParams, RecurringChainInfoEntry, RecurringEligibility } from './types';\n\n/**\n * Pure check that a `(fromToken, toToken, ownerAddress)` triple is supported\n * for recurring swaps against a cached `/info/chains` response.\n *\n * Mirrors the branch order of the mobile `useRecurringEligibility` hook so the\n * `reason` codes returned here can drive UI strings unchanged.\n *\n * ## What this checks (static, no I/O)\n *\n * - Owner has an EVM address → `NoEvmAddress`\n * - Source and target chains match (same-chain only) → `CrossChain`\n * - Chain is in the cached recurring chain-info map → `UnsupportedSourceChain`\n * - `fromTokenAddress` is in the chain's supported list → `UnsupportedToken`\n * - `toTokenAddress` differs from `fromTokenAddress` → `UnsupportedToken`\n * - When `amount` is provided, `amount >= minimumAmount` → `AmountBelowMinimum`\n * (the failure variant carries `minimumAmount` so error UIs can say\n * \"Min is X\" without a second `getRecurringChainInfo()` lookup)\n *\n * ## What this does NOT check\n *\n * - **Wallet balance.** This helper has no wallet/RPC context — it cannot\n * compare `amount × numberOfOrders` against the user's `tokenIn` balance,\n * their native-gas balance for the first-fill TX, or any other on-chain\n * state. Balance checks are the **consumer's** responsibility, same as the\n * one-shot swap flow.\n * - **Post-fill failures** (e.g. a scheduled fill reverts because the user\n * later moved funds). These surface server-side via\n * `RecurringOrder.failures[].reasons: ReadonlyArray<string>` — open-ended\n * strings, NOT this enum. Markr emits literals like `\"Insufficient balance\"`\n * or `\"Slippage tolerance exceeded\"`; consumers substring-match per the\n * AC4 auto-cancel plan and call {@link RecurringNamespace.prepareCancellation}\n * when applicable. Kept as `string` (with `(string & NonNullable<unknown>)`\n * widening) so a new server-side reason doesn't brick already-shipped clients.\n * - **Server-side quote rejection** (slippage, target-token unsupported,\n * liquidity, etc.) — Markr decides at `/recurring/quote` time. Surface\n * those as `HttpError(400)` / `HttpError(422)` from\n * {@link RecurringNamespace.quote}.\n *\n * Net: this helper covers the \"can the user *attempt* a recurring swap with\n * this token pair at this size\" question. Anything that requires a wallet,\n * RPC, or live orchestrator round-trip lives elsewhere.\n */\nexport function checkRecurringEligibility(params: CheckRecurringEligibilityParams): RecurringEligibility {\n const { recurringChainInfo, fromTokenAddress, toTokenAddress, sourceChainId, targetChainId, ownerAddress, amount } =\n params;\n\n if (!ownerAddress) {\n return { eligible: false, reason: RecurringEligibilityReason.NoEvmAddress };\n }\n\n if (sourceChainId !== targetChainId) {\n return { eligible: false, reason: RecurringEligibilityReason.CrossChain };\n }\n\n const chain: RecurringChainInfoEntry | undefined = recurringChainInfo.get(sourceChainId);\n\n if (!chain || chain.supportedTokens.length === 0) {\n return { eligible: false, reason: RecurringEligibilityReason.UnsupportedSourceChain };\n }\n\n // `isAddressEqual` does a case-insensitive compare without per-call string\n // allocations (matches the established pattern in `markr/_utils.ts`). The\n // `EvmAddress` brand type guarantees the inputs are well-formed; if a JS\n // consumer reaches in with a malformed value, the resulting throw is the\n // right failure mode (loud > silently \"unsupported-token\").\n const supportedToken = chain.supportedTokens.find((token) => isAddressEqual(token.address, fromTokenAddress));\n\n if (!supportedToken) {\n return { eligible: false, reason: RecurringEligibilityReason.UnsupportedToken };\n }\n\n // The target token only needs to exist on the same chain; recurring swaps\n // are one-way (tokenIn → tokenOut) and Markr decides target eligibility\n // server-side at /recurring/quote time. Reject the obvious nonsense\n // (`toTokenAddress` matching `fromTokenAddress`) up front to fail fast.\n if (isAddressEqual(toTokenAddress, fromTokenAddress)) {\n return { eligible: false, reason: RecurringEligibilityReason.UnsupportedToken };\n }\n\n if (amount !== undefined && amount < BigInt(supportedToken.minimumAmount)) {\n return {\n eligible: false,\n reason: RecurringEligibilityReason.AmountBelowMinimum,\n minimumAmount: supportedToken.minimumAmount,\n };\n }\n\n return {\n eligible: true,\n minimumAmount: supportedToken.minimumAmount,\n minIntervalSeconds: chain.minFrequencySeconds,\n };\n}\n"],"mappings":"8FA8CA,SAAgB,EAA0B,EAA+D,CACvG,GAAM,CAAE,qBAAoB,mBAAkB,iBAAgB,gBAAe,gBAAe,eAAc,UACxG,EAEF,GAAI,CAAC,EACH,MAAO,CAAE,SAAU,GAAO,OAAQ,EAA2B,aAAc,CAG7E,GAAI,IAAkB,EACpB,MAAO,CAAE,SAAU,GAAO,OAAQ,EAA2B,WAAY,CAG3E,IAAM,EAA6C,EAAmB,IAAI,EAAc,CAExF,GAAI,CAAC,GAAS,EAAM,gBAAgB,SAAW,EAC7C,MAAO,CAAE,SAAU,GAAO,OAAQ,EAA2B,uBAAwB,CAQvF,IAAM,EAAiB,EAAM,gBAAgB,KAAM,GAAU,EAAe,EAAM,QAAS,EAAiB,CAAC,CAsB7G,MApBI,CAAC,GAQD,EAAe,EAAgB,EAAiB,CAC3C,CAAE,SAAU,GAAO,OAAQ,EAA2B,iBAAkB,CAG7E,IAAW,IAAA,IAAa,EAAS,OAAO,EAAe,cAAc,CAChE,CACL,SAAU,GACV,OAAQ,EAA2B,mBACnC,cAAe,EAAe,cAC/B,CAGI,CACL,SAAU,GACV,cAAe,EAAe,cAC9B,mBAAoB,EAAM,oBAC3B"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function t(t){return e[t.unit]*t.value}function n(n,r){if(!(n.unit in e))return{ok:!1,reason:`invalid-unit`};if(!Number.isInteger(n.value)||n.value<1||n.value>365)return{ok:!1,reason:`invalid-value`};let i=t(n);return i<r?{ok:!1,reason:`below-minimum`}:{ok:!0,intervalSeconds:i}}exports.RECURRING_FREQUENCY_VALUE_MAX=365,exports.deriveIntervalSeconds=t,exports.validateFrequency=n;
|
|
2
|
+
//# sourceMappingURL=_frequency.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_frequency.cjs","names":[],"sources":["../../../../src/transfer-service/markr/recurring/_frequency.ts"],"sourcesContent":["import type { RecurringFrequency, RecurringFrequencyUnit } from './types';\n\n/**\n * Seconds-per-unit lookup. The \"month\" entry uses 30 days; Markr's `/recurring/quote`\n * returns the server-derived `intervalSeconds`, so this helper is a client-side\n * estimator (used for the picker's \"below-minimum\" greying), not the source of truth.\n */\nconst SECONDS_BY_UNIT: Readonly<Record<RecurringFrequencyUnit, number>> = {\n minute: 60,\n hour: 3600,\n day: 86_400,\n week: 604_800,\n month: 2_592_000,\n};\n\nexport function deriveIntervalSeconds(frequency: RecurringFrequency): number {\n return SECONDS_BY_UNIT[frequency.unit] * frequency.value;\n}\n\nexport type FrequencyValidationResult =\n | { ok: true; intervalSeconds: number }\n | { ok: false; reason: 'below-minimum' | 'invalid-unit' | 'invalid-value' };\n\n/** Server-enforced upper bound on `RecurringFrequency.value` (per Markr API docs). */\nexport const RECURRING_FREQUENCY_VALUE_MAX = 365;\n\nexport function validateFrequency(\n frequency: RecurringFrequency,\n minFrequencySeconds: number,\n): FrequencyValidationResult {\n if (!(frequency.unit in SECONDS_BY_UNIT)) {\n return { ok: false, reason: 'invalid-unit' };\n }\n\n // `1 ≤ value ≤ 365` mirrors the server-side bound. Catching it here lets\n // picker UIs surface the error inline instead of waiting for the\n // `/recurring/quote` HTTP round-trip to fail.\n if (!Number.isInteger(frequency.value) || frequency.value < 1 || frequency.value > RECURRING_FREQUENCY_VALUE_MAX) {\n return { ok: false, reason: 'invalid-value' };\n }\n\n const intervalSeconds = deriveIntervalSeconds(frequency);\n\n if (intervalSeconds < minFrequencySeconds) {\n return { ok: false, reason: 'below-minimum' };\n }\n\n return { ok: true, intervalSeconds };\n}\n"],"mappings":"AAOA,MAAM,EAAoE,CACxE,OAAQ,GACR,KAAM,KACN,IAAK,MACL,KAAM,OACN,MAAO,OACR,CAED,SAAgB,EAAsB,EAAuC,CAC3E,OAAO,EAAgB,EAAU,MAAQ,EAAU,MAUrD,SAAgB,EACd,EACA,EAC2B,CAC3B,GAAI,EAAE,EAAU,QAAQ,GACtB,MAAO,CAAE,GAAI,GAAO,OAAQ,eAAgB,CAM9C,GAAI,CAAC,OAAO,UAAU,EAAU,MAAM,EAAI,EAAU,MAAQ,GAAK,EAAU,MAAA,IACzE,MAAO,CAAE,GAAI,GAAO,OAAQ,gBAAiB,CAG/C,IAAM,EAAkB,EAAsB,EAAU,CAMxD,OAJI,EAAkB,EACb,CAAE,GAAI,GAAO,OAAQ,gBAAiB,CAGxC,CAAE,GAAI,GAAM,kBAAiB"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { RecurringFrequency } from "./types.cjs";
|
|
2
|
+
|
|
3
|
+
//#region src/transfer-service/markr/recurring/_frequency.d.ts
|
|
4
|
+
declare function deriveIntervalSeconds(frequency: RecurringFrequency): number;
|
|
5
|
+
type FrequencyValidationResult = {
|
|
6
|
+
ok: true;
|
|
7
|
+
intervalSeconds: number;
|
|
8
|
+
} | {
|
|
9
|
+
ok: false;
|
|
10
|
+
reason: "below-minimum" | "invalid-unit" | "invalid-value";
|
|
11
|
+
};
|
|
12
|
+
/** Server-enforced upper bound on `RecurringFrequency.value` (per Markr API docs). */
|
|
13
|
+
declare const RECURRING_FREQUENCY_VALUE_MAX = 365;
|
|
14
|
+
declare function validateFrequency(frequency: RecurringFrequency, minFrequencySeconds: number): FrequencyValidationResult;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { FrequencyValidationResult, RECURRING_FREQUENCY_VALUE_MAX, deriveIntervalSeconds, validateFrequency };
|
|
17
|
+
//# sourceMappingURL=_frequency.d.cts.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { RecurringFrequency } from "./types.js";
|
|
2
|
+
|
|
3
|
+
//#region src/transfer-service/markr/recurring/_frequency.d.ts
|
|
4
|
+
declare function deriveIntervalSeconds(frequency: RecurringFrequency): number;
|
|
5
|
+
type FrequencyValidationResult = {
|
|
6
|
+
ok: true;
|
|
7
|
+
intervalSeconds: number;
|
|
8
|
+
} | {
|
|
9
|
+
ok: false;
|
|
10
|
+
reason: "below-minimum" | "invalid-unit" | "invalid-value";
|
|
11
|
+
};
|
|
12
|
+
/** Server-enforced upper bound on `RecurringFrequency.value` (per Markr API docs). */
|
|
13
|
+
declare const RECURRING_FREQUENCY_VALUE_MAX = 365;
|
|
14
|
+
declare function validateFrequency(frequency: RecurringFrequency, minFrequencySeconds: number): FrequencyValidationResult;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { FrequencyValidationResult, RECURRING_FREQUENCY_VALUE_MAX, deriveIntervalSeconds, validateFrequency };
|
|
17
|
+
//# sourceMappingURL=_frequency.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function t(t){return e[t.unit]*t.value}const n=365;function r(n,r){if(!(n.unit in e))return{ok:!1,reason:`invalid-unit`};if(!Number.isInteger(n.value)||n.value<1||n.value>365)return{ok:!1,reason:`invalid-value`};let i=t(n);return i<r?{ok:!1,reason:`below-minimum`}:{ok:!0,intervalSeconds:i}}export{n as RECURRING_FREQUENCY_VALUE_MAX,t as deriveIntervalSeconds,r as validateFrequency};
|
|
2
|
+
//# sourceMappingURL=_frequency.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_frequency.js","names":[],"sources":["../../../../src/transfer-service/markr/recurring/_frequency.ts"],"sourcesContent":["import type { RecurringFrequency, RecurringFrequencyUnit } from './types';\n\n/**\n * Seconds-per-unit lookup. The \"month\" entry uses 30 days; Markr's `/recurring/quote`\n * returns the server-derived `intervalSeconds`, so this helper is a client-side\n * estimator (used for the picker's \"below-minimum\" greying), not the source of truth.\n */\nconst SECONDS_BY_UNIT: Readonly<Record<RecurringFrequencyUnit, number>> = {\n minute: 60,\n hour: 3600,\n day: 86_400,\n week: 604_800,\n month: 2_592_000,\n};\n\nexport function deriveIntervalSeconds(frequency: RecurringFrequency): number {\n return SECONDS_BY_UNIT[frequency.unit] * frequency.value;\n}\n\nexport type FrequencyValidationResult =\n | { ok: true; intervalSeconds: number }\n | { ok: false; reason: 'below-minimum' | 'invalid-unit' | 'invalid-value' };\n\n/** Server-enforced upper bound on `RecurringFrequency.value` (per Markr API docs). */\nexport const RECURRING_FREQUENCY_VALUE_MAX = 365;\n\nexport function validateFrequency(\n frequency: RecurringFrequency,\n minFrequencySeconds: number,\n): FrequencyValidationResult {\n if (!(frequency.unit in SECONDS_BY_UNIT)) {\n return { ok: false, reason: 'invalid-unit' };\n }\n\n // `1 ≤ value ≤ 365` mirrors the server-side bound. Catching it here lets\n // picker UIs surface the error inline instead of waiting for the\n // `/recurring/quote` HTTP round-trip to fail.\n if (!Number.isInteger(frequency.value) || frequency.value < 1 || frequency.value > RECURRING_FREQUENCY_VALUE_MAX) {\n return { ok: false, reason: 'invalid-value' };\n }\n\n const intervalSeconds = deriveIntervalSeconds(frequency);\n\n if (intervalSeconds < minFrequencySeconds) {\n return { ok: false, reason: 'below-minimum' };\n }\n\n return { ok: true, intervalSeconds };\n}\n"],"mappings":"AAOA,MAAM,EAAoE,CACxE,OAAQ,GACR,KAAM,KACN,IAAK,MACL,KAAM,OACN,MAAO,OACR,CAED,SAAgB,EAAsB,EAAuC,CAC3E,OAAO,EAAgB,EAAU,MAAQ,EAAU,MAQrD,MAAa,EAAgC,IAE7C,SAAgB,EACd,EACA,EAC2B,CAC3B,GAAI,EAAE,EAAU,QAAQ,GACtB,MAAO,CAAE,GAAI,GAAO,OAAQ,eAAgB,CAM9C,GAAI,CAAC,OAAO,UAAU,EAAU,MAAM,EAAI,EAAU,MAAQ,GAAK,EAAU,MAAA,IACzE,MAAO,CAAE,GAAI,GAAO,OAAQ,gBAAiB,CAG/C,IAAM,EAAkB,EAAsB,EAAU,CAMxD,OAJI,EAAkB,EACb,CAAE,GAAI,GAAO,OAAQ,gBAAiB,CAGxC,CAAE,GAAI,GAAM,kBAAiB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
require(`../../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../../constants.cjs`),t=require(`../../../errors.cjs`),n=require(`../../../utils/caip.cjs`),r=require(`../../_utils.cjs`),i=require(`../../_evm-errors.cjs`),a=require(`../../_evm-approval.cjs`),o=require(`../_api.cjs`),s=require(`../_utils.cjs`),c=require(`./_api.cjs`),l=require(`./_eligibility.cjs`);let u=require(`viem`);function d({apiOptions:e,appId:t,evmSigner:n,recurringChainInfo:r}){return{quote:n=>c.markrRecurringQuote(e,{...n,appId:t}),executeFirstFill:r=>f({...r,apiOptions:e,appId:t,evmSigner:n}),listOrders:t=>c.markrListRecurringOrders(e,t),executeCancellation:t=>p({...t,action:`cancel`,apiOptions:e,evmSigner:n,fetchCalldata:c.markrPrepareCancellation}),executePause:t=>p({...t,action:`pause`,apiOptions:e,evmSigner:n,fetchCalldata:c.markrPreparePause}),executeUnpause:t=>p({...t,action:`unpause`,apiOptions:e,evmSigner:n,fetchCalldata:c.markrPrepareUnpause}),checkEligibility:e=>l.checkRecurringEligibility({...e,recurringChainInfo:r}),getRecurringChainInfo:()=>r}}async function f({apiOptions:l,appId:u,evmSigner:d,fallbackToDefaultOnBatchFailure:f,fromAddress:p,gasSettings:h,quote:g,sourceChain:_}){let v=Math.floor(Date.now()/1e3);if(g.expiredAt<=v){let e=v-g.expiredAt;throw new t.InvalidParamsError(t.ErrorReason.QUOTE_EXPIRED,`Recurring quote expired ${e} seconds ago.`)}let y=n.caip2ToEip155ChainId(_.chainId);if(y!==g.chainId)throw new t.InvalidParamsError(`sourceChain does not match quote.chainId`,`sourceChain.chainId=${_.chainId} resolves to ${y}, but quote.chainId=${g.chainId}.`);let b=r.getEvmClientForChain({chain:_}),x=n.caip2ToEip155HexChainId(_.chainId),{address:S}=await o.markrGetSpenderAddress(l,{chainId:g.chainId,crossChainSwap:!1,quoteId:g.uuid});if(!S)throw new t.SdkError(t.ErrorReason.CHAIN_NOT_SUPPORTED,t.ErrorCode.INVALID_PARAMS,{details:`Missing Markr spender address for source chain ${_.chainId}.`});let C=await a.buildErc20ApprovalRequest({chainIdHex:x,client:b,gasSettings:h,owner:p,requiredAllowance:g.totalAmountIn,spender:S,token:g.tokenIn}),w=m({fromAddress:p,quote:g,sourceChain:_}),T=await c.markrRecurringSwap(l,{uuid:g.uuid,appId:u});if(C!==void 0&&typeof d.signBatch==`function`){let n={currentSignature:1,currentSignatureReason:e.TransferSignatureReason.TokensTransfer,quote:w,requiredSignatures:1},i={chainId:x,data:T.data,from:p,gas:void 0,to:T.to,value:T.value,...r.maybe1559(h)};try{let e=(await d.signBatch([C,i],e=>b.sendRawTransaction({serializedTransaction:e}),n)).at(-1);if(!e)throw new t.SdkError(`One-click batch signing returned no transaction hashes.`,t.ErrorCode.SIGNING_FAILED);return{txHash:e}}catch(e){if(!f)throw e}}C&&await a.signApprovalAndAssertConfirmed({client:b,evmSigner:d,request:C,step:{currentSignature:1,currentSignatureReason:e.TransferSignatureReason.AllowanceApproval,quote:w,requiredSignatures:2}});let E=await s.getMarkrSwapWrapperAbi(!1),D=await i.estimateGasWithRevert(b,{account:p,to:T.to,data:T.data,value:T.value},E,`Failed to estimate gas for recurring first-fill swap transaction.`),O={chainId:x,data:T.data,from:p,gas:r.applyFeeUnitsBpsMargin(D,h?.estimateGasMarginBps),to:T.to,value:T.value,...r.maybe1559(h)},k={currentSignature:C?2:1,currentSignatureReason:e.TransferSignatureReason.TokensTransfer,quote:w,requiredSignatures:C?2:1};return{txHash:await d.sign(O,e=>b.sendRawTransaction({serializedTransaction:e}),k)}}async function p({action:t,address:a,apiOptions:o,evmSigner:s,fetchCalldata:c,gasSettings:l,orderId:d,sourceChain:f}){let p=r.getEvmClientForChain({chain:f}),m=n.caip2ToEip155ChainId(f.chainId),g=n.caip2ToEip155HexChainId(f.chainId),_=await c(o,{orderId:d,address:a,chainId:m}),v=await i.estimateGasWithRevert(p,{account:a,to:_.to,data:_.data,value:_.value},u.erc20Abi,`Failed to estimate gas for recurring ${t} transaction.`),y={chainId:g,data:_.data,from:a,gas:r.applyFeeUnitsBpsMargin(v,l?.estimateGasMarginBps),to:_.to,value:_.value,...r.maybe1559(l)},b={currentSignature:1,currentSignatureReason:e.TransferSignatureReason.TokensTransfer,quote:h({address:a,action:t,orderId:d,sourceChain:f}),requiredSignatures:1};return{txHash:await s.sign(y,e=>p.sendRawTransaction({serializedTransaction:e}),b)}}function m({fromAddress:t,quote:n,sourceChain:r}){return{aggregator:{id:`markr-recurring`,name:`Markr Recurring`},amountIn:n.amount,amountOut:n.amountOut,assetIn:{type:e.TokenType.ERC20,address:n.tokenIn,name:``,symbol:``,decimals:0},assetOut:{type:e.TokenType.ERC20,address:n.tokenOut,name:``,symbol:``,decimals:0},expiresAt:n.expiredAt,fees:[],fromAddress:t,id:n.uuid,partnerFeeBps:null,serviceType:e.ServiceType.MARKR,slippageBps:n.recommendedSlippage,sourceChain:r,targetChain:r,toAddress:t}}function h({action:t,address:n,orderId:r,sourceChain:i}){return{aggregator:{id:`markr-recurring-${t}`,name:`Markr Recurring (${t})`},amountIn:0n,amountOut:0n,assetIn:g(),assetOut:g(),expiresAt:0,fees:[],fromAddress:n,id:r,partnerFeeBps:null,serviceType:e.ServiceType.MARKR,slippageBps:0,sourceChain:i,targetChain:i,toAddress:n}}function g(){return{type:e.TokenType.NATIVE,name:``,symbol:``,decimals:0}}exports.createRecurringNamespace=d;
|
|
2
|
+
//# sourceMappingURL=_namespace.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_namespace.cjs","names":["markrRecurringQuote","markrListRecurringOrders","markrPrepareCancellation","markrPreparePause","markrPrepareUnpause","checkRecurringEligibility","InvalidParamsError","ErrorReason","caip2ToEip155ChainId","getEvmClientForChain","caip2ToEip155HexChainId","markrGetSpenderAddress","SdkError","ErrorCode","buildErc20ApprovalRequest","markrRecurringSwap","TransferSignatureReason","maybe1559","signApprovalAndAssertConfirmed","getMarkrSwapWrapperAbi","estimateGasWithRevert","applyFeeUnitsBpsMargin","erc20Abi","TokenType","ServiceType"],"sources":["../../../../src/transfer-service/markr/recurring/_namespace.ts"],"sourcesContent":["import { erc20Abi } from 'viem';\nimport { ServiceType, TokenType, TransferSignatureReason } from '../../../constants';\nimport { ErrorCode, ErrorReason, InvalidParamsError, SdkError } from '../../../errors';\nimport type { Chain } from '../../../types/chain';\nimport type { Quote } from '../../../types/quote';\nimport type { EvmSigner, EvmTransactionRequest } from '../../../types/signer';\nimport type { TransferStepDetails } from '../../../types/transfer';\nimport { caip2ToEip155ChainId, caip2ToEip155HexChainId } from '../../../utils/caip';\nimport { applyFeeUnitsBpsMargin, getEvmClientForChain, maybe1559 } from '../../_utils';\nimport { buildErc20ApprovalRequest, signApprovalAndAssertConfirmed } from '../../_evm-approval';\nimport { estimateGasWithRevert } from '../../_evm-errors';\nimport type { WrappedSwapTransactionResponse } from '../_schema';\nimport { markrGetSpenderAddress, type ApiOptions } from '../_api';\nimport { getMarkrSwapWrapperAbi } from '../_utils';\nimport {\n markrListRecurringOrders,\n markrPrepareCancellation,\n markrPreparePause,\n markrPrepareUnpause,\n markrRecurringQuote,\n markrRecurringSwap,\n} from './_api';\nimport { checkRecurringEligibility } from './_eligibility';\nimport type {\n RecurringChainInfoMap,\n RecurringExecuteFirstFillParams,\n RecurringExecuteOrderActionParams,\n RecurringExecuteResult,\n RecurringNamespace,\n RecurringQuoteResponse,\n} from './types';\n\nexport interface CreateRecurringNamespaceOptions {\n apiOptions: ApiOptions;\n appId: string;\n evmSigner: EvmSigner;\n /**\n * The cached `/info/chains` recurring metadata. Captured by value at\n * namespace construction time — matches how `partnerFeeBps`,\n * `supportedChains`, and `supportedTokens` are also frozen at\n * `createMarkrService` init. If staleness ever becomes a real consumer\n * concern, the fix is a top-level `manager.refresh()` (not a per-namespace\n * lazy-read pattern).\n */\n recurringChainInfo: RecurringChainInfoMap;\n}\n\nexport function createRecurringNamespace({\n apiOptions,\n appId,\n evmSigner,\n recurringChainInfo,\n}: CreateRecurringNamespaceOptions): RecurringNamespace {\n return {\n quote: (props) => markrRecurringQuote(apiOptions, { ...props, appId }),\n\n executeFirstFill: (props) => executeFirstFillImpl({ ...props, apiOptions, appId, evmSigner }),\n\n listOrders: (props) => markrListRecurringOrders(apiOptions, props),\n\n executeCancellation: (props) =>\n executeOrderActionImpl({\n ...props,\n action: 'cancel',\n apiOptions,\n evmSigner,\n fetchCalldata: markrPrepareCancellation,\n }),\n\n executePause: (props) =>\n executeOrderActionImpl({\n ...props,\n action: 'pause',\n apiOptions,\n evmSigner,\n fetchCalldata: markrPreparePause,\n }),\n\n executeUnpause: (props) =>\n executeOrderActionImpl({\n ...props,\n action: 'unpause',\n apiOptions,\n evmSigner,\n fetchCalldata: markrPrepareUnpause,\n }),\n\n checkEligibility: (props) => checkRecurringEligibility({ ...props, recurringChainInfo }),\n\n getRecurringChainInfo: () => recurringChainInfo,\n };\n}\n\n// ---------------------------------------------------------------------------\n// First-fill execution (allowance check + approve-if-needed + first-fill swap)\n// ---------------------------------------------------------------------------\n\ninterface ExecuteFirstFillImplParams extends RecurringExecuteFirstFillParams {\n apiOptions: ApiOptions;\n appId: string;\n evmSigner: EvmSigner;\n}\n\nasync function executeFirstFillImpl({\n apiOptions,\n appId,\n evmSigner,\n fallbackToDefaultOnBatchFailure,\n fromAddress,\n gasSettings,\n quote,\n sourceChain,\n}: ExecuteFirstFillImplParams): Promise<RecurringExecuteResult> {\n // Mirror the one-shot guard at `TransferManager.estimateNativeFee` — fail at\n // the SDK boundary with `QUOTE_EXPIRED` instead of an opaque `HttpError`\n // from `/recurring/swap` for a slow-to-approve user.\n const now = Math.floor(Date.now() / 1_000);\n if (quote.expiredAt <= now) {\n const expiredSecondsAgo = now - quote.expiredAt;\n throw new InvalidParamsError(\n ErrorReason.QUOTE_EXPIRED,\n `Recurring quote expired ${expiredSecondsAgo} seconds ago.`,\n );\n }\n\n // Wiring-mistake guard: the passed `sourceChain.chainId` (CAIP-2) must agree\n // with the `chainId` (numeric) the quote was issued against. Otherwise the\n // allowance / gas reads hit the wrong chain.\n const sourceChainIdNumeric = caip2ToEip155ChainId(sourceChain.chainId);\n if (sourceChainIdNumeric !== quote.chainId) {\n throw new InvalidParamsError(\n 'sourceChain does not match quote.chainId',\n `sourceChain.chainId=${sourceChain.chainId} resolves to ${sourceChainIdNumeric}, but quote.chainId=${quote.chainId}.`,\n );\n }\n\n const sourceClient = getEvmClientForChain({ chain: sourceChain });\n const chainIdHex = caip2ToEip155HexChainId(sourceChain.chainId);\n\n const { address: spenderAddress } = await markrGetSpenderAddress(apiOptions, {\n chainId: quote.chainId,\n crossChainSwap: false,\n quoteId: quote.uuid,\n });\n\n if (!spenderAddress) {\n throw new SdkError(ErrorReason.CHAIN_NOT_SUPPORTED, ErrorCode.INVALID_PARAMS, {\n details: `Missing Markr spender address for source chain ${sourceChain.chainId}.`,\n });\n }\n\n const approvalRequest = await buildErc20ApprovalRequest({\n chainIdHex,\n client: sourceClient,\n gasSettings,\n owner: fromAddress,\n requiredAllowance: quote.totalAmountIn,\n spender: spenderAddress,\n token: quote.tokenIn,\n });\n\n const syntheticQuote = buildSyntheticQuoteForFirstFill({ fromAddress, quote, sourceChain });\n\n const swap = await markrRecurringSwap(apiOptions, { uuid: quote.uuid, appId });\n\n // One-click batch path: same-chain DCA, approval required, signer exposes\n // `signBatch`. Matches `_executeEvmTransfer`'s eligibility check (recurring\n // is always same-chain so the cross-chain check there collapses to true).\n if (approvalRequest !== undefined && typeof evmSigner.signBatch === 'function') {\n const batchStep: TransferStepDetails = {\n currentSignature: 1,\n currentSignatureReason: TransferSignatureReason.TokensTransfer,\n quote: syntheticQuote,\n requiredSignatures: 1,\n };\n\n // Gas is left undefined on the swap leg — the wallet handles batched gas\n // estimation since the approval hasn't executed yet.\n const swapRequest: EvmTransactionRequest = {\n chainId: chainIdHex,\n data: swap.data,\n from: fromAddress,\n gas: undefined,\n to: swap.to,\n value: swap.value,\n ...maybe1559(gasSettings),\n };\n\n try {\n const txHashes = await evmSigner.signBatch(\n [approvalRequest, swapRequest],\n (signedTxHash) => sourceClient.sendRawTransaction({ serializedTransaction: signedTxHash }),\n batchStep,\n );\n const swapTxHash = txHashes.at(-1);\n if (!swapTxHash) {\n throw new SdkError('One-click batch signing returned no transaction hashes.', ErrorCode.SIGNING_FAILED);\n }\n return { txHash: swapTxHash };\n } catch (error) {\n if (!fallbackToDefaultOnBatchFailure) {\n throw error;\n }\n // Fall through to the two-signature path below.\n }\n }\n\n if (approvalRequest) {\n await signApprovalAndAssertConfirmed({\n client: sourceClient,\n evmSigner,\n request: approvalRequest,\n step: {\n currentSignature: 1,\n currentSignatureReason: TransferSignatureReason.AllowanceApproval,\n quote: syntheticQuote,\n requiredSignatures: 2,\n },\n });\n }\n\n // Use the Markr same-chain swap wrapper ABI for best-effort revert decoding\n // — matches `_estimateGasFromSwapResponse` in `estimate-native-fee.ts`.\n // Recurring is always same-chain, so `crossChain: false`. Built-in\n // `Error(string)` / `Panic(uint256)` are decoded regardless of ABI.\n const markrAbi = await getMarkrSwapWrapperAbi(false);\n const swapGasEstimate = await estimateGasWithRevert(\n sourceClient,\n { account: fromAddress, to: swap.to, data: swap.data, value: swap.value },\n markrAbi,\n 'Failed to estimate gas for recurring first-fill swap transaction.',\n );\n\n const swapRequest: EvmTransactionRequest = {\n chainId: chainIdHex,\n data: swap.data,\n from: fromAddress,\n gas: applyFeeUnitsBpsMargin(swapGasEstimate, gasSettings?.estimateGasMarginBps),\n to: swap.to,\n value: swap.value,\n ...maybe1559(gasSettings),\n };\n\n const swapStep: TransferStepDetails = {\n currentSignature: approvalRequest ? 2 : 1,\n currentSignatureReason: TransferSignatureReason.TokensTransfer,\n quote: syntheticQuote,\n requiredSignatures: approvalRequest ? 2 : 1,\n };\n\n const txHash = await evmSigner.sign(\n swapRequest,\n (signedTxHash) => sourceClient.sendRawTransaction({ serializedTransaction: signedTxHash }),\n swapStep,\n );\n\n return { txHash };\n}\n\n// ---------------------------------------------------------------------------\n// Order-action execution (cancel / pause / unpause — single-tx state change)\n// ---------------------------------------------------------------------------\n\ninterface ExecuteOrderActionImplParams extends RecurringExecuteOrderActionParams {\n action: 'cancel' | 'pause' | 'unpause';\n apiOptions: ApiOptions;\n evmSigner: EvmSigner;\n fetchCalldata: (\n apiOptions: ApiOptions,\n params: { orderId: `0x${string}`; address: `0x${string}`; chainId: number },\n ) => Promise<WrappedSwapTransactionResponse>;\n}\n\nasync function executeOrderActionImpl({\n action,\n address,\n apiOptions,\n evmSigner,\n fetchCalldata,\n gasSettings,\n orderId,\n sourceChain,\n}: ExecuteOrderActionImplParams): Promise<RecurringExecuteResult> {\n const sourceClient = getEvmClientForChain({ chain: sourceChain });\n const chainIdNumeric = caip2ToEip155ChainId(sourceChain.chainId);\n const chainIdHex = caip2ToEip155HexChainId(sourceChain.chainId);\n\n const calldata = await fetchCalldata(apiOptions, { orderId, address, chainId: chainIdNumeric });\n\n const gasEstimate = await estimateGasWithRevert(\n sourceClient,\n { account: address, to: calldata.to, data: calldata.data, value: calldata.value },\n erc20Abi,\n `Failed to estimate gas for recurring ${action} transaction.`,\n );\n\n const request: EvmTransactionRequest = {\n chainId: chainIdHex,\n data: calldata.data,\n from: address,\n gas: applyFeeUnitsBpsMargin(gasEstimate, gasSettings?.estimateGasMarginBps),\n to: calldata.to,\n value: calldata.value,\n ...maybe1559(gasSettings),\n };\n\n const step: TransferStepDetails = {\n currentSignature: 1,\n currentSignatureReason: TransferSignatureReason.TokensTransfer,\n quote: buildSyntheticQuoteForOrderAction({ address, action, orderId, sourceChain }),\n requiredSignatures: 1,\n };\n\n const txHash = await evmSigner.sign(\n request,\n (signedTxHash) => sourceClient.sendRawTransaction({ serializedTransaction: signedTxHash }),\n step,\n );\n\n return { txHash };\n}\n\n// ---------------------------------------------------------------------------\n// Internal: synthetic Quote objects for `TransferStepDetails.quote`\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a minimum-viable {@link Quote} for the signer step so consumer\n * `EvmSigner` impls can render meaningful wallet prompts for a recurring\n * action (which has no real `Quote` in the swap-quoter sense). The synthetic\n * value carries enough recurring context (uuid, chain, amounts, tokens) for\n * a wallet UI to label the popup; the `aggregator.id` (`'markr-recurring'`)\n * lets advanced signers detect the recurring path explicitly.\n *\n * Asset fields use placeholder `name`/`symbol`/`decimals` because the\n * recurring quote doesn't echo those — consumers needing rich asset display\n * should resolve token metadata against their own asset map keyed by\n * `quote.tokenIn`/`tokenOut`.\n */\nfunction buildSyntheticQuoteForFirstFill({\n fromAddress,\n quote,\n sourceChain,\n}: {\n fromAddress: `0x${string}`;\n quote: RecurringQuoteResponse;\n sourceChain: Chain;\n}): Quote {\n return {\n aggregator: { id: 'markr-recurring', name: 'Markr Recurring' },\n amountIn: quote.amount,\n amountOut: quote.amountOut,\n assetIn: { type: TokenType.ERC20, address: quote.tokenIn, name: '', symbol: '', decimals: 0 },\n assetOut: { type: TokenType.ERC20, address: quote.tokenOut, name: '', symbol: '', decimals: 0 },\n expiresAt: quote.expiredAt,\n fees: [],\n fromAddress,\n id: quote.uuid,\n partnerFeeBps: null,\n serviceType: ServiceType.MARKR,\n slippageBps: quote.recommendedSlippage,\n // Pass the caller-provided `Chain` straight through — recurring is always\n // same-chain, so source === target. Avoids stripping `chainName` /\n // `networkToken` / `rpcUrl` that consumer signers may use for display.\n sourceChain,\n targetChain: sourceChain,\n toAddress: fromAddress,\n };\n}\n\nfunction buildSyntheticQuoteForOrderAction({\n action,\n address,\n orderId,\n sourceChain,\n}: {\n action: 'cancel' | 'pause' | 'unpause';\n address: `0x${string}`;\n orderId: `0x${string}`;\n sourceChain: Chain;\n}): Quote {\n return {\n aggregator: { id: `markr-recurring-${action}`, name: `Markr Recurring (${action})` },\n amountIn: 0n,\n amountOut: 0n,\n assetIn: emptyNativeAsset(),\n assetOut: emptyNativeAsset(),\n expiresAt: 0,\n fees: [],\n fromAddress: address,\n id: orderId,\n partnerFeeBps: null,\n serviceType: ServiceType.MARKR,\n slippageBps: 0,\n // See `buildSyntheticQuoteForFirstFill` — pass the real `Chain` through.\n sourceChain,\n targetChain: sourceChain,\n toAddress: address,\n };\n}\n\nfunction emptyNativeAsset() {\n return { type: TokenType.NATIVE, name: '', symbol: '', decimals: 0 } as const;\n}\n"],"mappings":"2YA+CA,SAAgB,EAAyB,CACvC,aACA,QACA,YACA,sBACsD,CACtD,MAAO,CACL,MAAQ,GAAUA,EAAAA,oBAAoB,EAAY,CAAE,GAAG,EAAO,QAAO,CAAC,CAEtE,iBAAmB,GAAU,EAAqB,CAAE,GAAG,EAAO,aAAY,QAAO,YAAW,CAAC,CAE7F,WAAa,GAAUC,EAAAA,yBAAyB,EAAY,EAAM,CAElE,oBAAsB,GACpB,EAAuB,CACrB,GAAG,EACH,OAAQ,SACR,aACA,YACA,cAAeC,EAAAA,yBAChB,CAAC,CAEJ,aAAe,GACb,EAAuB,CACrB,GAAG,EACH,OAAQ,QACR,aACA,YACA,cAAeC,EAAAA,kBAChB,CAAC,CAEJ,eAAiB,GACf,EAAuB,CACrB,GAAG,EACH,OAAQ,UACR,aACA,YACA,cAAeC,EAAAA,oBAChB,CAAC,CAEJ,iBAAmB,GAAUC,EAAAA,0BAA0B,CAAE,GAAG,EAAO,qBAAoB,CAAC,CAExF,0BAA6B,EAC9B,CAaH,eAAe,EAAqB,CAClC,aACA,QACA,YACA,kCACA,cACA,cACA,QACA,eAC8D,CAI9D,IAAM,EAAM,KAAK,MAAM,KAAK,KAAK,CAAG,IAAM,CAC1C,GAAI,EAAM,WAAa,EAAK,CAC1B,IAAM,EAAoB,EAAM,EAAM,UACtC,MAAM,IAAIC,EAAAA,mBACRC,EAAAA,YAAY,cACZ,2BAA2B,EAAkB,eAC9C,CAMH,IAAM,EAAuBC,EAAAA,qBAAqB,EAAY,QAAQ,CACtE,GAAI,IAAyB,EAAM,QACjC,MAAM,IAAIF,EAAAA,mBACR,2CACA,uBAAuB,EAAY,QAAQ,eAAe,EAAqB,sBAAsB,EAAM,QAAQ,GACpH,CAGH,IAAM,EAAeG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M,GAAI,OAAQ,GAAI,SAAU,EAAG"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ServiceType as e,TokenType as t,TransferSignatureReason as n}from"../../../constants.js";import{ErrorCode as r,ErrorReason as i,InvalidParamsError as a,SdkError as o}from"../../../errors.js";import{caip2ToEip155ChainId as s,caip2ToEip155HexChainId as c}from"../../../utils/caip.js";import{applyFeeUnitsBpsMargin as l,getEvmClientForChain as u,maybe1559 as d}from"../../_utils.js";import{estimateGasWithRevert as f}from"../../_evm-errors.js";import{buildErc20ApprovalRequest as p,signApprovalAndAssertConfirmed as m}from"../../_evm-approval.js";import{markrGetSpenderAddress as h}from"../_api.js";import{getMarkrSwapWrapperAbi as g}from"../_utils.js";import{markrListRecurringOrders as _,markrPrepareCancellation as v,markrPreparePause as y,markrPrepareUnpause as b,markrRecurringQuote as x,markrRecurringSwap as S}from"./_api.js";import{checkRecurringEligibility as C}from"./_eligibility.js";import{erc20Abi as w}from"viem";function T({apiOptions:e,appId:t,evmSigner:n,recurringChainInfo:r}){return{quote:n=>x(e,{...n,appId:t}),executeFirstFill:r=>E({...r,apiOptions:e,appId:t,evmSigner:n}),listOrders:t=>_(e,t),executeCancellation:t=>D({...t,action:`cancel`,apiOptions:e,evmSigner:n,fetchCalldata:v}),executePause:t=>D({...t,action:`pause`,apiOptions:e,evmSigner:n,fetchCalldata:y}),executeUnpause:t=>D({...t,action:`unpause`,apiOptions:e,evmSigner:n,fetchCalldata:b}),checkEligibility:e=>C({...e,recurringChainInfo:r}),getRecurringChainInfo:()=>r}}async function E({apiOptions:e,appId:t,evmSigner:_,fallbackToDefaultOnBatchFailure:v,fromAddress:y,gasSettings:b,quote:x,sourceChain:C}){let w=Math.floor(Date.now()/1e3);if(x.expiredAt<=w){let e=w-x.expiredAt;throw new a(i.QUOTE_EXPIRED,`Recurring quote expired ${e} seconds ago.`)}let T=s(C.chainId);if(T!==x.chainId)throw new a(`sourceChain does not match quote.chainId`,`sourceChain.chainId=${C.chainId} resolves to ${T}, but quote.chainId=${x.chainId}.`);let E=u({chain:C}),D=c(C.chainId),{address:k}=await h(e,{chainId:x.chainId,crossChainSwap:!1,quoteId:x.uuid});if(!k)throw new o(i.CHAIN_NOT_SUPPORTED,r.INVALID_PARAMS,{details:`Missing Markr spender address for source chain ${C.chainId}.`});let A=await p({chainIdHex:D,client:E,gasSettings:b,owner:y,requiredAllowance:x.totalAmountIn,spender:k,token:x.tokenIn}),j=O({fromAddress:y,quote:x,sourceChain:C}),M=await S(e,{uuid:x.uuid,appId:t});if(A!==void 0&&typeof _.signBatch==`function`){let e={currentSignature:1,currentSignatureReason:n.TokensTransfer,quote:j,requiredSignatures:1},t={chainId:D,data:M.data,from:y,gas:void 0,to:M.to,value:M.value,...d(b)};try{let n=(await _.signBatch([A,t],e=>E.sendRawTransaction({serializedTransaction:e}),e)).at(-1);if(!n)throw new o(`One-click batch signing returned no transaction hashes.`,r.SIGNING_FAILED);return{txHash:n}}catch(e){if(!v)throw e}}A&&await m({client:E,evmSigner:_,request:A,step:{currentSignature:1,currentSignatureReason:n.AllowanceApproval,quote:j,requiredSignatures:2}});let N=await g(!1),P=await f(E,{account:y,to:M.to,data:M.data,value:M.value},N,`Failed to estimate gas for recurring first-fill swap transaction.`),F={chainId:D,data:M.data,from:y,gas:l(P,b?.estimateGasMarginBps),to:M.to,value:M.value,...d(b)},I={currentSignature:A?2:1,currentSignatureReason:n.TokensTransfer,quote:j,requiredSignatures:A?2:1};return{txHash:await _.sign(F,e=>E.sendRawTransaction({serializedTransaction:e}),I)}}async function D({action:e,address:t,apiOptions:r,evmSigner:i,fetchCalldata:a,gasSettings:o,orderId:p,sourceChain:m}){let h=u({chain:m}),g=s(m.chainId),_=c(m.chainId),v=await a(r,{orderId:p,address:t,chainId:g}),y=await f(h,{account:t,to:v.to,data:v.data,value:v.value},w,`Failed to estimate gas for recurring ${e} transaction.`),b={chainId:_,data:v.data,from:t,gas:l(y,o?.estimateGasMarginBps),to:v.to,value:v.value,...d(o)},x={currentSignature:1,currentSignatureReason:n.TokensTransfer,quote:k({address:t,action:e,orderId:p,sourceChain:m}),requiredSignatures:1};return{txHash:await i.sign(b,e=>h.sendRawTransaction({serializedTransaction:e}),x)}}function O({fromAddress:n,quote:r,sourceChain:i}){return{aggregator:{id:`markr-recurring`,name:`Markr Recurring`},amountIn:r.amount,amountOut:r.amountOut,assetIn:{type:t.ERC20,address:r.tokenIn,name:``,symbol:``,decimals:0},assetOut:{type:t.ERC20,address:r.tokenOut,name:``,symbol:``,decimals:0},expiresAt:r.expiredAt,fees:[],fromAddress:n,id:r.uuid,partnerFeeBps:null,serviceType:e.MARKR,slippageBps:r.recommendedSlippage,sourceChain:i,targetChain:i,toAddress:n}}function k({action:t,address:n,orderId:r,sourceChain:i}){return{aggregator:{id:`markr-recurring-${t}`,name:`Markr Recurring (${t})`},amountIn:0n,amountOut:0n,assetIn:A(),assetOut:A(),expiresAt:0,fees:[],fromAddress:n,id:r,partnerFeeBps:null,serviceType:e.MARKR,slippageBps:0,sourceChain:i,targetChain:i,toAddress:n}}function A(){return{type:t.NATIVE,name:``,symbol:``,decimals:0}}export{T as createRecurringNamespace};
|
|
2
|
+
//# sourceMappingURL=_namespace.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_namespace.js","names":[],"sources":["../../../../src/transfer-service/markr/recurring/_namespace.ts"],"sourcesContent":["import { erc20Abi } from 'viem';\nimport { ServiceType, TokenType, TransferSignatureReason } from '../../../constants';\nimport { ErrorCode, ErrorReason, InvalidParamsError, SdkError } from '../../../errors';\nimport type { Chain } from '../../../types/chain';\nimport type { Quote } from '../../../types/quote';\nimport type { EvmSigner, EvmTransactionRequest } from '../../../types/signer';\nimport type { TransferStepDetails } from '../../../types/transfer';\nimport { caip2ToEip155ChainId, caip2ToEip155HexChainId } from '../../../utils/caip';\nimport { applyFeeUnitsBpsMargin, getEvmClientForChain, maybe1559 } from '../../_utils';\nimport { buildErc20ApprovalRequest, signApprovalAndAssertConfirmed } from '../../_evm-approval';\nimport { estimateGasWithRevert } from '../../_evm-errors';\nimport type { WrappedSwapTransactionResponse } from '../_schema';\nimport { markrGetSpenderAddress, type ApiOptions } from '../_api';\nimport { getMarkrSwapWrapperAbi } from '../_utils';\nimport {\n markrListRecurringOrders,\n markrPrepareCancellation,\n markrPreparePause,\n markrPrepareUnpause,\n markrRecurringQuote,\n markrRecurringSwap,\n} from './_api';\nimport { checkRecurringEligibility } from './_eligibility';\nimport type {\n RecurringChainInfoMap,\n RecurringExecuteFirstFillParams,\n RecurringExecuteOrderActionParams,\n RecurringExecuteResult,\n RecurringNamespace,\n RecurringQuoteResponse,\n} from './types';\n\nexport interface CreateRecurringNamespaceOptions {\n apiOptions: ApiOptions;\n appId: string;\n evmSigner: EvmSigner;\n /**\n * The cached `/info/chains` recurring metadata. Captured by value at\n * namespace construction time — matches how `partnerFeeBps`,\n * `supportedChains`, and `supportedTokens` are also frozen at\n * `createMarkrService` init. If staleness ever becomes a real consumer\n * concern, the fix is a top-level `manager.refresh()` (not a per-namespace\n * lazy-read pattern).\n */\n recurringChainInfo: RecurringChainInfoMap;\n}\n\nexport function createRecurringNamespace({\n apiOptions,\n appId,\n evmSigner,\n recurringChainInfo,\n}: CreateRecurringNamespaceOptions): RecurringNamespace {\n return {\n quote: (props) => markrRecurringQuote(apiOptions, { ...props, appId }),\n\n executeFirstFill: (props) => executeFirstFillImpl({ ...props, apiOptions, appId, evmSigner }),\n\n listOrders: (props) => markrListRecurringOrders(apiOptions, props),\n\n executeCancellation: (props) =>\n executeOrderActionImpl({\n ...props,\n action: 'cancel',\n apiOptions,\n evmSigner,\n fetchCalldata: markrPrepareCancellation,\n }),\n\n executePause: (props) =>\n executeOrderActionImpl({\n ...props,\n action: 'pause',\n apiOptions,\n evmSigner,\n fetchCalldata: markrPreparePause,\n }),\n\n executeUnpause: (props) =>\n executeOrderActionImpl({\n ...props,\n action: 'unpause',\n apiOptions,\n evmSigner,\n fetchCalldata: markrPrepareUnpause,\n }),\n\n checkEligibility: (props) => checkRecurringEligibility({ ...props, recurringChainInfo }),\n\n getRecurringChainInfo: () => recurringChainInfo,\n };\n}\n\n// ---------------------------------------------------------------------------\n// First-fill execution (allowance check + approve-if-needed + first-fill swap)\n// ---------------------------------------------------------------------------\n\ninterface ExecuteFirstFillImplParams extends RecurringExecuteFirstFillParams {\n apiOptions: ApiOptions;\n appId: string;\n evmSigner: EvmSigner;\n}\n\nasync function executeFirstFillImpl({\n apiOptions,\n appId,\n evmSigner,\n fallbackToDefaultOnBatchFailure,\n fromAddress,\n gasSettings,\n quote,\n sourceChain,\n}: ExecuteFirstFillImplParams): Promise<RecurringExecuteResult> {\n // Mirror the one-shot guard at `TransferManager.estimateNativeFee` — fail at\n // the SDK boundary with `QUOTE_EXPIRED` instead of an opaque `HttpError`\n // from `/recurring/swap` for a slow-to-approve user.\n const now = Math.floor(Date.now() / 1_000);\n if (quote.expiredAt <= now) {\n const expiredSecondsAgo = now - quote.expiredAt;\n throw new InvalidParamsError(\n ErrorReason.QUOTE_EXPIRED,\n `Recurring quote expired ${expiredSecondsAgo} seconds ago.`,\n );\n }\n\n // Wiring-mistake guard: the passed `sourceChain.chainId` (CAIP-2) must agree\n // with the `chainId` (numeric) the quote was issued against. Otherwise the\n // allowance / gas reads hit the wrong chain.\n const sourceChainIdNumeric = caip2ToEip155ChainId(sourceChain.chainId);\n if (sourceChainIdNumeric !== quote.chainId) {\n throw new InvalidParamsError(\n 'sourceChain does not match quote.chainId',\n `sourceChain.chainId=${sourceChain.chainId} resolves to ${sourceChainIdNumeric}, but quote.chainId=${quote.chainId}.`,\n );\n }\n\n const sourceClient = getEvmClientForChain({ chain: sourceChain });\n const chainIdHex = caip2ToEip155HexChainId(sourceChain.chainId);\n\n const { address: spenderAddress } = await markrGetSpenderAddress(apiOptions, {\n chainId: quote.chainId,\n crossChainSwap: false,\n quoteId: quote.uuid,\n });\n\n if (!spenderAddress) {\n throw new SdkError(ErrorReason.CHAIN_NOT_SUPPORTED, ErrorCode.INVALID_PARAMS, {\n details: `Missing Markr spender address for source chain ${sourceChain.chainId}.`,\n });\n }\n\n const approvalRequest = await buildErc20ApprovalRequest({\n chainIdHex,\n client: sourceClient,\n gasSettings,\n owner: fromAddress,\n requiredAllowance: quote.totalAmountIn,\n spender: spenderAddress,\n token: quote.tokenIn,\n });\n\n const syntheticQuote = buildSyntheticQuoteForFirstFill({ fromAddress, quote, sourceChain });\n\n const swap = await markrRecurringSwap(apiOptions, { uuid: quote.uuid, appId });\n\n // One-click batch path: same-chain DCA, approval required, signer exposes\n // `signBatch`. Matches `_executeEvmTransfer`'s eligibility check (recurring\n // is always same-chain so the cross-chain check there collapses to true).\n if (approvalRequest !== undefined && typeof evmSigner.signBatch === 'function') {\n const batchStep: TransferStepDetails = {\n currentSignature: 1,\n currentSignatureReason: TransferSignatureReason.TokensTransfer,\n quote: syntheticQuote,\n requiredSignatures: 1,\n };\n\n // Gas is left undefined on the swap leg — the wallet handles batched gas\n // estimation since the approval hasn't executed yet.\n const swapRequest: EvmTransactionRequest = {\n chainId: chainIdHex,\n data: swap.data,\n from: fromAddress,\n gas: undefined,\n to: swap.to,\n value: swap.value,\n ...maybe1559(gasSettings),\n };\n\n try {\n const txHashes = await evmSigner.signBatch(\n [approvalRequest, swapRequest],\n (signedTxHash) => sourceClient.sendRawTransaction({ serializedTransaction: signedTxHash }),\n batchStep,\n );\n const swapTxHash = txHashes.at(-1);\n if (!swapTxHash) {\n throw new SdkError('One-click batch signing returned no transaction hashes.', ErrorCode.SIGNING_FAILED);\n }\n return { txHash: swapTxHash };\n } catch (error) {\n if (!fallbackToDefaultOnBatchFailure) {\n throw error;\n }\n // Fall through to the two-signature path below.\n }\n }\n\n if (approvalRequest) {\n await signApprovalAndAssertConfirmed({\n client: sourceClient,\n evmSigner,\n request: approvalRequest,\n step: {\n currentSignature: 1,\n currentSignatureReason: TransferSignatureReason.AllowanceApproval,\n quote: syntheticQuote,\n requiredSignatures: 2,\n },\n });\n }\n\n // Use the Markr same-chain swap wrapper ABI for best-effort revert decoding\n // — matches `_estimateGasFromSwapResponse` in `estimate-native-fee.ts`.\n // Recurring is always same-chain, so `crossChain: false`. Built-in\n // `Error(string)` / `Panic(uint256)` are decoded regardless of ABI.\n const markrAbi = await getMarkrSwapWrapperAbi(false);\n const swapGasEstimate = await estimateGasWithRevert(\n sourceClient,\n { account: fromAddress, to: swap.to, data: swap.data, value: swap.value },\n markrAbi,\n 'Failed to estimate gas for recurring first-fill swap transaction.',\n );\n\n const swapRequest: EvmTransactionRequest = {\n chainId: chainIdHex,\n data: swap.data,\n from: fromAddress,\n gas: applyFeeUnitsBpsMargin(swapGasEstimate, gasSettings?.estimateGasMarginBps),\n to: swap.to,\n value: swap.value,\n ...maybe1559(gasSettings),\n };\n\n const swapStep: TransferStepDetails = {\n currentSignature: approvalRequest ? 2 : 1,\n currentSignatureReason: TransferSignatureReason.TokensTransfer,\n quote: syntheticQuote,\n requiredSignatures: approvalRequest ? 2 : 1,\n };\n\n const txHash = await evmSigner.sign(\n swapRequest,\n (signedTxHash) => sourceClient.sendRawTransaction({ serializedTransaction: signedTxHash }),\n swapStep,\n );\n\n return { txHash };\n}\n\n// ---------------------------------------------------------------------------\n// Order-action execution (cancel / pause / unpause — single-tx state change)\n// ---------------------------------------------------------------------------\n\ninterface ExecuteOrderActionImplParams extends RecurringExecuteOrderActionParams {\n action: 'cancel' | 'pause' | 'unpause';\n apiOptions: ApiOptions;\n evmSigner: EvmSigner;\n fetchCalldata: (\n apiOptions: ApiOptions,\n params: { orderId: `0x${string}`; address: `0x${string}`; chainId: number },\n ) => Promise<WrappedSwapTransactionResponse>;\n}\n\nasync function executeOrderActionImpl({\n action,\n address,\n apiOptions,\n evmSigner,\n fetchCalldata,\n gasSettings,\n orderId,\n sourceChain,\n}: ExecuteOrderActionImplParams): Promise<RecurringExecuteResult> {\n const sourceClient = getEvmClientForChain({ chain: sourceChain });\n const chainIdNumeric = caip2ToEip155ChainId(sourceChain.chainId);\n const chainIdHex = caip2ToEip155HexChainId(sourceChain.chainId);\n\n const calldata = await fetchCalldata(apiOptions, { orderId, address, chainId: chainIdNumeric });\n\n const gasEstimate = await estimateGasWithRevert(\n sourceClient,\n { account: address, to: calldata.to, data: calldata.data, value: calldata.value },\n erc20Abi,\n `Failed to estimate gas for recurring ${action} transaction.`,\n );\n\n const request: EvmTransactionRequest = {\n chainId: chainIdHex,\n data: calldata.data,\n from: address,\n gas: applyFeeUnitsBpsMargin(gasEstimate, gasSettings?.estimateGasMarginBps),\n to: calldata.to,\n value: calldata.value,\n ...maybe1559(gasSettings),\n };\n\n const step: TransferStepDetails = {\n currentSignature: 1,\n currentSignatureReason: TransferSignatureReason.TokensTransfer,\n quote: buildSyntheticQuoteForOrderAction({ address, action, orderId, sourceChain }),\n requiredSignatures: 1,\n };\n\n const txHash = await evmSigner.sign(\n request,\n (signedTxHash) => sourceClient.sendRawTransaction({ serializedTransaction: signedTxHash }),\n step,\n );\n\n return { txHash };\n}\n\n// ---------------------------------------------------------------------------\n// Internal: synthetic Quote objects for `TransferStepDetails.quote`\n// ---------------------------------------------------------------------------\n\n/**\n * Builds a minimum-viable {@link Quote} for the signer step so consumer\n * `EvmSigner` impls can render meaningful wallet prompts for a recurring\n * action (which has no real `Quote` in the swap-quoter sense). The synthetic\n * value carries enough recurring context (uuid, chain, amounts, tokens) for\n * a wallet UI to label the popup; the `aggregator.id` (`'markr-recurring'`)\n * lets advanced signers detect the recurring path explicitly.\n *\n * Asset fields use placeholder `name`/`symbol`/`decimals` because the\n * recurring quote doesn't echo those — consumers needing rich asset display\n * should resolve token metadata against their own asset map keyed by\n * `quote.tokenIn`/`tokenOut`.\n */\nfunction buildSyntheticQuoteForFirstFill({\n fromAddress,\n quote,\n sourceChain,\n}: {\n fromAddress: `0x${string}`;\n quote: RecurringQuoteResponse;\n sourceChain: Chain;\n}): Quote {\n return {\n aggregator: { id: 'markr-recurring', name: 'Markr Recurring' },\n amountIn: quote.amount,\n amountOut: quote.amountOut,\n assetIn: { type: TokenType.ERC20, address: quote.tokenIn, name: '', symbol: '', decimals: 0 },\n assetOut: { type: TokenType.ERC20, address: quote.tokenOut, name: '', symbol: '', decimals: 0 },\n expiresAt: quote.expiredAt,\n fees: [],\n fromAddress,\n id: quote.uuid,\n partnerFeeBps: null,\n serviceType: ServiceType.MARKR,\n slippageBps: quote.recommendedSlippage,\n // Pass the caller-provided `Chain` straight through — recurring is always\n // same-chain, so source === target. Avoids stripping `chainName` /\n // `networkToken` / `rpcUrl` that consumer signers may use for display.\n sourceChain,\n targetChain: sourceChain,\n toAddress: fromAddress,\n };\n}\n\nfunction buildSyntheticQuoteForOrderAction({\n action,\n address,\n orderId,\n sourceChain,\n}: {\n action: 'cancel' | 'pause' | 'unpause';\n address: `0x${string}`;\n orderId: `0x${string}`;\n sourceChain: Chain;\n}): Quote {\n return {\n aggregator: { id: `markr-recurring-${action}`, name: `Markr Recurring (${action})` },\n amountIn: 0n,\n amountOut: 0n,\n assetIn: emptyNativeAsset(),\n assetOut: emptyNativeAsset(),\n expiresAt: 0,\n fees: [],\n fromAddress: address,\n id: orderId,\n partnerFeeBps: null,\n serviceType: ServiceType.MARKR,\n slippageBps: 0,\n // See `buildSyntheticQuoteForFirstFill` — pass the real `Chain` through.\n sourceChain,\n targetChain: sourceChain,\n toAddress: address,\n };\n}\n\nfunction emptyNativeAsset() {\n return { type: TokenType.NATIVE, name: '', symbol: '', decimals: 0 } as const;\n}\n"],"mappings":"m6BA+CA,SAAgB,EAAyB,CACvC,aACA,QACA,YACA,sBACsD,CACtD,MAAO,CACL,MAAQ,GAAU,EAAoB,EAAY,CAAE,GAAG,EAAO,QAAO,CAAC,CAEtE,iBAAmB,GAAU,EAAqB,CAAE,GAAG,EAAO,aAAY,QAAO,YAAW,CAAC,CAE7F,WAAa,GAAU,EAAyB,EAAY,EAAM,CAElE,oBAAsB,GACpB,EAAuB,CACrB,GAAG,EACH,OAAQ,SACR,aACA,YACA,cAAe,EAChB,CAAC,C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,CAGH,SAAS,EAAkC,CACzC,SACA,UACA,UACA,eAMQ,CACR,MAAO,CACL,WAAY,CAAE,GAAI,mBAAmB,IAAU,KAAM,oBAAoB,EAAO,GAAI,CACpF,SAAU,GACV,UAAW,GACX,QAAS,GAAkB,CAC3B,SAAU,GAAkB,CAC5B,UAAW,EACX,KAAM,EAAE,CACR,YAAa,EACb,GAAI,EACJ,cAAe,KACf,YAAa,EAAY,MACzB,YAAa,EAEb,cACA,YAAa,EACb,UAAW,EACZ,CAGH,SAAS,GAAmB,CAC1B,MAAO,CAAE,KAAM,EAAU,OAAQ,KAAM,GAAI,OAAQ,GAAI,SAAU,EAAG"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
require(`../../../_virtual/_rolldown/runtime.cjs`);const e=require(`./types.cjs`),t=require(`../../service-schemas.cjs`);let n=require(`zod`);const r=/^0x[0-9a-fA-F]{64}$/,i=n.z.enum(e.RECURRING_FREQUENCY_UNITS),a=n.z.object({unit:i,value:n.z.number().int().min(1)}),o=n.z.enum(Object.values(e.RecurringOrderStatus)),s=n.z.object({executionIndex:n.z.number().int().nonnegative(),reasons:n.z.array(n.z.string()),tryCount:n.z.number().int().nonnegative(),failedAt:n.z.number().int().nonnegative()}),c=n.z.string().regex(r,`Invalid recurring order id (expected 0x-prefixed bytes32)`).transform(e=>e),l=n.z.object({orderId:c,owner:t.EvmAddressSchema,chainId:n.z.coerce.number().int().nonnegative(),tokenIn:t.EvmAddressSchema,tokenOut:t.EvmAddressSchema,amount:n.z.coerce.bigint().nonnegative(),numberOfOrders:n.z.number().int(),executedOrders:n.z.number().int().nonnegative(),remainingOrders:n.z.number().int().nonnegative().nullish().transform(e=>e??null),frequency:a,totalAmountIn:n.z.coerce.bigint().nonnegative(),tryCount:n.z.number().int().nonnegative(),failures:n.z.array(s),status:o,createdAt:n.z.number().int().nonnegative(),nextExecutionAt:n.z.number().int().nonnegative().nullish().transform(e=>e??null),cancelledAt:n.z.number().int().nonnegative().nullish().transform(e=>e??null)}),u=n.z.object({type:n.z.enum([`gas`,`recurring`,`protocol`,`bridge`,`slippage`,`swap`,`other`]).or(n.z.string()),name:n.z.string(),amount:n.z.coerce.bigint().nonnegative(),token:n.z.object({chainId:n.z.coerce.number().int().nonnegative(),address:t.EvmAddressSchema}),extra:n.z.union([n.z.boolean(),n.z.record(n.z.string(),n.z.unknown())]).optional()}),d=n.z.object({uuid:n.z.uuid(),chainId:n.z.coerce.number().int().nonnegative(),tokenIn:t.EvmAddressSchema,tokenOut:t.EvmAddressSchema,amount:n.z.coerce.bigint().nonnegative(),numberOfOrders:n.z.number().int(),frequency:a,intervalSeconds:n.z.number().int().nonnegative(),totalAmountIn:n.z.coerce.bigint().nonnegative(),amountOut:n.z.coerce.bigint().nonnegative(),minAmountOut:n.z.coerce.bigint().nonnegative(),fees:n.z.array(u),recommendedSlippage:n.z.number().int().nonnegative(),expiredAt:n.z.number().int().nonnegative()}),f=n.z.object({address:t.EvmAddressSchema,count:n.z.number().int().nonnegative(),orders:n.z.array(l)});exports.ListRecurringOrdersResponseSchema=f,exports.RecurringQuoteResponseSchema=d;
|
|
2
|
+
//# sourceMappingURL=_schema.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_schema.cjs","names":["z","RECURRING_FREQUENCY_UNITS","RecurringOrderStatus","EvmAddressSchema"],"sources":["../../../../src/transfer-service/markr/recurring/_schema.ts"],"sourcesContent":["import { z } from 'zod';\nimport { EvmAddressSchema } from '../../service-schemas';\nimport {\n RECURRING_FREQUENCY_UNITS,\n RecurringOrderStatus,\n type ListRecurringOrdersResponse,\n type RecurringFrequency,\n type RecurringFrequencyUnit,\n type RecurringOrder,\n type RecurringOrderFailure,\n type RecurringQuoteResponse,\n} from './types';\n\nconst ORDER_ID_REGEX = /^0x[0-9a-fA-F]{64}$/;\n\nexport const RecurringFrequencyUnitSchema: z.ZodType<RecurringFrequencyUnit> = z.enum(RECURRING_FREQUENCY_UNITS);\n\nexport const RecurringFrequencySchema: z.ZodType<RecurringFrequency> = z.object({\n unit: RecurringFrequencyUnitSchema,\n value: z.number().int().min(1),\n});\n\n/**\n * Closed enum — see {@link RecurringOrderStatus}. Unknown server-side values\n * (e.g. a hypothetical `'expired'`) will fail parsing loudly, which gates\n * UI behavior on an SDK update rather than silently surfacing an unhandled\n * status to the consumer.\n */\nexport const RecurringOrderStatusSchema: z.ZodType<RecurringOrderStatus> = z.enum(\n Object.values(RecurringOrderStatus) as [RecurringOrderStatus, ...RecurringOrderStatus[]],\n);\n\nexport const RecurringOrderFailureSchema: z.ZodType<RecurringOrderFailure> = z.object({\n // `nonnegative` (not `positive`) — Markr documents `executionIndex` as\n // 1-based today, but forward-compat with a future setup-time failure\n // emitting index `0` costs nothing and matches the same brittleness fix\n // applied to the status / fee-type enums.\n executionIndex: z.number().int().nonnegative(),\n reasons: z.array(z.string()),\n tryCount: z.number().int().nonnegative(),\n failedAt: z.number().int().nonnegative(),\n});\n\n/**\n * `0x`-prefixed bytes32 hex. Use `.transform()` to widen `string` into the\n * template-literal type that `RecurringOrder.orderId` declares — mirrors the\n * `EvmAddressSchema` pattern from `service-schemas.ts`.\n */\nconst OrderIdSchema: z.ZodType<`0x${string}`> = z\n .string()\n .regex(ORDER_ID_REGEX, 'Invalid recurring order id (expected 0x-prefixed bytes32)')\n .transform((value) => value as `0x${string}`);\n\n/**\n * Schema for a single `RecurringOrder` element as returned by Markr's\n * `/recurring/orders` (list) and `/recurring/orders/{orderId}/cancel`\n * endpoints.\n */\nexport const RecurringOrderSchema: z.ZodType<RecurringOrder> = z.object({\n orderId: OrderIdSchema,\n owner: EvmAddressSchema,\n chainId: z.coerce.number().int().nonnegative(),\n tokenIn: EvmAddressSchema,\n tokenOut: EvmAddressSchema,\n amount: z.coerce.bigint().nonnegative(),\n numberOfOrders: z.number().int(),\n executedOrders: z.number().int().nonnegative(),\n // `null` (or omitted) on unlimited schedules per the Markr OpenAPI spec —\n // `numberOfOrders: -1` schedules have no finite remainder to report. Finite\n // schedules carry `numberOfOrders - executedOrders` as a non-negative int.\n // `.nullish()` accepts both `null` and `undefined`; we normalize to `null`\n // by coercing `undefined` via a default transform so consumers can use a\n // simple `if (order.remainingOrders === null)` check instead of also\n // guarding for `undefined`.\n remainingOrders: z\n .number()\n .int()\n .nonnegative()\n .nullish()\n .transform((value) => value ?? null),\n frequency: RecurringFrequencySchema,\n totalAmountIn: z.coerce.bigint().nonnegative(),\n tryCount: z.number().int().nonnegative(),\n failures: z.array(RecurringOrderFailureSchema),\n status: RecurringOrderStatusSchema,\n createdAt: z.number().int().nonnegative(),\n // OpenAPI marks `nextExecutionAt` as optional + nullable — accept all\n // three wire shapes (number / null / omitted) and normalize to\n // `number | null` so consumers can use a single `=== null` check.\n // Same pattern as `remainingOrders` above.\n nextExecutionAt: z\n .number()\n .int()\n .nonnegative()\n .nullish()\n .transform((value) => value ?? null),\n // OpenAPI marks `cancelledAt` as optional + nullable; populated only when\n // `status === 'cancelled'`. Normalize to `number | null` (always present\n // in the parsed shape) for the same consumer-ergonomics reason as\n // `nextExecutionAt` / `remainingOrders`.\n cancelledAt: z\n .number()\n .int()\n .nonnegative()\n .nullish()\n .transform((value) => value ?? null),\n});\n\nconst RecurringQuoteFeeSchema = z.object({\n // Tolerant of unknown fee categories (forward-compat). Unlike\n // `RecurringOrderStatusSchema` (closed enum — see comment there), a new\n // fee category from Markr is safe to render as \"Other fee\" instead of\n // bricking parsing on already-shipped clients.\n type: z.enum(['gas', 'recurring', 'protocol', 'bridge', 'slippage', 'swap', 'other']).or(z.string()),\n name: z.string(),\n amount: z.coerce.bigint().nonnegative(),\n token: z.object({\n chainId: z.coerce.number().int().nonnegative(),\n address: EvmAddressSchema,\n }),\n // Docs: `extra: boolean or object` — accept both. See the equivalent\n // widening on the one-shot quote schema in `markr/_schema.ts`.\n extra: z.union([z.boolean(), z.record(z.string(), z.unknown())]).optional(),\n});\n\n/**\n * Schema for the response from Markr's `/recurring/quote` endpoint.\n */\nexport const RecurringQuoteResponseSchema: z.ZodType<RecurringQuoteResponse> = z.object({\n uuid: z.uuid(),\n chainId: z.coerce.number().int().nonnegative(),\n tokenIn: EvmAddressSchema,\n tokenOut: EvmAddressSchema,\n amount: z.coerce.bigint().nonnegative(),\n numberOfOrders: z.number().int(),\n frequency: RecurringFrequencySchema,\n intervalSeconds: z.number().int().nonnegative(),\n totalAmountIn: z.coerce.bigint().nonnegative(),\n amountOut: z.coerce.bigint().nonnegative(),\n minAmountOut: z.coerce.bigint().nonnegative(),\n fees: z.array(RecurringQuoteFeeSchema),\n recommendedSlippage: z.number().int().nonnegative(),\n expiredAt: z.number().int().nonnegative(),\n});\n\n/**\n * Schema for the response from Markr's `/recurring/orders` (list) endpoint.\n */\nexport const ListRecurringOrdersResponseSchema: z.ZodType<ListRecurringOrdersResponse> = z.object({\n address: EvmAddressSchema,\n count: z.number().int().nonnegative(),\n orders: z.array(RecurringOrderSchema),\n});\n"],"mappings":"8IAaA,MAAM,EAAiB,sBAEV,EAAkEA,EAAAA,EAAE,KAAKC,EAAAA,0BAA0B,CAEnG,EAA0DD,EAAAA,EAAE,OAAO,CAC9E,KAAM,EACN,MAAOA,EAAAA,EAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,CAC/B,CAAC,CAQW,EAA8DA,EAAAA,EAAE,KAC3E,OAAO,OAAOE,EAAAA,qBAAqB,CACpC,CAEY,EAAgEF,EAAAA,EAAE,OAAO,CAKpF,eAAgBA,EAAAA,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CAC9C,QAASA,EAAAA,EAAE,MAAMA,EAAAA,EAAE,QAAQ,CAAC,CAC5B,SAAUA,EAAAA,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CACxC,SAAUA,EAAAA,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CACzC,CAAC,CAOI,EAA0CA,EAAAA,EAC7C,QAAQ,CACR,MAAM,EAAgB,4DAA4D,CAClF,UAAW,GAAU,EAAuB,CAOlC,EAAkD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AAOH,EAAAA,EAAE,MAAM,CAACA,EAAAA,EAAE,SAAS,CAAEA,EAAAA,EAAE,OAAOA,EAAAA,EAAE,QAAQ,CAAEA,EAAAA,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,UAAU,CAC5E,CAAC,CAKW,EAAkEA,EAAAA,EAAE,OAAO,CACtF,KAAMA,EAAAA,EAAE,MAAM,CACd,QAASA,EAAAA,EAAE,OAAO,QAAQ,CAAC,KAAK,CAAC,aAAa,CAC9C,QAASG,EAAAA,iBACT,SAAUA,EAAAA,iBACV,OAAQH,EAAAA,EAAE,OAAO,QAAQ,CAAC,aAAa,CACvC,eAAgBA,EAAAA,EAAE,QAAQ,CAAC,KAAK,CAChC,UAAW,EACX,gBAAiBA,EAAAA,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CAC/C,cAAeA,EAAAA,EAAE,OAAO,QAAQ,CAAC,aAAa,CAC9C,UAAWA,EAAAA,EAAE,OAAO,QAAQ,CAAC,aAAa,CAC1C,aAAcA,EAAAA,EAAE,OAAO,QAAQ,CAAC,aAAa,CAC7C,KAAMA,EAAAA,EAAE,MAAM,EAAwB,CACtC,oBAAqBA,EAAAA,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CACnD,UAAWA,EAAAA,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CAC1C,CAAC,CAKW,EAA4EA,EAAAA,EAAE,OAAO,CAChG,QAASG,EAAAA,iBACT,MAAOH,EAAAA,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CACrC,OAAQA,EAAAA,EAAE,MAAM,EAAqB,CACtC,CAAC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{RECURRING_FREQUENCY_UNITS as e,RecurringOrderStatus as t}from"./types.js";import{EvmAddressSchema as n}from"../../service-schemas.js";import{z as r}from"zod";const i=/^0x[0-9a-fA-F]{64}$/,a=r.enum(e),o=r.object({unit:a,value:r.number().int().min(1)}),s=r.enum(Object.values(t)),c=r.object({executionIndex:r.number().int().nonnegative(),reasons:r.array(r.string()),tryCount:r.number().int().nonnegative(),failedAt:r.number().int().nonnegative()}),l=r.string().regex(i,`Invalid recurring order id (expected 0x-prefixed bytes32)`).transform(e=>e),u=r.object({orderId:l,owner:n,chainId:r.coerce.number().int().nonnegative(),tokenIn:n,tokenOut:n,amount:r.coerce.bigint().nonnegative(),numberOfOrders:r.number().int(),executedOrders:r.number().int().nonnegative(),remainingOrders:r.number().int().nonnegative().nullish().transform(e=>e??null),frequency:o,totalAmountIn:r.coerce.bigint().nonnegative(),tryCount:r.number().int().nonnegative(),failures:r.array(c),status:s,createdAt:r.number().int().nonnegative(),nextExecutionAt:r.number().int().nonnegative().nullish().transform(e=>e??null),cancelledAt:r.number().int().nonnegative().nullish().transform(e=>e??null)}),d=r.object({type:r.enum([`gas`,`recurring`,`protocol`,`bridge`,`slippage`,`swap`,`other`]).or(r.string()),name:r.string(),amount:r.coerce.bigint().nonnegative(),token:r.object({chainId:r.coerce.number().int().nonnegative(),address:n}),extra:r.union([r.boolean(),r.record(r.string(),r.unknown())]).optional()}),f=r.object({uuid:r.uuid(),chainId:r.coerce.number().int().nonnegative(),tokenIn:n,tokenOut:n,amount:r.coerce.bigint().nonnegative(),numberOfOrders:r.number().int(),frequency:o,intervalSeconds:r.number().int().nonnegative(),totalAmountIn:r.coerce.bigint().nonnegative(),amountOut:r.coerce.bigint().nonnegative(),minAmountOut:r.coerce.bigint().nonnegative(),fees:r.array(d),recommendedSlippage:r.number().int().nonnegative(),expiredAt:r.number().int().nonnegative()}),p=r.object({address:n,count:r.number().int().nonnegative(),orders:r.array(u)});export{p as ListRecurringOrdersResponseSchema,f as RecurringQuoteResponseSchema};
|
|
2
|
+
//# sourceMappingURL=_schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_schema.js","names":[],"sources":["../../../../src/transfer-service/markr/recurring/_schema.ts"],"sourcesContent":["import { z } from 'zod';\nimport { EvmAddressSchema } from '../../service-schemas';\nimport {\n RECURRING_FREQUENCY_UNITS,\n RecurringOrderStatus,\n type ListRecurringOrdersResponse,\n type RecurringFrequency,\n type RecurringFrequencyUnit,\n type RecurringOrder,\n type RecurringOrderFailure,\n type RecurringQuoteResponse,\n} from './types';\n\nconst ORDER_ID_REGEX = /^0x[0-9a-fA-F]{64}$/;\n\nexport const RecurringFrequencyUnitSchema: z.ZodType<RecurringFrequencyUnit> = z.enum(RECURRING_FREQUENCY_UNITS);\n\nexport const RecurringFrequencySchema: z.ZodType<RecurringFrequency> = z.object({\n unit: RecurringFrequencyUnitSchema,\n value: z.number().int().min(1),\n});\n\n/**\n * Closed enum — see {@link RecurringOrderStatus}. Unknown server-side values\n * (e.g. a hypothetical `'expired'`) will fail parsing loudly, which gates\n * UI behavior on an SDK update rather than silently surfacing an unhandled\n * status to the consumer.\n */\nexport const RecurringOrderStatusSchema: z.ZodType<RecurringOrderStatus> = z.enum(\n Object.values(RecurringOrderStatus) as [RecurringOrderStatus, ...RecurringOrderStatus[]],\n);\n\nexport const RecurringOrderFailureSchema: z.ZodType<RecurringOrderFailure> = z.object({\n // `nonnegative` (not `positive`) — Markr documents `executionIndex` as\n // 1-based today, but forward-compat with a future setup-time failure\n // emitting index `0` costs nothing and matches the same brittleness fix\n // applied to the status / fee-type enums.\n executionIndex: z.number().int().nonnegative(),\n reasons: z.array(z.string()),\n tryCount: z.number().int().nonnegative(),\n failedAt: z.number().int().nonnegative(),\n});\n\n/**\n * `0x`-prefixed bytes32 hex. Use `.transform()` to widen `string` into the\n * template-literal type that `RecurringOrder.orderId` declares — mirrors the\n * `EvmAddressSchema` pattern from `service-schemas.ts`.\n */\nconst OrderIdSchema: z.ZodType<`0x${string}`> = z\n .string()\n .regex(ORDER_ID_REGEX, 'Invalid recurring order id (expected 0x-prefixed bytes32)')\n .transform((value) => value as `0x${string}`);\n\n/**\n * Schema for a single `RecurringOrder` element as returned by Markr's\n * `/recurring/orders` (list) and `/recurring/orders/{orderId}/cancel`\n * endpoints.\n */\nexport const RecurringOrderSchema: z.ZodType<RecurringOrder> = z.object({\n orderId: OrderIdSchema,\n owner: EvmAddressSchema,\n chainId: z.coerce.number().int().nonnegative(),\n tokenIn: EvmAddressSchema,\n tokenOut: EvmAddressSchema,\n amount: z.coerce.bigint().nonnegative(),\n numberOfOrders: z.number().int(),\n executedOrders: z.number().int().nonnegative(),\n // `null` (or omitted) on unlimited schedules per the Markr OpenAPI spec —\n // `numberOfOrders: -1` schedules have no finite remainder to report. Finite\n // schedules carry `numberOfOrders - executedOrders` as a non-negative int.\n // `.nullish()` accepts both `null` and `undefined`; we normalize to `null`\n // by coercing `undefined` via a default transform so consumers can use a\n // simple `if (order.remainingOrders === null)` check instead of also\n // guarding for `undefined`.\n remainingOrders: z\n .number()\n .int()\n .nonnegative()\n .nullish()\n .transform((value) => value ?? null),\n frequency: RecurringFrequencySchema,\n totalAmountIn: z.coerce.bigint().nonnegative(),\n tryCount: z.number().int().nonnegative(),\n failures: z.array(RecurringOrderFailureSchema),\n status: RecurringOrderStatusSchema,\n createdAt: z.number().int().nonnegative(),\n // OpenAPI marks `nextExecutionAt` as optional + nullable — accept all\n // three wire shapes (number / null / omitted) and normalize to\n // `number | null` so consumers can use a single `=== null` check.\n // Same pattern as `remainingOrders` above.\n nextExecutionAt: z\n .number()\n .int()\n .nonnegative()\n .nullish()\n .transform((value) => value ?? null),\n // OpenAPI marks `cancelledAt` as optional + nullable; populated only when\n // `status === 'cancelled'`. Normalize to `number | null` (always present\n // in the parsed shape) for the same consumer-ergonomics reason as\n // `nextExecutionAt` / `remainingOrders`.\n cancelledAt: z\n .number()\n .int()\n .nonnegative()\n .nullish()\n .transform((value) => value ?? null),\n});\n\nconst RecurringQuoteFeeSchema = z.object({\n // Tolerant of unknown fee categories (forward-compat). Unlike\n // `RecurringOrderStatusSchema` (closed enum — see comment there), a new\n // fee category from Markr is safe to render as \"Other fee\" instead of\n // bricking parsing on already-shipped clients.\n type: z.enum(['gas', 'recurring', 'protocol', 'bridge', 'slippage', 'swap', 'other']).or(z.string()),\n name: z.string(),\n amount: z.coerce.bigint().nonnegative(),\n token: z.object({\n chainId: z.coerce.number().int().nonnegative(),\n address: EvmAddressSchema,\n }),\n // Docs: `extra: boolean or object` — accept both. See the equivalent\n // widening on the one-shot quote schema in `markr/_schema.ts`.\n extra: z.union([z.boolean(), z.record(z.string(), z.unknown())]).optional(),\n});\n\n/**\n * Schema for the response from Markr's `/recurring/quote` endpoint.\n */\nexport const RecurringQuoteResponseSchema: z.ZodType<RecurringQuoteResponse> = z.object({\n uuid: z.uuid(),\n chainId: z.coerce.number().int().nonnegative(),\n tokenIn: EvmAddressSchema,\n tokenOut: EvmAddressSchema,\n amount: z.coerce.bigint().nonnegative(),\n numberOfOrders: z.number().int(),\n frequency: RecurringFrequencySchema,\n intervalSeconds: z.number().int().nonnegative(),\n totalAmountIn: z.coerce.bigint().nonnegative(),\n amountOut: z.coerce.bigint().nonnegative(),\n minAmountOut: z.coerce.bigint().nonnegative(),\n fees: z.array(RecurringQuoteFeeSchema),\n recommendedSlippage: z.number().int().nonnegative(),\n expiredAt: z.number().int().nonnegative(),\n});\n\n/**\n * Schema for the response from Markr's `/recurring/orders` (list) endpoint.\n */\nexport const ListRecurringOrdersResponseSchema: z.ZodType<ListRecurringOrdersResponse> = z.object({\n address: EvmAddressSchema,\n count: z.number().int().nonnegative(),\n orders: z.array(RecurringOrderSchema),\n});\n"],"mappings":"qKAaA,MAAM,EAAiB,sBAEV,EAAkE,EAAE,KAAK,EAA0B,CAEnG,EAA0D,EAAE,OAAO,CAC9E,KAAM,EACN,MAAO,EAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,CAC/B,CAAC,CAQW,EAA8D,EAAE,KAC3E,OAAO,OAAO,EAAqB,CACpC,CAEY,EAAgE,EAAE,OAAO,CAKpF,eAAgB,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CAC9C,QAAS,EAAE,MAAM,EAAE,QAAQ,CAAC,CAC5B,S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GF,MAAO,EAAE,MAAM,CAAC,EAAE,SAAS,CAAE,EAAE,OAAO,EAAE,QAAQ,CAAE,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,UAAU,CAC5E,CAAC,CAKW,EAAkE,EAAE,OAAO,CACtF,KAAM,EAAE,MAAM,CACd,QAAS,EAAE,OAAO,QAAQ,CAAC,KAAK,CAAC,aAAa,CAC9C,QAAS,EACT,SAAU,EACV,OAAQ,EAAE,OAAO,QAAQ,CAAC,aAAa,CACvC,eAAgB,EAAE,QAAQ,CAAC,KAAK,CAChC,UAAW,EACX,gBAAiB,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CAC/C,cAAe,EAAE,OAAO,QAAQ,CAAC,aAAa,CAC9C,UAAW,EAAE,OAAO,QAAQ,CAAC,aAAa,CAC1C,aAAc,EAAE,OAAO,QAAQ,CAAC,aAAa,CAC7C,KAAM,EAAE,MAAM,EAAwB,CACtC,oBAAqB,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CACnD,UAAW,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CAC1C,CAAC,CAKW,EAA4E,EAAE,OAAO,CAChG,QAAS,EACT,MAAO,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,CACrC,OAAQ,EAAE,MAAM,EAAqB,CACtC,CAAC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { CheckRecurringEligibilityParams, ListRecurringOrdersParams, ListRecurringOrdersResponse, RECURRING_FREQUENCY_UNITS, RECURRING_UNLIMITED_ORDERS_SENTINEL, RecurringChainInfoEntry, RecurringChainInfoMap, RecurringEligibility, RecurringEligibilityReason, RecurringExecuteFirstFillParams, RecurringExecuteOrderActionParams, RecurringExecuteResult, RecurringFrequency, RecurringFrequencyUnit, RecurringNamespace, RecurringNamespaceCheckEligibilityParams, RecurringNamespaceQuoteParams, RecurringOrder, RecurringOrderFailure, RecurringOrderStatus, RecurringQuoteFee, RecurringQuoteFeeType, RecurringQuoteParams, RecurringQuoteResponse, RecurringSwapParams } from "./types.js";
|
|
2
|
+
import { FrequencyValidationResult, RECURRING_FREQUENCY_VALUE_MAX, deriveIntervalSeconds, validateFrequency } from "./_frequency.js";
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=[`minute`,`hour`,`day`,`week`,`month`];let t=function(e){return e.Active=`active`,e.Completed=`completed`,e.Cancelled=`cancelled`,e.Paused=`paused`,e}({}),n=function(e){return e.CrossChain=`cross-chain`,e.UnsupportedSourceChain=`unsupported-source-chain`,e.UnsupportedToken=`unsupported-token`,e.NoEvmAddress=`no-evm-address`,e.AmountBelowMinimum=`amount-below-minimum`,e}({});exports.RECURRING_FREQUENCY_UNITS=e,exports.RECURRING_UNLIMITED_ORDERS_SENTINEL=-1,exports.RecurringEligibilityReason=n,exports.RecurringOrderStatus=t;
|
|
2
|
+
//# sourceMappingURL=types.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.cjs","names":[],"sources":["../../../../src/transfer-service/markr/recurring/types.ts"],"sourcesContent":["import type { Address as EvmAddress } from 'viem';\nimport type { Chain } from '../../../types/chain';\nimport type { GasSettings } from '../../../types/service';\nimport type { Hex } from '../../../types/signer';\n\n/**\n * Frequency units accepted by Markr's `/recurring/quote` and `/recurring/orders` endpoints.\n *\n * @see https://orchestrator-docs.markr.io/#/paths/~1recurring~1quote/post\n */\nexport const RECURRING_FREQUENCY_UNITS = ['minute', 'hour', 'day', 'week', 'month'] as const;\n\nexport type RecurringFrequencyUnit = (typeof RECURRING_FREQUENCY_UNITS)[number];\n\nexport interface RecurringFrequency {\n unit: RecurringFrequencyUnit;\n /**\n * Integer in `[1, 365]` (server-enforced upper bound). `validateFrequency`\n * surfaces violations as `{ ok: false, reason: 'invalid-value' }`.\n */\n value: number;\n}\n\n/**\n * Markr's \"unlimited orders\" sentinel. Sent to the server as `-1`, which the\n * router expands to `uint256` max on-chain. Callers can also pass `Infinity`\n * to {@link RecurringQuoteParams.numberOfOrders} for the same effect; the API\n * helpers translate to `-1` at the wire boundary.\n */\nexport const RECURRING_UNLIMITED_ORDERS_SENTINEL = -1;\n\n/**\n * Status values emitted by Markr for a recurring schedule. Treated as a\n * closed set — if Markr ever adds a new value server-side, the schema\n * will reject it loudly so the SDK update gates rendering changes\n * (instead of silently passing an unhandled state through to the UI).\n *\n * Mirrors the existing `TransferSignatureReason` enum pattern in\n * `constants.ts`: PascalCase members with kebab/lowercase wire values.\n */\nexport enum RecurringOrderStatus {\n Active = 'active',\n Completed = 'completed',\n Cancelled = 'cancelled',\n Paused = 'paused',\n}\n\nexport interface RecurringOrderFailure {\n /** 1-based index of the failed scheduled swap. */\n executionIndex: number;\n /** Reason strings supplied by the orchestrator (e.g. `\"Slippage tolerance exceeded\"`). */\n reasons: ReadonlyArray<string>;\n /** On-chain attempts before the execution was marked failed. */\n tryCount: number;\n /** Unix seconds. */\n failedAt: number;\n}\n\n/**\n * Server-side recurring-swap order returned by `GET /recurring/orders` and\n * `POST /recurring/orders/{orderId}/cancel`.\n *\n * @see https://orchestrator-docs.markr.io/#/Recurring%20Swaps\n */\nexport interface RecurringOrder {\n /**\n * bytes32 hex (`0x` + 64 hex chars). Used as the path param for cancellation.\n * Typed as a template-literal `0x`-prefixed string to catch the obvious\n * \"I forgot the `0x`\" mistake at compile time; the wire-level regex check\n * (in `markrCancelRecurringOrder`) enforces the full bytes32 shape.\n */\n orderId: `0x${string}`;\n /** EVM wallet that created the schedule. */\n owner: EvmAddress;\n chainId: number;\n tokenIn: EvmAddress;\n tokenOut: EvmAddress;\n /** Per-order input amount, in `tokenIn`'s smallest unit. */\n amount: bigint;\n /** -1 when unlimited; otherwise a positive integer (server-clamped to ≤ 365). */\n numberOfOrders: number;\n executedOrders: number;\n /**\n * `numberOfOrders - executedOrders` on finite schedules. `null` on\n * unlimited schedules (`numberOfOrders === -1`) — they have no finite\n * remainder to report. Per the Markr OpenAPI spec the field is\n * nullable; the schema also normalizes `undefined` to `null` so a\n * `=== null` check is sufficient.\n */\n remainingOrders: number | null;\n frequency: RecurringFrequency;\n /** `amount × numberOfOrders` — the ERC-20 allowance granted at setup. */\n totalAmountIn: bigint;\n /** Retry count for the *next* pending execution. `0` when none is pending. */\n tryCount: number;\n /** History of failed `executionIndex` values, newest last. */\n failures: ReadonlyArray<RecurringOrderFailure>;\n status: RecurringOrderStatus;\n /** Unix seconds. */\n createdAt: number;\n /**\n * Unix seconds. `null` once the schedule is completed / cancelled /\n * inactive. Per the Markr OpenAPI spec this field is optional + nullable;\n * the schema normalizes an omitted-field response to `null` so consumers\n * can branch on a single `=== null` check.\n */\n nextExecutionAt: number | null;\n /**\n * Unix seconds when the order was cancelled; `null` otherwise. Populated\n * with a number when `status === 'cancelled'`. Per the Markr OpenAPI spec\n * this field is optional + nullable; the schema normalizes both wire\n * shapes (`null` and omitted) to `null` for consumer ergonomics.\n */\n cancelledAt: number | null;\n}\n\n/**\n * Known fee types emitted by Markr today. Open at runtime — the schema\n * tolerates unknown values so a new fee category from the orchestrator doesn't\n * fail quote parsing. See {@link RecurringOrderStatus} for the widening\n * pattern.\n */\nexport type RecurringQuoteFeeType =\n | 'gas'\n | 'recurring'\n | 'protocol'\n | 'bridge'\n | 'slippage'\n | 'swap'\n | 'other'\n // See `RecurringOrderStatus` for why `Record<never, never>` replaces `{}`.\n | (string & Record<never, never>);\n\nexport interface RecurringQuoteFee {\n type: RecurringQuoteFeeType;\n name: string;\n amount: bigint;\n token: { chainId: number; address: EvmAddress };\n /**\n * Docs document `extra` as `boolean or object`. The boolean form is the\n * legacy \"additive one-time charge\" flag (e.g. the one-time native\n * schedule fee with `type: 'recurring'`); the object form is reserved\n * for future structured metadata. Consumers should treat any truthy\n * value as \"additive — balance-check separately.\"\n */\n extra?: boolean | Record<string, unknown>;\n}\n\nexport interface RecurringQuoteResponse {\n uuid: string;\n chainId: number;\n tokenIn: EvmAddress;\n tokenOut: EvmAddress;\n /** Per-order input. */\n amount: bigint;\n /** Server-side clamped value (may be 365 if the request was unlimited). */\n numberOfOrders: number;\n frequency: RecurringFrequency;\n /** Server-derived from `frequency`. */\n intervalSeconds: number;\n /** `amount × numberOfOrders` — the ERC-20 allowance the caller must grant. */\n totalAmountIn: bigint;\n /** First-fill output estimate. */\n amountOut: bigint;\n /** First-fill `minAmountOut` (slippage applied). */\n minAmountOut: bigint;\n fees: ReadonlyArray<RecurringQuoteFee>;\n /** Basis points. */\n recommendedSlippage: number;\n /** Unix seconds. */\n expiredAt: number;\n}\n\nexport interface RecurringQuoteParams {\n appId: string;\n chainId: number;\n tokenIn: EvmAddress;\n tokenInDecimals: number;\n tokenOut: EvmAddress;\n tokenOutDecimals: number;\n /**\n * Per-order input in smallest unit. `bigint` only — matches the rest of the\n * SDK's internal amount types (response amounts, `Quote.amountIn`, etc.).\n * Callers holding a decimal string should coerce with `BigInt(s)` at the\n * call site.\n */\n amount: bigint;\n /**\n * Number of orders. Accepts:\n * - `Infinity` or `-1` — translated to the unlimited sentinel (`-1`) on the wire.\n * - Integer in `[2, 365]` — Markr's documented finite bound.\n *\n * Anything else (`NaN`, `0`, `1`, negatives other than `-1`, non-integers,\n * values > 365) throws `InvalidParamsError` at the SDK boundary so a\n * misbehaving form parse (`parseInt('')` → `NaN`, or a stale \"minimum is 1\"\n * assumption) can't silently become an unlimited schedule or a guaranteed\n * server-side rejection.\n */\n numberOfOrders: number;\n frequency: RecurringFrequency;\n /** Basis points (matches `/quote` semantics). */\n slippage?: number;\n}\n\nexport interface RecurringSwapParams {\n uuid: string;\n appId: string;\n}\n\nexport interface ListRecurringOrdersParams {\n address: EvmAddress;\n chainId?: number;\n status?: RecurringOrderStatus;\n}\n\nexport interface ListRecurringOrdersResponse {\n address: EvmAddress;\n count: number;\n orders: ReadonlyArray<RecurringOrder>;\n}\n\n/**\n * Wire-level params for the internal `_api.ts` cancel/pause/unpause helpers\n * (`markrPrepareCancellation` etc.). Public consumers reach the same endpoints\n * via {@link RecurringNamespace.executeCancellation}/`executePause`/\n * `executeUnpause`, which take {@link RecurringExecuteOrderActionParams}\n * instead and derive `chainId` from the passed `sourceChain`.\n */\nexport interface RecurringOrderActionApiParams {\n /** See {@link RecurringOrder.orderId} for the shape. */\n orderId: `0x${string}`;\n address: EvmAddress;\n /**\n * Chain the schedule lives on — required by Markr's\n * `POST /recurring/orders/{orderId}/{action}` endpoints (the orchestrator\n * scopes orderIds per chain, so the same bytes32 could in principle exist\n * on multiple chains).\n */\n chainId: number;\n}\n\n/**\n * Shared params for the three order-action execute methods\n * ({@link RecurringNamespace.executeCancellation},\n * {@link RecurringNamespace.executePause},\n * {@link RecurringNamespace.executeUnpause}). The SDK derives the wire-level\n * `chainId` from `sourceChain`, estimates gas via the chain's RPC, then signs\n * and broadcasts via the configured `evmSigner`.\n */\nexport interface RecurringExecuteOrderActionParams {\n /** See {@link RecurringOrder.orderId} for the shape. */\n orderId: `0x${string}`;\n /** Owner address of the schedule — must match the order's `owner`. */\n address: EvmAddress;\n /**\n * Source chain the schedule lives on — pass the same `Chain` that backs\n * `sourceChain` on the recurring order (the SDK reads `rpcUrl` + multicall\n * for the on-chain gas estimate and uses `chainId` for the wire request).\n */\n sourceChain: Chain;\n /** Optional fee-margin + 1559 overrides forwarded to the signed TX. */\n gasSettings?: GasSettings;\n}\n\n/**\n * Params for {@link RecurringNamespace.executeFirstFill}. Replaces the\n * pre-signer `prepareFirstFill` shape; the SDK now reads the on-chain\n * allowance against `totalAmountIn`, signs an `approve` if needed (batched\n * one-click when `evmSigner.signBatch` is available and the swap is\n * same-chain), then signs and broadcasts the first-fill swap.\n */\nexport interface RecurringExecuteFirstFillParams {\n /** Full recurring quote — carries `uuid`, `totalAmountIn`, `expiredAt`. */\n quote: RecurringQuoteResponse;\n /** EVM address creating the schedule (and signing the first fill). */\n fromAddress: EvmAddress;\n /**\n * Source chain — same `Chain` used to obtain the recurring quote. The SDK\n * reads `rpcUrl` for allowance + gas calls; `chainId` is cross-checked\n * against `quote.chainId` to catch obvious wiring mistakes.\n */\n sourceChain: Chain;\n /** Optional fee-margin + 1559 overrides. */\n gasSettings?: GasSettings;\n /**\n * Mirrors the same flag on `TransferService.transferAsset`: when the\n * one-click batch (approval + first-fill) is attempted and the consumer's\n * wallet rejects the batch, fall back to two sequential signatures\n * (`approve`, then `swap`) instead of bubbling the batch error up.\n */\n fallbackToDefaultOnBatchFailure?: boolean;\n}\n\n/** Result of any `recurring.execute*` method — broadcast TX hash. */\nexport interface RecurringExecuteResult {\n txHash: Hex;\n}\n\nexport interface RecurringChainInfoEntry {\n /** Server-published lower bound for `intervalSeconds` (today: 300s on enabled chains). */\n minFrequencySeconds: number;\n supportedTokens: ReadonlyArray<{\n address: EvmAddress;\n /**\n * Smallest-unit decimal string — must be `BigInt()`-parseable (i.e.\n * matches `/^\\d+$/`). The Zod schema enforces this on the wire, but the\n * TS type alone is plain `string`; consumers constructing this map by\n * hand (caching, tests) should pass a digits-only decimal string or\n * `BigInt(minimumAmount)` will throw downstream in `checkEligibility`.\n */\n minimumAmount: string;\n }>;\n}\n\n/**\n * Cached `/info/chains` recurring metadata keyed by EVM chainId. SVM chains\n * are omitted — Markr supports recurring on same-chain EVM only.\n */\nexport type RecurringChainInfoMap = ReadonlyMap<number, RecurringChainInfoEntry>;\n\n/**\n * Reasons surfaced when {@link checkRecurringEligibility} returns\n * `{ eligible: false, … }`. Mirrors the existing `TransferSignatureReason`\n * enum pattern (PascalCase member, kebab-case wire value) so external\n * consumers comparing the raw string still match.\n */\nexport enum RecurringEligibilityReason {\n CrossChain = 'cross-chain',\n UnsupportedSourceChain = 'unsupported-source-chain',\n UnsupportedToken = 'unsupported-token',\n NoEvmAddress = 'no-evm-address',\n AmountBelowMinimum = 'amount-below-minimum',\n}\n\nexport type RecurringEligibility =\n | { eligible: true; minimumAmount: string; minIntervalSeconds: number }\n // `AmountBelowMinimum` carries the floor so error UIs can say \"Min is X\"\n // without a second `getRecurringChainInfo()` lookup. The value is the same\n // smallest-unit decimal string as the success branch's `minimumAmount`.\n | { eligible: false; reason: RecurringEligibilityReason.AmountBelowMinimum; minimumAmount: string }\n | { eligible: false; reason: Exclude<RecurringEligibilityReason, RecurringEligibilityReason.AmountBelowMinimum> };\n\nexport interface CheckRecurringEligibilityParams {\n recurringChainInfo: RecurringChainInfoMap;\n fromTokenAddress: EvmAddress;\n toTokenAddress: EvmAddress;\n sourceChainId: number;\n targetChainId: number;\n ownerAddress?: EvmAddress;\n /** Per-order amount; when present, enables the `amount-below-minimum` check. */\n amount?: bigint;\n}\n\n/**\n * Params passed to `RecurringNamespace.checkEligibility`. Same as\n * `CheckRecurringEligibilityParams` minus the chain-info map, which the\n * namespace closure injects.\n */\nexport type RecurringNamespaceCheckEligibilityParams = Omit<CheckRecurringEligibilityParams, 'recurringChainInfo'>;\n\n/**\n * Params passed to `RecurringNamespace.quote`. Same as `RecurringQuoteParams`\n * minus `appId`, which the namespace closure injects.\n */\nexport type RecurringNamespaceQuoteParams = Omit<RecurringQuoteParams, 'appId'>;\n\n/**\n * High-level wrapper exposed as `MarkrService.recurring`. Methods curry\n * `apiOptions`, `appId`, and the cached `recurringChainInfo` so callers only\n * pass per-call inputs.\n */\nexport interface RecurringNamespace {\n /** POST `/recurring/quote` — full quote with `totalAmountIn`, fees, expiry, uuid. */\n quote(props: RecurringNamespaceQuoteParams): Promise<RecurringQuoteResponse>;\n\n /**\n * Creates the schedule on-chain by signing and broadcasting the first\n * `/recurring/swap` fill via the configured `evmSigner`. Mirrors\n * `TransferService.transferAsset`:\n *\n * 1. Reads on-chain `allowance(tokenIn → router)` against `quote.totalAmountIn`.\n * 2. If allowance is short, builds an `approve(router, totalAmountIn)` TX.\n * When the consumer's signer exposes `signBatch`, the SDK attempts a\n * one-click batch (approve + swap) — set\n * {@link RecurringExecuteFirstFillParams.fallbackToDefaultOnBatchFailure}\n * to fall back to two sequential signatures if the wallet rejects the\n * batch.\n * 3. Estimates gas (with `gasSettings.estimateGasMarginBps` margin) for\n * each TX before signing, and dispatches the signed serialized TX via\n * the chain's RPC.\n *\n * Quote-expiry guard mirrors the previous `prepareFirstFill` behavior —\n * `quote.expiredAt <= now` throws `InvalidParamsError(QUOTE_EXPIRED)` at\n * the SDK boundary before any HTTP / on-chain call.\n *\n * Returns the broadcast first-fill TX hash; the schedule transitions to\n * `'active'` once Markr observes the on-chain event (poll `listOrders`).\n */\n executeFirstFill(props: RecurringExecuteFirstFillParams): Promise<RecurringExecuteResult>;\n\n /**\n * GET `/recurring/orders?address=…&chainId?=…&status?=…` — returns the\n * full response (`{ address, count, orders }`) so callers can render the\n * server-echoed `address` (e.g. confirming the queried wallet matches the\n * current EVM signer) and `count` (pagination / \"you have N schedules\"\n * affordances) without an extra lookup. Consumers that only care about the\n * orders array can destructure: `const { orders } = await listOrders(…)`.\n */\n listOrders(props: ListRecurringOrdersParams): Promise<ListRecurringOrdersResponse>;\n\n /**\n * Cancels the recurring schedule identified by `orderId`: fetches the\n * `/recurring/orders/{orderId}/cancel` calldata, estimates gas, then signs\n * and broadcasts via the configured `evmSigner`. The schedule transitions\n * to `status: 'cancelled'` only once the TX confirms and Markr observes\n * the on-chain event.\n *\n * Eligibility: only `'active'` and `'paused'` orders can be cancelled per\n * Markr's docs. An attempt to cancel a `'completed'` order surfaces as\n * `HttpError(400)` from the orchestrator before signing.\n */\n executeCancellation(props: RecurringExecuteOrderActionParams): Promise<RecurringExecuteResult>;\n\n /**\n * Pauses the recurring schedule identified by `orderId`: fetches the\n * `/recurring/orders/{orderId}/pause` calldata, estimates gas, then signs\n * and broadcasts via the configured `evmSigner`. The schedule transitions\n * to `status: 'paused'` only once the TX confirms and Markr observes the\n * on-chain event.\n *\n * Eligibility: only `'active'` orders can be paused per Markr's docs.\n * Attempting to pause a non-`active` order surfaces as `HttpError(400)`.\n *\n * Pausing preserves the schedule's existing ERC-20 allowance — when the\n * user later unpauses, no re-approval and no new native schedule fee are\n * required (this is the key UX benefit of pause over cancel-and-recreate).\n *\n * @see https://orchestrator-docs.markr.io/#tag/Recurring-Swaps/paths/~1recurring~1orders~1{orderId}~1pause/post\n */\n executePause(props: RecurringExecuteOrderActionParams): Promise<RecurringExecuteResult>;\n\n /**\n * Unpauses (resumes) the recurring schedule identified by `orderId`:\n * fetches the `/recurring/orders/{orderId}/unpause` calldata, estimates\n * gas, then signs and broadcasts via the configured `evmSigner`. The\n * schedule transitions back to `status: 'active'` only once the TX\n * confirms and Markr observes the on-chain event.\n *\n * Eligibility: only `'paused'` orders can be unpaused per Markr's docs.\n * Attempting to unpause a non-`paused` order surfaces as `HttpError(400)`.\n *\n * Resumes execution from where the schedule left off — remaining fills\n * continue on the original `frequency` cadence. The orchestrator recomputes\n * `nextExecutionAt` after the TX confirms.\n *\n * @see https://orchestrator-docs.markr.io/#tag/Recurring-Swaps/paths/~1recurring~1orders~1{orderId}~1unpause/post\n */\n executeUnpause(props: RecurringExecuteOrderActionParams): Promise<RecurringExecuteResult>;\n\n /**\n * Pure (no fetch) — uses the cached `/info/chains` recurring metadata.\n *\n * **Covers:** chain support, token support, EVM-address presence, same-chain\n * (cross-chain rejected), and per-order minimum (when `amount` is passed —\n * failure carries `minimumAmount`).\n *\n * **Does NOT cover wallet balance.** This helper has no wallet/RPC context.\n * Checking that the user holds `amount × numberOfOrders` of `tokenIn` (plus\n * native gas for the first fill) is the consumer's responsibility, same as\n * the one-shot swap flow. There is no `InsufficientBalance` reason on\n * {@link RecurringEligibilityReason} by design.\n *\n * **Does NOT cover post-fill failures.** Once a schedule is live, on-chain\n * reverts (slippage, runtime insufficient balance, etc.) surface server-side\n * as open-ended strings on `RecurringOrder.failures[].reasons` — substring-\n * match those for client-driven auto-cancel (AC4 pattern) and call\n * {@link RecurringNamespace.prepareCancellation} when applicable.\n *\n * **Does NOT cover server-side quote rejection.** Slippage, target-token\n * unsupported, liquidity, etc. are decided at `/recurring/quote` time and\n * surface as `HttpError` from {@link RecurringNamespace.quote}.\n */\n checkEligibility(props: RecurringNamespaceCheckEligibilityParams): RecurringEligibility;\n\n /** Returns the cached `/info/chains` recurring metadata. */\n getRecurringChainInfo(): RecurringChainInfoMap;\n}\n"],"mappings":"AAUA,MAAa,EAA4B,CAAC,SAAU,OAAQ,MAAO,OAAQ,QAAQ,CA8BnF,IAAY,EAAL,SAAA,EAAA,OACL,GAAA,OAAA,SACA,EAAA,UAAA,YACA,EAAA,UAAA,YACA,EAAA,OAAA,eACD,CAyRW,EAAL,SAAA,EAAA,OACL,GAAA,WAAA,cACA,EAAA,uBAAA,2BACA,EAAA,iBAAA,oBACA,EAAA,aAAA,iBACA,EAAA,mBAAA,6BACD"}
|