@secondlayer/stacks 4.3.2 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -11
- package/dist/shared/{stacks-bfan7ex7.js → stacks-4d7c3x27.js} +5 -5
- package/dist/shared/{stacks-bfan7ex7.js.map → stacks-4d7c3x27.js.map} +3 -3
- package/dist/shared/{stacks-709tra19.js → stacks-4hs8r4q2.js} +16 -2
- package/dist/shared/stacks-4hs8r4q2.js.map +10 -0
- package/dist/shared/{stacks-w23294am.js → stacks-51ybf135.js} +3 -3
- package/dist/shared/{stacks-0jk7vd8r.cjs → stacks-69nq48jp.js} +120 -17
- package/dist/shared/stacks-69nq48jp.js.map +15 -0
- package/dist/shared/{stacks-8pfdscq6.js → stacks-6gavarmy.js} +37 -9
- package/dist/shared/stacks-6gavarmy.js.map +12 -0
- package/dist/shared/{stacks-gxq2pbky.js → stacks-71k0vmct.js} +65 -8
- package/dist/shared/stacks-71k0vmct.js.map +13 -0
- package/dist/shared/{stacks-7wkf2rph.js → stacks-7bqkf3b0.js} +86 -71
- package/dist/shared/{stacks-7wkf2rph.js.map → stacks-7bqkf3b0.js.map} +9 -10
- package/dist/shared/{stacks-zcpvzbr0.js → stacks-8brgfvqx.js} +3 -3
- package/dist/shared/{stacks-4vzmhw3q.cjs → stacks-8vzxax5e.cjs} +13 -3
- package/dist/shared/stacks-8vzxax5e.cjs.map +10 -0
- package/dist/shared/{stacks-hnqt5rz4.js → stacks-9c1yam8b.js} +3 -3
- package/dist/shared/{stacks-bnbdqznq.cjs → stacks-bdgh9n83.cjs} +11 -10
- package/dist/shared/{stacks-bnbdqznq.cjs.map → stacks-bdgh9n83.cjs.map} +3 -3
- package/dist/shared/{stacks-fb75yew8.js → stacks-db3kwavg.cjs} +346 -138
- package/dist/shared/stacks-db3kwavg.cjs.map +23 -0
- package/dist/shared/{stacks-jpt52csy.js → stacks-e3nwm1dz.js} +14 -17
- package/dist/shared/stacks-e3nwm1dz.js.map +10 -0
- package/dist/shared/{stacks-ta1gar0b.cjs → stacks-ee53k9j2.cjs} +62 -6
- package/dist/shared/stacks-ee53k9j2.cjs.map +13 -0
- package/dist/shared/{stacks-27fmgajb.js → stacks-ga026yxz.js} +9 -9
- package/dist/shared/{stacks-27fmgajb.js.map → stacks-ga026yxz.js.map} +3 -3
- package/dist/shared/{stacks-nyaw1z2a.cjs → stacks-ggdz96r1.cjs} +4 -4
- package/dist/shared/{stacks-nyaw1z2a.cjs.map → stacks-ggdz96r1.cjs.map} +3 -3
- package/dist/shared/{stacks-08y0y0t7.js → stacks-gjz26k6b.js} +2 -2
- package/dist/shared/{stacks-x5386y2y.cjs → stacks-gza2n1zs.cjs} +5 -5
- package/dist/shared/{stacks-x5386y2y.cjs.map → stacks-gza2n1zs.cjs.map} +3 -3
- package/dist/shared/{stacks-ztzygy90.js → stacks-mftyrc60.js} +2 -2
- package/dist/shared/stacks-n4d8j8q3.js +801 -0
- package/dist/shared/stacks-n4d8j8q3.js.map +23 -0
- package/dist/shared/{stacks-ycbq8pf7.cjs → stacks-p337hp6m.cjs} +74 -59
- package/dist/shared/{stacks-ycbq8pf7.cjs.map → stacks-p337hp6m.cjs.map} +9 -10
- package/dist/shared/{stacks-ttdk2g2f.js → stacks-s5vej5z6.cjs} +92 -41
- package/dist/shared/stacks-s5vej5z6.cjs.map +15 -0
- package/dist/shared/stacks-sdqkapct.cjs +67 -0
- package/dist/shared/stacks-sdqkapct.cjs.map +12 -0
- package/dist/shared/{stacks-1arrcd11.js → stacks-v2rfr46a.js} +2 -2
- package/dist/shared/{stacks-9mqveyjv.cjs → stacks-w9t61fra.cjs} +7 -10
- package/dist/shared/stacks-w9t61fra.cjs.map +10 -0
- package/dist/shared/{stacks-tjjnkt3r.js → stacks-wxfd6r4b.js} +2 -2
- package/dist/shared/{stacks-4z72akdf.js → stacks-x0qqwrev.js} +3 -3
- package/dist/shared/{stacks-gck1sq7h.cjs → stacks-xjkn3en1.cjs} +16 -2
- package/dist/shared/stacks-xjkn3en1.cjs.map +10 -0
- package/dist/shared/stacks-xnrywjf1.cjs +131 -0
- package/dist/shared/stacks-xnrywjf1.cjs.map +11 -0
- package/dist/shared/stacks-yajyej2y.js +139 -0
- package/dist/shared/stacks-yajyej2y.js.map +11 -0
- package/dist/shared/{stacks-913a2rx7.js → stacks-yvb7rvwk.js} +13 -3
- package/dist/shared/stacks-yvb7rvwk.js.map +10 -0
- package/dist/shared/{stacks-0cdm20eh.js → stacks-z90xdr1x.js} +7 -11
- package/dist/shared/{stacks-0cdm20eh.js.map → stacks-z90xdr1x.js.map} +3 -3
- package/dist/src/accounts/index.js +2 -3
- package/dist/src/accounts/index.js.map +2 -2
- package/dist/src/actions/index.cjs +2 -1
- package/dist/src/actions/index.cjs.map +1 -1
- package/dist/src/actions/index.d.cts +108 -20
- package/dist/src/actions/index.d.ts +108 -20
- package/dist/src/actions/index.js +17 -15
- package/dist/src/actions/index.js.map +1 -1
- package/dist/src/bitcoin/index.d.cts +27 -0
- package/dist/src/bitcoin/index.d.ts +27 -0
- package/dist/src/bitcoin/index.js +10 -11
- package/dist/src/bitcoin/index.js.map +2 -2
- package/dist/src/bns/index.d.cts +27 -0
- package/dist/src/bns/index.d.ts +27 -0
- package/dist/src/bns/index.js +13 -13
- package/dist/src/bns/index.js.map +1 -1
- package/dist/src/clarity/index.js +7 -6
- package/dist/src/clarity/index.js.map +1 -1
- package/dist/src/connect/index.cjs +44 -30
- package/dist/src/connect/index.cjs.map +7 -7
- package/dist/src/connect/index.d.cts +16 -1
- package/dist/src/connect/index.d.ts +16 -1
- package/dist/src/connect/index.js +44 -30
- package/dist/src/connect/index.js.map +7 -7
- package/dist/src/connect/walletconnect/index.cjs +49 -413
- package/dist/src/connect/walletconnect/index.cjs.map +4 -4
- package/dist/src/connect/walletconnect/index.js +47 -411
- package/dist/src/connect/walletconnect/index.js.map +4 -4
- package/dist/src/filters/index.js +2 -2
- package/dist/src/index.cjs +49 -124
- package/dist/src/index.cjs.map +6 -8
- package/dist/src/index.d.cts +163 -54
- package/dist/src/index.d.ts +163 -54
- package/dist/src/index.js +79 -147
- package/dist/src/index.js.map +6 -8
- package/dist/src/postconditions/index.js +6 -5
- package/dist/src/postconditions/index.js.map +1 -1
- package/dist/src/pox/index.cjs +7 -83
- package/dist/src/pox/index.cjs.map +3 -3
- package/dist/src/pox/index.d.cts +32 -1
- package/dist/src/pox/index.d.ts +32 -1
- package/dist/src/pox/index.js +22 -102
- package/dist/src/pox/index.js.map +3 -3
- package/dist/src/pox5/index.cjs +4 -112
- package/dist/src/pox5/index.cjs.map +3 -4
- package/dist/src/pox5/index.d.cts +27 -0
- package/dist/src/pox5/index.d.ts +27 -0
- package/dist/src/pox5/index.js +20 -131
- package/dist/src/pox5/index.js.map +3 -4
- package/dist/src/sbtc/index.cjs +2 -27
- package/dist/src/sbtc/index.cjs.map +3 -3
- package/dist/src/sbtc/index.d.cts +30 -2
- package/dist/src/sbtc/index.d.ts +30 -2
- package/dist/src/sbtc/index.js +15 -45
- package/dist/src/sbtc/index.js.map +3 -3
- package/dist/src/stackingdao/index.d.cts +27 -0
- package/dist/src/stackingdao/index.d.ts +27 -0
- package/dist/src/stackingdao/index.js +11 -11
- package/dist/src/stackingdao/index.js.map +1 -1
- package/dist/src/subscriptions/index.d.cts +27 -0
- package/dist/src/subscriptions/index.d.ts +27 -0
- package/dist/src/subscriptions/index.js +2 -2
- package/dist/src/tools/btc/index.cjs.map +2 -2
- package/dist/src/tools/btc/index.js.map +2 -2
- package/dist/src/tools/index.cjs +629 -392
- package/dist/src/tools/index.cjs.map +30 -28
- package/dist/src/tools/index.d.cts +44 -0
- package/dist/src/tools/index.d.ts +44 -0
- package/dist/src/tools/index.js +628 -391
- package/dist/src/tools/index.js.map +30 -28
- package/dist/src/transactions/index.js +6 -5
- package/dist/src/transactions/index.js.map +1 -1
- package/dist/src/utils/index.d.cts +2 -5
- package/dist/src/utils/index.d.ts +2 -5
- package/dist/src/utils/index.js +2 -2
- package/package.json +18 -7
- package/dist/shared/stacks-0eatsx6d.cjs +0 -25
- package/dist/shared/stacks-0eatsx6d.cjs.map +0 -10
- package/dist/shared/stacks-0jk7vd8r.cjs.map +0 -14
- package/dist/shared/stacks-4vzmhw3q.cjs.map +0 -10
- package/dist/shared/stacks-5nmz5ad9.js +0 -409
- package/dist/shared/stacks-5nmz5ad9.js.map +0 -10
- package/dist/shared/stacks-709tra19.js.map +0 -10
- package/dist/shared/stacks-8pfdscq6.js.map +0 -12
- package/dist/shared/stacks-913a2rx7.js.map +0 -10
- package/dist/shared/stacks-9mqveyjv.cjs.map +0 -10
- package/dist/shared/stacks-e4xn4m7j.js +0 -27
- package/dist/shared/stacks-e4xn4m7j.js.map +0 -10
- package/dist/shared/stacks-fb75yew8.js.map +0 -21
- package/dist/shared/stacks-gck1sq7h.cjs.map +0 -10
- package/dist/shared/stacks-gxq2pbky.js.map +0 -13
- package/dist/shared/stacks-jpt52csy.js.map +0 -10
- package/dist/shared/stacks-mnnhpex3.cjs +0 -407
- package/dist/shared/stacks-mnnhpex3.cjs.map +0 -10
- package/dist/shared/stacks-ta1gar0b.cjs.map +0 -13
- package/dist/shared/stacks-tdsp5gsb.cjs +0 -527
- package/dist/shared/stacks-tdsp5gsb.cjs.map +0 -21
- package/dist/shared/stacks-ttdk2g2f.js.map +0 -14
- package/dist/shared/stacks-wdp5yr8n.cjs +0 -39
- package/dist/shared/stacks-wdp5yr8n.cjs.map +0 -12
- /package/dist/shared/{stacks-w23294am.js.map → stacks-51ybf135.js.map} +0 -0
- /package/dist/shared/{stacks-zcpvzbr0.js.map → stacks-8brgfvqx.js.map} +0 -0
- /package/dist/shared/{stacks-hnqt5rz4.js.map → stacks-9c1yam8b.js.map} +0 -0
- /package/dist/shared/{stacks-08y0y0t7.js.map → stacks-gjz26k6b.js.map} +0 -0
- /package/dist/shared/{stacks-ztzygy90.js.map → stacks-mftyrc60.js.map} +0 -0
- /package/dist/shared/{stacks-1arrcd11.js.map → stacks-v2rfr46a.js.map} +0 -0
- /package/dist/shared/{stacks-tjjnkt3r.js.map → stacks-wxfd6r4b.js.map} +0 -0
- /package/dist/shared/{stacks-4z72akdf.js.map → stacks-x0qqwrev.js.map} +0 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/actions/public/estimateFee.ts", "../src/actions/public/getBlockHeight.ts", "../src/errors/http.ts", "../src/actions/public/getMapEntry.ts", "../src/actions/public/getNonce.ts", "../src/errors/transport.ts", "../src/transports/createTransport.ts", "../src/actions/public/txSources.ts", "../src/actions/public/getTransaction.ts", "../src/actions/public/waitForTransactionReceipt.ts", "../src/actions/wallet/sendTransaction.ts", "../src/actions/wallet/nonceManager.ts", "../src/actions/wallet/utils.ts", "../src/actions/wallet/callContract.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { Client } from \"../../clients/types.ts\";\nimport { MalformedResponseError } from \"../../errors/response.ts\";\nimport type { StacksTransaction } from \"../../transactions/types.ts\";\nimport {\n\tserializePayload,\n\tserializeTransaction,\n} from \"../../transactions/wire/serialize.ts\";\nimport { bytesToHex } from \"../../utils/encoding.ts\";\n\nexport type EstimateFeeParams = {\n\ttransaction: StacksTransaction;\n};\n\nexport type FeeEstimation = {\n\tfeeRate: number;\n\tfee: number;\n};\n\nfunction isValidEstimation(\n\te: unknown,\n): e is { fee_rate: number | string; fee: number | string } {\n\treturn (\n\t\ttypeof e === \"object\" &&\n\t\te !== null &&\n\t\t\"fee_rate\" in e &&\n\t\t\"fee\" in e &&\n\t\t(typeof (e as Record<string, unknown>).fee_rate === \"number\" ||\n\t\t\ttypeof (e as Record<string, unknown>).fee_rate === \"string\") &&\n\t\t(typeof (e as Record<string, unknown>).fee === \"number\" ||\n\t\t\ttypeof (e as Record<string, unknown>).fee === \"string\")\n\t);\n}\n\nexport async function estimateFee(\n\tclient: Client,\n\tparams: EstimateFeeParams,\n): Promise<FeeEstimation[]> {\n\tconst payloadHex = bytesToHex(serializePayload(params.transaction.payload));\n\tconst txHex = bytesToHex(serializeTransaction(params.transaction));\n\n\tconst data = await client.request(\"/v2/fees/transaction\", {\n\t\tmethod: \"POST\",\n\t\tbody: {\n\t\t\testimated_len: Math.ceil(txHex.length / 2),\n\t\t\ttransaction_payload: `0x${payloadHex}`,\n\t\t},\n\t});\n\n\tconst raw = (data as { estimations?: unknown[] })?.estimations ?? [];\n\treturn raw.map((e) => {\n\t\tif (!isValidEstimation(e)) {\n\t\t\tthrow new MalformedResponseError(\n\t\t\t\t\"estimateFee: node response contains invalid fee estimation entry\",\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tfeeRate: Number(e.fee_rate),\n\t\t\tfee: Number(e.fee),\n\t\t};\n\t});\n}\n",
|
|
6
|
+
"import type { Client } from \"../../clients/types.ts\";\nimport { MalformedResponseError } from \"../../errors/response.ts\";\n\nexport async function getBlockHeight(client: Client): Promise<number> {\n\tconst data = await client.request(\"/v2/info\", { method: \"GET\" });\n\tif (typeof data?.stacks_tip_height !== \"number\") {\n\t\tthrow new MalformedResponseError(\n\t\t\t'getBlockHeight: /v2/info response is missing \"stacks_tip_height\"',\n\t\t);\n\t}\n\treturn data.stacks_tip_height;\n}\n",
|
|
7
|
+
"import { BaseError } from \"./base.ts\";\n\n/** Thrown by the HTTP transport when a response's status isn't 2xx. */\nexport class HttpRequestError extends BaseError {\n\toverride name = \"HttpRequestError\";\n\tstatus: number;\n\t/** Request URL, when the transport knows it. */\n\turl?: string;\n\t/** Request method, when the transport knows it. */\n\tmethod?: string;\n\n\tconstructor(\n\t\tstatus: number,\n\t\toptions?: {\n\t\t\tcause?: Error;\n\t\t\tdetails?: string;\n\t\t\turl?: string;\n\t\t\tmethod?: string;\n\t\t},\n\t) {\n\t\tconst where =\n\t\t\toptions?.url !== undefined\n\t\t\t\t? ` (${options.method ?? \"GET\"} ${options.url})`\n\t\t\t\t: \"\";\n\t\tsuper(`HTTP request failed with status ${status}${where}`, options);\n\t\tthis.status = status;\n\t\tthis.url = options?.url;\n\t\tthis.method = options?.method;\n\t}\n}\n",
|
|
8
|
+
"import { deserializeCVBytes } from \"../../clarity/deserialize.ts\";\nimport { serializeCVBytes } from \"../../clarity/serialize.ts\";\nimport type { ClarityValue } from \"../../clarity/types.ts\";\nimport type { Client } from \"../../clients/types.ts\";\nimport { MalformedResponseError } from \"../../errors/response.ts\";\nimport { parseContractId } from \"../../utils/address.ts\";\nimport { bytesToHex, with0x } from \"../../utils/encoding.ts\";\n\nexport type GetMapEntryParams = {\n\tcontract: string; // \"address.name\"\n\tmapName: string;\n\tkey: ClarityValue;\n};\n\nexport async function getMapEntry<T extends ClarityValue = ClarityValue>(\n\tclient: Client,\n\tparams: GetMapEntryParams,\n): Promise<T> {\n\tconst [address, name] = parseContractId(params.contract);\n\tconst serializedKey = with0x(bytesToHex(serializeCVBytes(params.key)));\n\n\tconst data = await client.request(\n\t\t`/v2/map_entry/${address}/${name}/${params.mapName}`,\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tbody: serializedKey,\n\t\t},\n\t);\n\n\tif (typeof data?.data !== \"string\") {\n\t\tthrow new MalformedResponseError(\n\t\t\t`getMapEntry: /v2/map_entry/${address}/${name}/${params.mapName} response is missing \"data\"`,\n\t\t);\n\t}\n\treturn deserializeCVBytes<T>(data.data);\n}\n",
|
|
9
|
+
"import type { Client } from \"../../clients/types.ts\";\n\nexport type GetNonceParams = {\n\taddress: string;\n};\n\nexport type GetNonceResult = {\n\tnonce: bigint;\n\tpossibleNextNonce: bigint;\n};\n\nexport async function getNonce(\n\tclient: Client,\n\tparams: GetNonceParams,\n): Promise<bigint> {\n\tconst data = await client.request(`/v2/accounts/${params.address}`, {\n\t\tmethod: \"GET\",\n\t});\n\tconst nonce = (data as { nonce?: unknown })?.nonce;\n\tif (typeof nonce !== \"number\" && typeof nonce !== \"string\") {\n\t\tthrow new Error(\n\t\t\t`getNonce: unexpected /v2/accounts response for ${params.address} (missing numeric nonce)`,\n\t\t);\n\t}\n\treturn BigInt(nonce);\n}\n",
|
|
10
|
+
"import { BaseError } from \"./base.ts\";\n\n/**\n * Thrown by the HTTP transport when a request, headers and body included,\n * does not finish inside `timeout`. Carries enough to tell which endpoint\n * stalled and on which retry attempt. A caller-supplied `signal` abort is\n * NOT a timeout: that rejects with the signal's own reason and never retries.\n */\nexport class TimeoutError extends BaseError {\n\toverride name = \"TimeoutError\";\n\tmethod: string;\n\turl: string;\n\ttimeout: number;\n\t/** Zero-based attempt index at which the timeout fired. */\n\tattempt: number;\n\n\tconstructor(params: {\n\t\tmethod: string;\n\t\turl: string;\n\t\ttimeout: number;\n\t\tattempt: number;\n\t}) {\n\t\tsuper(\n\t\t\t`${params.method} ${params.url} did not complete within ${params.timeout}ms (attempt ${params.attempt + 1})`,\n\t\t);\n\t\tthis.method = params.method;\n\t\tthis.url = params.url;\n\t\tthis.timeout = params.timeout;\n\t\tthis.attempt = params.attempt;\n\t}\n}\n",
|
|
11
|
+
"import { HttpRequestError } from \"../errors/http.ts\";\nimport { TimeoutError } from \"../errors/transport.ts\";\nimport type {\n\tRequestFn,\n\tRequestOptions,\n\tTransport,\n\tTransportConfig,\n} from \"./types.ts\";\n\n/** Bind a request function into a transport. The exposed `config` never\n * carries `apiKey`: the key lives in the request closure, so logging a\n * client or inspecting `client.transport.config` does not print it. */\nexport function createTransport(\n\ttype: string,\n\tconfig: TransportConfig & { request: RequestFn },\n): Transport {\n\tconst { request, apiKey: _apiKey, ...exposed } = config;\n\treturn {\n\t\ttype,\n\t\trequest,\n\t\tconfig: exposed,\n\t};\n}\n\n/** Longest response body kept on `HttpRequestError.details`. The body is\n * untrusted and lands in `error.message`, so a runaway HTML page or a\n * hostile reply must not become a multi-megabyte log line. */\nexport const MAX_ERROR_DETAILS_BYTES = 4096;\n\nfunction capDetails(body: string | undefined): string | undefined {\n\tif (body === undefined) return undefined;\n\tconst bytes = new TextEncoder().encode(body);\n\tif (bytes.length <= MAX_ERROR_DETAILS_BYTES) return body;\n\tconst head = new TextDecoder().decode(\n\t\tbytes.subarray(0, MAX_ERROR_DETAILS_BYTES),\n\t);\n\treturn `${head}... [truncated ${bytes.length - MAX_ERROR_DETAILS_BYTES} bytes]`;\n}\n\n/** 5xx and 429 are transient and worth a retry. Every other status is not. */\nfunction isRetryableStatus(status: number): boolean {\n\treturn status === 429 || status >= 500;\n}\n\n/** Retry-After above this cap falls back to the normal backoff: a node\n * asking for minutes should not stall a transport-level retry. */\nconst MAX_RETRY_AFTER_MS = 60_000;\n\n/** Parse a `Retry-After` header (delta-seconds or HTTP-date) into a delay,\n * or undefined when absent/unparseable/over the cap. */\nfunction retryAfterMs(response: Response): number | undefined {\n\tconst value = response.headers.get(\"Retry-After\");\n\tif (!value) return undefined;\n\tconst seconds = Number(value);\n\tconst ms = Number.isFinite(seconds)\n\t\t? seconds * 1000\n\t\t: Date.parse(value) - Date.now();\n\tif (!Number.isFinite(ms) || ms < 0 || ms > MAX_RETRY_AFTER_MS)\n\t\treturn undefined;\n\treturn ms;\n}\n\nfunction abortReason(signal: AbortSignal): Error {\n\tconst reason = signal.reason;\n\tif (reason instanceof Error) return reason;\n\treturn new DOMException(\n\t\ttypeof reason === \"string\" ? reason : \"The operation was aborted\",\n\t\t\"AbortError\",\n\t);\n}\n\n/** Sleep that wakes early (rejecting with the abort reason) when `signal` fires. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) return reject(abortReason(signal));\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(id);\n\t\t\treject(abortReason(signal as AbortSignal));\n\t\t};\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nexport type FetchWithRetryOptions<T> = {\n\t/** Caller-side cancellation. Combined with the timeout; never retried. */\n\tsignal?: AbortSignal;\n\t/**\n\t * Consume the response body inside the timeout window. Defaults to\n\t * returning the `Response` untouched, in which case the caller reads the\n\t * body outside the deadline.\n\t */\n\tread?: (response: Response) => Promise<T>;\n};\n\n/**\n * Fetch with linear backoff on network errors, timeouts, 429 and 5xx.\n *\n * One timeout covers each attempt end to end, headers and body: the timer is\n * armed before `fetch` and cleared once the attempt settles (before any\n * retry sleep, and in `finally`), so a body that never arrives rejects with\n * {@link TimeoutError} rather than hanging the caller, and a rejected fetch\n * never leaves a live timer behind.\n * A caller abort (`signal`) rejects at once with the signal's reason and is\n * not retried.\n */\nexport async function fetchWithRetry<T = Response>(\n\turl: string,\n\toptions: RequestInit,\n\tretryCount: number,\n\tretryDelay: number,\n\ttimeout: number,\n\textra: FetchWithRetryOptions<T> = {},\n): Promise<T> {\n\tconst { signal } = extra;\n\tconst read =\n\t\textra.read ?? (async (response: Response) => response as unknown as T);\n\tconst method = options.method ?? \"GET\";\n\tlet lastError: Error | undefined;\n\n\tfor (let attempt = 0; attempt <= retryCount; attempt++) {\n\t\tif (signal?.aborted) throw abortReason(signal);\n\n\t\tconst controller = new AbortController();\n\t\tlet timedOut = false;\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tcontroller.abort(new TimeoutError({ method, url, timeout, attempt }));\n\t\t}, timeout);\n\t\tconst onCallerAbort = () =>\n\t\t\tcontroller.abort(abortReason(signal as AbortSignal));\n\t\tsignal?.addEventListener(\"abort\", onCallerAbort, { once: true });\n\n\t\t// Rejects the moment the attempt is aborted, whether by the timer or by\n\t\t// the caller, so a body read on a stalled stream cannot outlive the\n\t\t// deadline even when the runtime does not tie the body to the signal.\n\t\tconst aborted = new Promise<never>((_, reject) => {\n\t\t\tif (controller.signal.aborted) return reject(controller.signal.reason);\n\t\t\tcontroller.signal.addEventListener(\n\t\t\t\t\"abort\",\n\t\t\t\t() => reject(controller.signal.reason),\n\t\t\t\t{ once: true },\n\t\t\t);\n\t\t});\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\ttry {\n\t\t\t\tresponse = await Promise.race([\n\t\t\t\t\tfetch(url, { ...options, signal: controller.signal }),\n\t\t\t\t\taborted,\n\t\t\t\t]);\n\t\t\t} catch (error) {\n\t\t\t\tif (signal?.aborted) throw abortReason(signal);\n\t\t\t\tlastError = timedOut\n\t\t\t\t\t? new TimeoutError({ method, url, timeout, attempt })\n\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t? error\n\t\t\t\t\t\t: new Error(String(error));\n\t\t\t\tif (attempt < retryCount) {\n\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\tawait sleep(retryDelay * (attempt + 1), signal);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow lastError;\n\t\t\t}\n\n\t\t\tif (response.ok) {\n\t\t\t\ttry {\n\t\t\t\t\treturn await Promise.race([read(response), aborted]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tresponse.body?.cancel().catch(() => {});\n\t\t\t\t\tif (signal?.aborted) throw abortReason(signal);\n\t\t\t\t\tif (!timedOut) throw error;\n\t\t\t\t\tlastError = new TimeoutError({ method, url, timeout, attempt });\n\t\t\t\t\tif (attempt < retryCount) {\n\t\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\t\tawait sleep(retryDelay * (attempt + 1), signal);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow lastError;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst retryable = isRetryableStatus(response.status);\n\t\t\tif (!retryable || attempt === retryCount) {\n\t\t\t\tconst body = await Promise.race([\n\t\t\t\t\tresponse.text().catch(() => undefined),\n\t\t\t\t\taborted.catch(() => undefined),\n\t\t\t\t]);\n\t\t\t\tthrow new HttpRequestError(response.status, {\n\t\t\t\t\tdetails: capDetails(body),\n\t\t\t\t\turl,\n\t\t\t\t\tmethod,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlastError = new HttpRequestError(response.status, { url, method });\n\t\t\t// A server-sent Retry-After (429/503) overrides the linear backoff.\n\t\t\tconst delay = retryAfterMs(response) ?? retryDelay * (attempt + 1);\n\t\t\tresponse.body?.cancel().catch(() => {});\n\t\t\t// The attempt is over: a Retry-After longer than `timeout` must not\n\t\t\t// let the attempt timer fire mid-sleep and flag a timeout that never\n\t\t\t// happened.\n\t\t\tclearTimeout(timeoutId);\n\t\t\tawait sleep(delay, signal);\n\t\t} finally {\n\t\t\tclearTimeout(timeoutId);\n\t\t\tsignal?.removeEventListener(\"abort\", onCallerAbort);\n\t\t}\n\t}\n\n\tthrow lastError ?? new Error(\"Request failed\");\n}\n\n/** Decode a 2xx body: JSON when the content type says so, text otherwise. */\nexport async function readBody(response: Response): Promise<unknown> {\n\tconst contentType = response.headers.get(\"content-type\") ?? \"\";\n\tif (contentType.includes(\"application/json\")) {\n\t\treturn response.json();\n\t}\n\treturn response.text();\n}\n\nexport function buildRequestFn(\n\tbaseUrl: string,\n\tconfig: TransportConfig,\n): RequestFn {\n\tconst {\n\t\ttimeout = 30_000,\n\t\tretryCount = 3,\n\t\tretryDelay = 150,\n\t\tfetchOptions = {},\n\t\tapiKey,\n\t} = config;\n\n\treturn async (path: string, options?: RequestOptions) => {\n\t\tconst url = `${baseUrl.replace(/\\/$/, \"\")}${path}`;\n\t\tconst headers: Record<string, string> = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t...(fetchOptions.headers as Record<string, string>),\n\t\t\t...options?.headers,\n\t\t};\n\n\t\tif (apiKey) {\n\t\t\theaders[\"x-api-key\"] = apiKey;\n\t\t}\n\n\t\tconst init: RequestInit = {\n\t\t\t...fetchOptions,\n\t\t\tmethod: options?.method ?? \"GET\",\n\t\t\theaders,\n\t\t};\n\n\t\tif (options?.body !== undefined) {\n\t\t\tinit.body = JSON.stringify(options.body);\n\t\t}\n\n\t\treturn fetchWithRetry(\n\t\t\turl,\n\t\t\tinit,\n\t\t\toptions?.retryCount ?? retryCount,\n\t\t\tretryDelay,\n\t\t\ttimeout,\n\t\t\t{ signal: options?.signal, read: readBody },\n\t\t);\n\t};\n}\n",
|
|
12
|
+
"import { deserializeCVBytes } from \"../../clarity/deserialize.ts\";\nimport type { ClarityValue } from \"../../clarity/types.ts\";\nimport type { Client } from \"../../clients/types.ts\";\nimport { HttpRequestError } from \"../../errors/http.ts\";\nimport { buildRequestFn } from \"../../transports/createTransport.ts\";\nimport type { RequestFn } from \"../../transports/types.ts\";\n\n/**\n * Pluggable transaction-status sources for {@link getTransaction} /\n * `waitForTransactionReceipt`.\n *\n * A bare stacks-node has no confirmed-transaction endpoint, so status reads\n * need a host that indexes transactions. Where that data comes from is\n * pluggable, mirroring the nonce sources:\n *\n * - {@link extendedApiSource} — default; `/extended/v1/tx/{txid}` on the\n * client's transport host (Hiro API or any extended-API-compatible host).\n * - {@link indexTxSource}: a Secondlayer instance's\n * `/v1/index/transactions/{txid}`; returns the chain tip in the same\n * response, so N-confirmation waits need no second request.\n */\n\nexport type TransactionStatus =\n\t| \"pending\"\n\t| \"success\"\n\t| \"abort_by_response\"\n\t| \"abort_by_post_condition\"\n\t| \"dropped\";\n\nexport type TransactionReceipt = {\n\ttxid: string;\n\tstatus: TransactionStatus;\n\t/** Anchor block height; absent while pending. */\n\tblockHeight?: number;\n\tblockHash?: string;\n\t/** Decoded Clarity result; absent while pending or when the source omits it. */\n\tresult?: ClarityValue;\n\tresultHex?: string;\n\tevents: unknown[];\n\t/** The source's unnormalized response, for fields the receipt doesn't model. */\n\traw: unknown;\n};\n\nexport type TransactionSnapshot = {\n\t/** `null` when the source has no record of the tx (mempool + chain). */\n\treceipt: TransactionReceipt | null;\n\t/** Chain tip height, when the source knows it (saves a round-trip). */\n\ttip?: number;\n};\n\nexport type TransactionStatusSource = {\n\tget(args: { client: Client; txid: string }): Promise<TransactionSnapshot>;\n\t/**\n\t * True when the source only knows mined transactions and reports\n\t * `receipt: null` for the whole mempool life of a tx. The wait action\n\t * then stretches its dropped-grace window to the full timeout, since\n\t * \"unknown\" cannot mean \"dropped\" until the deadline.\n\t */\n\tcanonicalOnly?: boolean;\n};\n\n/**\n * Thrown when an index-backed source cannot reach a Secondlayer instance\n * because of how it was configured (no URL, a Hiro host, a bare node).\n * Sources that degrade on transient failures let this one through: a\n * misconfiguration would otherwise degrade silently on every read.\n */\nexport class IndexSourceConfigError extends Error {\n\toverride name = \"IndexSourceConfigError\";\n}\n\n/** Hosts that serve Hiro's API, never a Secondlayer instance. */\nfunction isHiroHost(url: string, client: Client): boolean {\n\tlet hostname: string;\n\ttry {\n\t\thostname = new URL(url).hostname;\n\t} catch {\n\t\treturn false;\n\t}\n\tif (hostname === \"hiro.so\" || hostname.endsWith(\".hiro.so\")) return true;\n\tconst defaults = client.chain?.rpcUrls?.default?.http ?? [];\n\treturn defaults.some((d) => {\n\t\ttry {\n\t\t\treturn new URL(d).hostname === hostname && hostname !== \"localhost\";\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\n/**\n * Pick the request function for a Secondlayer index route. With no\n * `baseUrl` the client's transport URL is taken to be the instance and\n * `client.request` carries its retries, timeout and auth; a transport\n * pointed at a Hiro host throws instead of polling routes it cannot serve.\n * A different `baseUrl` gets the transport's retry and timeout policy\n * bound to that host. Only policy crosses over: the transport's `apiKey`\n * and `fetchOptions` were issued for the transport host and never travel\n * to another one.\n */\nexport function indexRequestFn(\n\tclient: Client,\n\tbaseUrl: string | undefined,\n\tsourceName: string,\n): RequestFn {\n\tconst transportUrl = client.transport.config.url?.replace(/\\/$/, \"\");\n\tif (baseUrl === undefined) {\n\t\tif (!transportUrl) {\n\t\t\tthrow new IndexSourceConfigError(\n\t\t\t\t`${sourceName} needs the URL of your Secondlayer instance: pass baseUrl, or use an http() transport pointed at the instance`,\n\t\t\t);\n\t\t}\n\t\tif (isHiroHost(transportUrl, client)) {\n\t\t\tthrow new IndexSourceConfigError(\n\t\t\t\t`${sourceName} reads /v1/index on a Secondlayer instance, and ${transportUrl} is a Hiro host: pass baseUrl with the URL of your instance`,\n\t\t\t);\n\t\t}\n\t\treturn client.request;\n\t}\n\tconst target = baseUrl.replace(/\\/$/, \"\");\n\tif (target === transportUrl) return client.request;\n\tconst { timeout, retryCount, retryDelay } = client.transport.config;\n\treturn buildRequestFn(target, { timeout, retryCount, retryDelay });\n}\n\n/**\n * An instance answers an unknown tx with a JSON 404.\n * A 404 with a non-JSON body comes from a host that does not serve\n * `/v1/index` at all (a bare stacks-node, an unmatched route), so it is a\n * configuration error rather than \"not mined yet\".\n */\nexport function indexNotFound(\n\terror: unknown,\n\tsourceName: string,\n): error is HttpRequestError {\n\tif (!(error instanceof HttpRequestError) || error.status !== 404) {\n\t\treturn false;\n\t}\n\tconst body = error.details;\n\tif (body !== undefined) {\n\t\ttry {\n\t\t\tJSON.parse(body);\n\t\t} catch {\n\t\t\tthrow new IndexSourceConfigError(\n\t\t\t\t`${sourceName} got a non-JSON 404 from ${error.url ?? \"the transport host\"}: it does not serve /v1/index, pass baseUrl with the URL of your Secondlayer instance`,\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction normalizeTxid(txid: string): string {\n\treturn txid.startsWith(\"0x\") ? txid : `0x${txid}`;\n}\n\nfunction decodeResultHex(hex: string | null | undefined): {\n\tresult?: ClarityValue;\n\tresultHex?: string;\n} {\n\tif (!hex) return {};\n\ttry {\n\t\treturn { result: deserializeCVBytes(hex), resultHex: hex };\n\t} catch {\n\t\treturn { resultHex: hex };\n\t}\n}\n\n/** Map a Hiro `tx_status` string onto the receipt vocabulary. */\nfunction normalizeStatus(txStatus: string): TransactionStatus | undefined {\n\tswitch (txStatus) {\n\t\tcase \"pending\":\n\t\tcase \"success\":\n\t\tcase \"abort_by_response\":\n\t\tcase \"abort_by_post_condition\":\n\t\t\treturn txStatus;\n\t\tdefault:\n\t\t\treturn txStatus.startsWith(\"dropped\") ? \"dropped\" : undefined;\n\t}\n}\n\n/**\n * Default source: `GET /extended/v1/tx/{txid}` via the client's transport.\n * Requires a host that serves Hiro's extended API (a bare stacks-node does\n * not). Does not report the chain tip — the wait action fetches it separately\n * when `confirmations > 1`.\n */\nexport function extendedApiSource(): TransactionStatusSource {\n\treturn {\n\t\tasync get({ client, txid }) {\n\t\t\tlet data: Awaited<ReturnType<Client[\"request\"]>>;\n\t\t\ttry {\n\t\t\t\tdata = await client.request(\n\t\t\t\t\t`/extended/v1/tx/${encodeURIComponent(normalizeTxid(txid))}`,\n\t\t\t\t\t{ method: \"GET\" },\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof HttpRequestError && error.status === 404) {\n\t\t\t\t\treturn { receipt: null };\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tconst txStatus =\n\t\t\t\ttypeof data?.tx_status === \"string\" ? data.tx_status : undefined;\n\t\t\tif (!txStatus) return { receipt: null }; // unexpected shape\n\n\t\t\tconst status = normalizeStatus(txStatus);\n\t\t\tif (!status) return { receipt: null };\n\n\t\t\treturn {\n\t\t\t\treceipt: {\n\t\t\t\t\ttxid: normalizeTxid(txid),\n\t\t\t\t\tstatus,\n\t\t\t\t\tblockHeight:\n\t\t\t\t\t\ttypeof data.block_height === \"number\" && data.block_height > 0\n\t\t\t\t\t\t\t? data.block_height\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\tblockHash: data.block_hash ?? undefined,\n\t\t\t\t\t...decodeResultHex(data.tx_result?.hex),\n\t\t\t\t\tevents: Array.isArray(data.events) ? data.events : [],\n\t\t\t\t\traw: data,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\nexport type IndexTxSourceParams = {\n\t/**\n\t * URL of your Secondlayer instance. Without it the client's transport\n\t * URL is assumed to be the instance: a transport on a Hiro host throws\n\t * up front, and a host that answers `/v1/index` with a non-JSON 404\n\t * (a bare stacks-node) throws on the first read. Pass it whenever the\n\t * transport is not the instance.\n\t */\n\tbaseUrl?: string;\n\t/** Instance token, sent as `Authorization: Bearer`. */\n\tapiKey?: string;\n};\n\n/**\n * Source backed by a Secondlayer instance's `/v1/index/transactions/{txid}`.\n * The response embeds the chain tip, so N-confirmation math needs no extra\n * request. Requests go through the transport layer: same retries, timeout\n * and typed errors as every other read. The index only returns canonical\n * (mined) transactions; while a tx is in the mempool this source reports\n * `receipt: null`, and the wait action's grace window carries it until\n * inclusion.\n */\nexport function indexTxSource(\n\tparams: IndexTxSourceParams = {},\n): TransactionStatusSource {\n\tconst headers = params.apiKey\n\t\t? { authorization: `Bearer ${params.apiKey}` }\n\t\t: undefined;\n\n\treturn {\n\t\tcanonicalOnly: true,\n\t\tasync get({ client, txid }) {\n\t\t\tconst request = indexRequestFn(client, params.baseUrl, \"indexTxSource\");\n\t\t\tlet data: {\n\t\t\t\ttransaction?: {\n\t\t\t\t\ttx_id: string;\n\t\t\t\t\tblock_height: number;\n\t\t\t\t\tstatus: string;\n\t\t\t\t\tcontract_call?: { result_hex: string | null };\n\t\t\t\t};\n\t\t\t\ttip?: { block_height: number };\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tdata = await request(`/v1/index/transactions/${normalizeTxid(txid)}`, {\n\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (indexNotFound(error, \"indexTxSource\")) return { receipt: null };\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst tx = data.transaction;\n\t\t\tconst tip = data.tip?.block_height;\n\t\t\tif (!tx) return { receipt: null, tip };\n\n\t\t\tconst status = normalizeStatus(tx.status) ?? \"success\";\n\t\t\treturn {\n\t\t\t\treceipt: {\n\t\t\t\t\ttxid: normalizeTxid(tx.tx_id),\n\t\t\t\t\tstatus,\n\t\t\t\t\tblockHeight: tx.block_height,\n\t\t\t\t\t...decodeResultHex(tx.contract_call?.result_hex),\n\t\t\t\t\tevents: [],\n\t\t\t\t\traw: data,\n\t\t\t\t},\n\t\t\t\ttip,\n\t\t\t};\n\t\t},\n\t};\n}\n",
|
|
13
|
+
"import type { Client } from \"../../clients/types.ts\";\nimport {\n\ttype TransactionReceipt,\n\ttype TransactionStatusSource,\n\textendedApiSource,\n} from \"./txSources.ts\";\n\nexport type GetTransactionParams = {\n\ttxid: string;\n\t/** Where to read status from. Defaults to {@link extendedApiSource}. */\n\tsource?: TransactionStatusSource;\n};\n\n/**\n * Fetch a transaction's receipt (status, block info, decoded result).\n * Returns `null` when the source has no record of the transaction.\n */\nexport async function getTransaction(\n\tclient: Client,\n\tparams: GetTransactionParams,\n): Promise<TransactionReceipt | null> {\n\tconst source = params.source ?? extendedApiSource();\n\tconst { receipt } = await source.get({ client, txid: params.txid });\n\treturn receipt;\n}\n",
|
|
14
|
+
"import type { Client } from \"../../clients/types.ts\";\nimport {\n\tTransactionAbortedError,\n\tTransactionDroppedError,\n\tWaitForTransactionTimeoutError,\n} from \"../../errors/transaction.ts\";\nimport { getBlockHeight } from \"./getBlockHeight.ts\";\nimport {\n\ttype TransactionReceipt,\n\ttype TransactionStatusSource,\n\textendedApiSource,\n} from \"./txSources.ts\";\n\nexport type WaitForTransactionReceiptParams = {\n\ttxid: string;\n\t/** Anchor-block confirmations to wait for. Default 1 (mined). */\n\tconfirmations?: number;\n\t/** Give up after this many ms. Default 180_000 (3 min). */\n\ttimeout?: number;\n\t/** Delay between status polls, ms. Default 3_000. */\n\tpollingInterval?: number;\n\t/**\n\t * How long a tx may be unknown to the source before it counts as dropped,\n\t * ms. Covers broadcast propagation lag. Default 30_000, or the full\n\t * `timeout` for a canonical-only source (one that cannot see the\n\t * mempool, so \"unknown\" means \"not mined yet\" until the deadline).\n\t */\n\tdroppedGracePeriod?: number;\n\t/** Where to read status from. Defaults to {@link extendedApiSource}. */\n\tsource?: TransactionStatusSource;\n};\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/**\n * Poll until a transaction is mined with N confirmations, then return its\n * receipt.\n *\n * Rejects with {@link TransactionAbortedError} when the tx mines but aborts\n * (`abort_by_response` / `abort_by_post_condition`) — the receipt is attached.\n * Rejects with {@link TransactionDroppedError} when the tx leaves the mempool\n * unmined or stays unknown past `droppedGracePeriod`, and\n * {@link WaitForTransactionTimeoutError} at `timeout`.\n *\n * Reorg-tolerant: every cycle re-reads the receipt (block height may change)\n * and recomputes confirmations from the current tip.\n */\nexport async function waitForTransactionReceipt(\n\tclient: Client,\n\tparams: WaitForTransactionReceiptParams,\n): Promise<TransactionReceipt> {\n\tconst {\n\t\ttxid,\n\t\tconfirmations = 1,\n\t\ttimeout = 180_000,\n\t\tpollingInterval = 3_000,\n\t} = params;\n\tconst source = params.source ?? extendedApiSource();\n\tconst droppedGracePeriod =\n\t\tparams.droppedGracePeriod ?? (source.canonicalOnly ? timeout : 30_000);\n\n\tconst startedAt = Date.now();\n\tlet unknownSince: number | null = null;\n\tlet everPending = false;\n\n\twhile (true) {\n\t\tconst snapshot = await source.get({ client, txid });\n\t\tconst receipt = snapshot.receipt;\n\n\t\tif (receipt === null) {\n\t\t\t// Unknown to the source: propagation lag, a canonical-only source\n\t\t\t// looking at a mempool tx, or a genuine drop. Only the grace clock\n\t\t\t// distinguishes them.\n\t\t\tunknownSince ??= Date.now();\n\t\t\tif (Date.now() - unknownSince >= droppedGracePeriod) {\n\t\t\t\tthrow new TransactionDroppedError(\n\t\t\t\t\teverPending\n\t\t\t\t\t\t? `Transaction ${txid} left the mempool without being mined`\n\t\t\t\t\t\t: `Transaction ${txid} was never observed by the status source`,\n\t\t\t\t\t{ txid },\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tunknownSince = null;\n\n\t\t\tswitch (receipt.status) {\n\t\t\t\tcase \"dropped\":\n\t\t\t\t\tthrow new TransactionDroppedError(\n\t\t\t\t\t\t`Transaction ${txid} was dropped from the mempool`,\n\t\t\t\t\t\t{ txid },\n\t\t\t\t\t);\n\t\t\t\tcase \"abort_by_response\":\n\t\t\t\tcase \"abort_by_post_condition\":\n\t\t\t\t\tthrow new TransactionAbortedError(\n\t\t\t\t\t\t`Transaction ${txid} aborted (${receipt.status})`,\n\t\t\t\t\t\t{ receipt },\n\t\t\t\t\t);\n\t\t\t\tcase \"pending\":\n\t\t\t\t\teverPending = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"success\": {\n\t\t\t\t\tif (confirmations <= 1) return receipt;\n\t\t\t\t\tif (receipt.blockHeight !== undefined) {\n\t\t\t\t\t\tconst tip = snapshot.tip ?? (await getBlockHeight(client));\n\t\t\t\t\t\tif (tip - receipt.blockHeight + 1 >= confirmations) return receipt;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (Date.now() - startedAt >= timeout) {\n\t\t\tthrow new WaitForTransactionTimeoutError(\n\t\t\t\t`Timed out after ${timeout}ms waiting for transaction ${txid}`,\n\t\t\t\t{ txid },\n\t\t\t);\n\t\t}\n\t\tawait sleep(pollingInterval);\n\t}\n}\n",
|
|
15
|
+
"import { getTransaction } from \"../../actions/public/getTransaction.ts\";\nimport type { TransactionReceipt } from \"../../actions/public/txSources.ts\";\nimport { waitForTransactionReceipt } from \"../../actions/public/waitForTransactionReceipt.ts\";\nimport type { Client } from \"../../clients/types.ts\";\nimport { HttpRequestError } from \"../../errors/http.ts\";\nimport { BroadcastError } from \"../../errors/transaction.ts\";\nimport { TimeoutError } from \"../../errors/transport.ts\";\nimport { getTransactionId } from \"../../transactions/signer.ts\";\nimport type { StacksTransaction } from \"../../transactions/types.ts\";\nimport { serializeTransaction } from \"../../transactions/wire/serialize.ts\";\nimport { bytesToHex } from \"../../utils/encoding.ts\";\n\nexport type SendTransactionParams = {\n\ttransaction: StacksTransaction;\n\tattachment?: Uint8Array | string;\n\t/**\n\t * Wait for the transaction to be mined before returning. `true` waits for\n\t * 1 confirmation; a number waits for that many. The receipt lands on the\n\t * result. Rejects if the tx aborts, is dropped, or the wait times out.\n\t */\n\twait?: boolean | number;\n};\n\nexport type SendTransactionResult = {\n\ttxid: string;\n\t/** Present when `wait` was requested. */\n\treceipt?: TransactionReceipt;\n};\n\n/** Broadcast a signed transaction to the network */\nexport async function sendTransaction(\n\tclient: Client,\n\tparams: SendTransactionParams,\n): Promise<SendTransactionResult> {\n\tconst hex = bytesToHex(serializeTransaction(params.transaction));\n\n\tconst body: Record<string, string> = { tx: hex };\n\tif (params.attachment) {\n\t\tbody.attachment =\n\t\t\ttypeof params.attachment === \"string\"\n\t\t\t\t? params.attachment\n\t\t\t\t: bytesToHex(params.attachment);\n\t}\n\n\t// A stacks-node responds to a rejected broadcast with a non-2xx status\n\t// (the transport throws for that) but the rejection JSON, the thing this\n\t// function actually needs, rides along as the error body. The broadcast\n\t// is never retried at the transport level: the node may already hold the\n\t// transaction, and a re-send would surface as a nonce conflict.\n\tlet data: Awaited<ReturnType<Client[\"request\"]>>;\n\ttry {\n\t\tdata = await client.request(\"/v2/transactions\", {\n\t\t\tmethod: \"POST\",\n\t\t\tbody,\n\t\t\tretryCount: 0,\n\t\t});\n\t} catch (error) {\n\t\tif (error instanceof HttpRequestError && error.details) {\n\t\t\ttry {\n\t\t\t\tdata = JSON.parse(error.details);\n\t\t\t} catch {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} else if (error instanceof TimeoutError) {\n\t\t\t// The deadline passed after the node may have accepted the tx. Ask\n\t\t\t// before surfacing: a known tx means the broadcast succeeded.\n\t\t\tconst txid = getTransactionId(params.transaction);\n\t\t\tconst receipt = await getTransaction(client, { txid }).catch(() => null);\n\t\t\tif (receipt === null) throw error;\n\t\t\tdata = { txid };\n\t\t} else {\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tif (data.error) {\n\t\tthrow new BroadcastError(data.reason ?? data.error, {\n\t\t\treason: data.reason,\n\t\t\treasonData: data.reason_data,\n\t\t\ttxid: data.txid ?? getTransactionId(params.transaction),\n\t\t});\n\t}\n\n\tconst txid =\n\t\ttypeof data === \"string\"\n\t\t\t? data.replace(/\"/g, \"\")\n\t\t\t: (data.txid ?? getTransactionId(params.transaction));\n\n\tif (params.wait) {\n\t\tconst confirmations = params.wait === true ? 1 : params.wait;\n\t\tconst receipt = await waitForTransactionReceipt(client, {\n\t\t\ttxid,\n\t\t\tconfirmations,\n\t\t});\n\t\treturn { txid, receipt };\n\t}\n\n\treturn { txid };\n}\n",
|
|
16
|
+
"import type { Client } from \"../../clients/types.ts\";\nimport { BroadcastError } from \"../../errors/transaction.ts\";\nimport type { StacksTransaction } from \"../../transactions/types.ts\";\nimport { getNonce } from \"../public/getNonce.ts\";\nimport { sendTransaction } from \"./sendTransaction.ts\";\n\n/**\n * Provides the confirmed on-chain nonce floor for an address.\n *\n * The default {@link jsonRpcSource} reads the configured node's `/v2/accounts`\n * endpoint — node-agnostic, no Hiro dependency. Other sources (mempool-aware,\n * first-party Index) can be swapped in without touching the manager.\n */\nexport type NonceManagerSource = {\n\tget(params: { client: Client; address: string }): Promise<bigint>;\n};\n\n/**\n * Holds per-address allocation state and hands out the next nonce.\n *\n * `reserve` MUST be atomic per `key`: two concurrent reservations for the same\n * key must never return the same value. The in-memory {@link memoryStore}\n * serializes with a per-key promise chain; a persisted store (Redis `INCR`,\n * Postgres `SELECT ... FOR UPDATE`) becomes the cross-process lock for the\n * multi-builder / smart-wallet-as-a-service case.\n */\nexport type NonceStore = {\n\t/**\n\t * Reserve the next nonce for `key`. `getFloor` reads the confirmed on-chain\n\t * nonce; it is only invoked when the store has no tracked value (cold start\n\t * or after {@link NonceStore.reset}).\n\t */\n\treserve(key: string, getFloor: () => Promise<bigint>): Promise<bigint>;\n\t/** Forget tracked state for `key` so the next reserve re-syncs from the floor. */\n\treset(key: string): void | Promise<void>;\n\t/**\n\t * Hand back a nonce that {@link NonceStore.reserve} issued but that never\n\t * reached the mempool. Rolls the counter back ONLY when `nonce` is the\n\t * most recently issued value (`next - 1`); a stale release, or one that\n\t * races a newer reservation, is a no-op. Optional: stores that omit it\n\t * leave the gap for {@link reconcileNonce} to heal.\n\t */\n\trelease?(key: string, nonce: bigint): void | Promise<void>;\n\t/**\n\t * Return the next nonce that {@link NonceStore.reserve} would hand out for\n\t * `key` WITHOUT consuming it, or `undefined` if `key` is untracked. Used by\n\t * {@link reconcileNonce} to detect drift. Optional — stores that omit it\n\t * simply opt out of reconciliation.\n\t */\n\tpeek?(key: string): Promise<bigint | undefined> | bigint | undefined;\n};\n\n/** Allocates mempool-safe sequential nonces across rapid broadcasts from one account. */\nexport type NonceManager = {\n\tconsume(params: { client: Client; address: string }): Promise<bigint>;\n\treset(params: { client: Client; address: string }): void | Promise<void>;\n\t/**\n\t * Give back a nonce from {@link NonceManager.consume} whose transaction\n\t * was never accepted by the node. No-op unless it is the latest issued.\n\t */\n\trelease(params: {\n\t\tclient: Client;\n\t\taddress: string;\n\t\tnonce: bigint;\n\t}): void | Promise<void>;\n\t/** Next nonce that {@link NonceManager.consume} would return without consuming it, or `undefined` if untracked. */\n\tpeek(params: {\n\t\tclient: Client;\n\t\taddress: string;\n\t}): Promise<bigint | undefined>;\n};\n\nexport type CreateNonceManagerParams = {\n\tsource?: NonceManagerSource;\n\tstore?: NonceStore;\n};\n\n/** Confirmed-nonce source backed by the configured node's `/v2/accounts` RPC (no Hiro dependency). */\nexport function jsonRpcSource(): NonceManagerSource {\n\treturn {\n\t\tget: ({ client, address }) => getNonce(client, { address }),\n\t};\n}\n\n/**\n * In-memory, single-process store. Tracks the next nonce per key and serializes\n * concurrent reservations with a per-key promise chain.\n *\n * Correct only within one process — swap in a persisted store for multi-process\n * deployments that share a signing key.\n */\nexport function memoryStore(): NonceStore {\n\tconst next = new Map<string, bigint>();\n\tconst locks = new Map<string, Promise<unknown>>();\n\n\tfunction withLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n\t\tconst prev = locks.get(key) ?? Promise.resolve();\n\t\t// Chain onto the prior reservation regardless of how it settled, so a\n\t\t// rejected reserve never wedges the key.\n\t\tconst run = prev.then(fn, fn);\n\t\tlocks.set(\n\t\t\tkey,\n\t\t\trun.catch(() => {}),\n\t\t);\n\t\treturn run;\n\t}\n\n\treturn {\n\t\treserve(key, getFloor) {\n\t\t\treturn withLock(key, async () => {\n\t\t\t\tlet current = next.get(key);\n\t\t\t\tif (current === undefined) current = await getFloor();\n\t\t\t\tnext.set(key, current + 1n);\n\t\t\t\treturn current;\n\t\t\t});\n\t\t},\n\t\treset(key) {\n\t\t\tnext.delete(key);\n\t\t},\n\t\trelease(key, nonce) {\n\t\t\treturn withLock(key, async () => {\n\t\t\t\tif (next.get(key) === nonce + 1n) next.set(key, nonce);\n\t\t\t});\n\t\t},\n\t\tpeek(key) {\n\t\t\treturn next.get(key);\n\t\t},\n\t};\n}\n\nfunction nonceKey(client: Client, address: string): string {\n\treturn `${client.chain?.id ?? \"stacks\"}:${address}`;\n}\n\n/**\n * Create a nonce manager that floors on a confirmed-nonce {@link NonceManagerSource}\n * and increments a {@link NonceStore} on every {@link NonceManager.consume}.\n *\n * Defaults to {@link jsonRpcSource} + {@link memoryStore} — node-agnostic,\n * single-process, zero external dependencies.\n */\nexport function createNonceManager(\n\tparams: CreateNonceManagerParams = {},\n): NonceManager {\n\tconst source = params.source ?? jsonRpcSource();\n\tconst store = params.store ?? memoryStore();\n\n\treturn {\n\t\tconsume({ client, address }) {\n\t\t\treturn store.reserve(nonceKey(client, address), () =>\n\t\t\t\tsource.get({ client, address }),\n\t\t\t);\n\t\t},\n\t\treset({ client, address }) {\n\t\t\treturn store.reset(nonceKey(client, address));\n\t\t},\n\t\trelease({ client, address, nonce }) {\n\t\t\treturn store.release?.(nonceKey(client, address), nonce);\n\t\t},\n\t\tasync peek({ client, address }) {\n\t\t\treturn store.peek?.(nonceKey(client, address));\n\t\t},\n\t};\n}\n\n/** Resolve the next nonce via the client's nonce manager, falling back to a confirmed read. */\nexport async function resolveNonce(\n\tclient: Client,\n\taddress: string,\n): Promise<bigint> {\n\tif (client.nonceManager)\n\t\treturn client.nonceManager.consume({ client, address });\n\treturn getNonce(client, { address });\n}\n\n/**\n * Return `nonce` to the client's nonce manager after a send that never\n * reached the mempool. No-op without a manager. Never throws: a failed\n * release must not mask the error that caused it.\n */\nexport async function releaseNonce(\n\tclient: Client,\n\taddress: string,\n\tnonce: bigint,\n): Promise<void> {\n\tif (!client.nonceManager) return;\n\ttry {\n\t\tawait client.nonceManager.release({ client, address, nonce });\n\t} catch {\n\t\t// The store is unreachable; the reconciler heals the gap later.\n\t}\n}\n\nexport type ReconcileNonceParams = {\n\tclient: Client;\n\taddress: string;\n\t/** Authoritative (ideally mempool-aware) source to reconcile against. */\n\tsource: NonceManagerSource;\n\t/**\n\t * Allow resetting DOWNWARD when the source's next nonce is below what the\n\t * store tracks — i.e. a previously-allocated tx is no longer pending or\n\t * confirmed (dropped/GC'd), so its nonce should be reused. Default `true`.\n\t *\n\t * Downward resets rely on `source` being current: with a go-forward mempool\n\t * source that lags broadcast, run reconciliation on an interval comfortably\n\t * longer than mempool propagation so a still-missing tx is genuinely dropped.\n\t * Set `false` for upward-only reconciliation (always safe).\n\t */\n\tdownward?: boolean;\n};\n\nexport type ReconcileNonceResult = {\n\t/** Whether the manager was reset (drift detected). */\n\treset: boolean;\n\t/** Authoritative next nonce from `source`. */\n\tauthoritative: bigint;\n\t/** Next nonce the store tracked, or `undefined` if untracked. */\n\ttracked: bigint | undefined;\n};\n\n/**\n * Reconcile a tracked nonce against an authoritative source, healing silent\n * drift that produces no broadcast error (a dropped/GC'd mempool tx leaving the\n * counter overshot, or the chain advancing past the local view).\n *\n * When the source's next nonce differs from the tracked value, the manager is\n * {@link NonceManager.reset}; the next `consume` re-seeds from `source`. A no-op\n * if the store is untracked or does not implement `peek`.\n */\nexport async function reconcileNonce(\n\tmanager: NonceManager,\n\tparams: ReconcileNonceParams,\n): Promise<ReconcileNonceResult> {\n\tconst { client, address, source } = params;\n\tconst downward = params.downward ?? true;\n\n\tconst authoritative = await source.get({ client, address });\n\tconst tracked = await manager.peek({ client, address });\n\n\tif (tracked === undefined || authoritative === tracked) {\n\t\treturn { reset: false, authoritative, tracked };\n\t}\n\tif (authoritative < tracked && !downward) {\n\t\treturn { reset: false, authoritative, tracked };\n\t}\n\n\tawait manager.reset({ client, address });\n\treturn { reset: true, authoritative, tracked };\n}\n\nexport type StartNonceReconcilerParams = {\n\tclient: Client;\n\taddresses: string[];\n\tsource: NonceManagerSource;\n\t/** Reconcile interval in ms. Default 60_000. Keep well above mempool propagation. */\n\tintervalMs?: number;\n\tdownward?: boolean;\n\t/** Per-address callback after each reconcile (observability). */\n\tonReconcile?: (address: string, result: ReconcileNonceResult) => void;\n\t/** Per-address error callback; reconciliation continues on the next tick. */\n\tonError?: (address: string, error: unknown) => void;\n\t/** Optional test clock. If provided, the reconciler advances time via\n\t * `clock.advance(ms)` instead of real `setInterval`. */\n\tclock?: {\n\t\tadvance: (ms: number) => Promise<void>;\n\t\tnow: () => number;\n\t};\n};\n\n/**\n * Run {@link reconcileNonce} on a timer for a set of addresses.\n *\n * SINGLE-WRITER: run this in exactly ONE process. With a shared persisted store,\n * a reconciler resetting the counter while other workers allocate is racy — keep\n * reconciliation on one designated process and let the others only allocate.\n *\n * Returns a handle; call `stop()` to clear the timer.\n */\nexport function startNonceReconciler(\n\tmanager: NonceManager,\n\tparams: StartNonceReconcilerParams,\n): { stop: () => void } {\n\tconst { client, addresses, source, clock } = params;\n\tconst intervalMs = params.intervalMs ?? 60_000;\n\tlet running = true;\n\n\tconst tick = async () => {\n\t\tif (!running) return;\n\t\tfor (const address of addresses) {\n\t\t\ttry {\n\t\t\t\tconst result = await reconcileNonce(manager, {\n\t\t\t\t\tclient,\n\t\t\t\t\taddress,\n\t\t\t\t\tsource,\n\t\t\t\t\tdownward: params.downward,\n\t\t\t\t});\n\t\t\t\tparams.onReconcile?.(address, result);\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tparams.onError?.(address, error);\n\t\t\t\t} catch {\n\t\t\t\t\t// A throwing onError callback must not abort the reconcile loop\n\t\t\t\t\t// or surface as an unhandled rejection on the interval timer.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (running && clock) {\n\t\t\tawait clock.advance(intervalMs);\n\t\t\ttick();\n\t\t}\n\t};\n\n\tif (clock) {\n\t\ttick();\n\t\treturn {\n\t\t\tstop: () => {\n\t\t\t\trunning = false;\n\t\t\t},\n\t\t};\n\t}\n\n\tconst timer = setInterval(tick, intervalMs);\n\t// Don't keep the event loop alive solely for reconciliation (Node/Bun).\n\t(timer as { unref?: () => void }).unref?.();\n\n\treturn {\n\t\tstop: () => clearInterval(timer),\n\t};\n}\n\n/** True when a broadcast was rejected for a nonce conflict (`ConflictingNonceInMempool`, `BadNonce`). */\nexport function isNonceConflictError(error: unknown): boolean {\n\tif (!(error instanceof BroadcastError)) return false;\n\tif (\n\t\terror.reason === \"ConflictingNonceInMempool\" ||\n\t\terror.reason === \"BadNonce\"\n\t) {\n\t\treturn true;\n\t}\n\t// Typed reason present but not nonce-related — trust it over the message\n\t// (e.g. a FeeTooLow message mentioning \"nonce\" must not trigger a reset).\n\tif (error.reason !== undefined) return false;\n\t// No structured reason (older nodes/proxies) — fall back to message match.\n\treturn error.message.toLowerCase().includes(\"nonce\");\n}\n\n/**\n * Broadcast a signed transaction; on a nonce-conflict rejection, reset the\n * manager so the next build re-syncs to the confirmed floor.\n */\nexport async function broadcastWithNonceReset(\n\tclient: Client,\n\tparams: { transaction: StacksTransaction; address: string },\n): Promise<string> {\n\ttry {\n\t\tconst result = await sendTransaction(client, {\n\t\t\ttransaction: params.transaction,\n\t\t});\n\t\treturn result.txid;\n\t} catch (error) {\n\t\tif (client.nonceManager && isNonceConflictError(error)) {\n\t\t\tawait client.nonceManager.reset({ client, address: params.address });\n\t\t}\n\t\tthrow error;\n\t}\n}\n",
|
|
17
|
+
"import type { ProviderAccount } from \"../../accounts/types.ts\";\nimport type { Account, Client } from \"../../clients/types.ts\";\nimport { HttpRequestError } from \"../../errors/http.ts\";\nimport type { StacksTransaction } from \"../../transactions/types.ts\";\nimport {\n\tclearTxCache,\n\tserializeTransaction,\n} from \"../../transactions/wire/serialize.ts\";\nimport type { IntegerType } from \"../../utils/encoding.ts\";\nimport { intToBigInt } from \"../../utils/encoding.ts\";\nimport { estimateFee } from \"../public/estimateFee.ts\";\n\nexport function isProviderAccount(\n\taccount: Account,\n): account is ProviderAccount {\n\treturn account.type === \"provider\";\n}\n\n/**\n * Named fee tiers. `'low' | 'mid' | 'high'` map to the node's three fee\n * estimations; `'min'` is the node's minimum relay fee — 1 uSTX per byte of\n * the serialized transaction, computable offline.\n */\nexport type FeeTier = \"min\" | \"low\" | \"mid\" | \"high\";\n\n/** Fee input accepted by wallet actions: an explicit amount or a named tier. */\nexport type FeeParam = IntegerType | FeeTier;\n\nconst FEE_TIERS: readonly FeeTier[] = [\"min\", \"low\", \"mid\", \"high\"];\nconst TIER_INDEX = { low: 0, mid: 1, high: 2 } as const;\n\nexport function isFeeTier(fee: FeeParam | undefined): fee is FeeTier {\n\treturn typeof fee === \"string\" && FEE_TIERS.includes(fee as FeeTier);\n}\n\n/**\n * Minimum relay fee: 1 uSTX per byte of the serialized transaction. The fee\n * field is fixed-width (8 bytes), so the size — and therefore this floor — is\n * stable regardless of the fee value later set on the spending condition.\n */\nexport function minimumFee(transaction: StacksTransaction): bigint {\n\treturn BigInt(serializeTransaction(transaction).length);\n}\n\n/** Outcome of {@link resolveFee}: the amount and which tier produced it. */\nexport type ResolvedFee = {\n\tfee: bigint;\n\t/**\n\t * Tier the amount came from. `'min'` when the estimator had no estimate\n\t * and the relay floor was used instead. Absent when the caller passed an\n\t * exact amount.\n\t */\n\ttier?: FeeTier;\n};\n\n/**\n * True when the node answered `POST /v2/fees/transaction` with 400\n * `NoEstimateAvailable`: it is healthy but has no fee history for this\n * payload (fresh devnet, quiet chain). Every other failure means the\n * estimate was never obtained and must surface to the caller.\n */\nexport function isNoEstimateAvailable(error: unknown): boolean {\n\treturn (\n\t\terror instanceof HttpRequestError &&\n\t\terror.status === 400 &&\n\t\t(error.details?.includes(\"NoEstimateAvailable\") ?? false)\n\t);\n}\n\n/**\n * Resolve a fee param to a concrete amount. Numeric input passes through.\n * Tiers `'low' | 'mid' | 'high'` index the node's estimations (nearest\n * available when fewer than three are returned); `'min'` resolves to\n * {@link minimumFee}, which needs no network round-trip.\n *\n * The relay floor is the fallback ONLY when the node reports\n * `NoEstimateAvailable` or returns no estimations. A transport timeout, 5xx,\n * or auth failure rethrows: silently under-paying because the node was\n * unreachable would strand the transaction in the mempool.\n */\nexport async function resolveFee(\n\tclient: Client,\n\ttransaction: StacksTransaction,\n\tfee: FeeParam | undefined,\n): Promise<ResolvedFee> {\n\tif (fee !== undefined && !isFeeTier(fee)) return { fee: intToBigInt(fee) };\n\n\tconst tier = fee ?? \"mid\";\n\tif (tier === \"min\") return { fee: minimumFee(transaction), tier };\n\n\tlet estimates: Awaited<ReturnType<typeof estimateFee>>;\n\ttry {\n\t\testimates = await estimateFee(client, { transaction });\n\t} catch (error) {\n\t\tif (!isNoEstimateAvailable(error)) throw error;\n\t\treturn { fee: minimumFee(transaction), tier: \"min\" };\n\t}\n\tconst pick = estimates[TIER_INDEX[tier]] ?? estimates[estimates.length - 1];\n\tif (pick) return { fee: BigInt(pick.fee), tier };\n\treturn { fee: minimumFee(transaction), tier: \"min\" };\n}\n\n/** Set the resolved fee on an unsigned transaction's origin spending condition. */\nexport function setUnsignedFee(\n\ttransaction: StacksTransaction,\n\tfee: bigint,\n): void {\n\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\t(transaction.auth.spendingCondition as any).fee = fee;\n\t// In-place mutation: invalidate the memoized serialization (resolveFee may\n\t// have already serialized this object via minimumFee/estimateFee).\n\tclearTxCache(transaction);\n}\n\n/** Throw when a named fee tier is used with a provider (wallet) account. */\nexport function assertNoFeeTierForProvider(fee: FeeParam | undefined): void {\n\tif (isFeeTier(fee)) {\n\t\tthrow new Error(\n\t\t\t`Fee tier '${fee}' requires local signing; provider (wallet) accounts set their own fee`,\n\t\t);\n\t}\n}\n",
|
|
18
|
+
"import type { ClarityValue } from \"../../clarity/types.ts\";\nimport type { Client } from \"../../clients/types.ts\";\nimport type {\n\tPostConditionInput,\n\tPostConditionMode,\n} from \"../../postconditions/types.ts\";\nimport { buildContractCall } from \"../../transactions/build.ts\";\nimport { signTransactionWithAccount } from \"../../transactions/signer.ts\";\nimport { parseContractId } from \"../../utils/address.ts\";\nimport type { IntegerType } from \"../../utils/encoding.ts\";\nimport {\n\tbroadcastWithNonceReset,\n\treleaseNonce,\n\tresolveNonce,\n} from \"./nonceManager.ts\";\nimport {\n\ttype FeeParam,\n\tassertNoFeeTierForProvider,\n\tisFeeTier,\n\tisProviderAccount,\n\tresolveFee,\n\tsetUnsignedFee,\n} from \"./utils.ts\";\n\nexport type CallContractParams = {\n\tcontract: string; // \"address.name\"\n\tfunctionName: string;\n\tfunctionArgs?: ClarityValue[];\n\tfee?: FeeParam;\n\tnonce?: IntegerType;\n\tpostConditionMode?: PostConditionMode;\n\tpostConditions?: PostConditionInput[];\n};\n\n/** Build, sign, and broadcast a contract call */\nexport async function callContract(\n\tclient: Client,\n\tparams: CallContractParams,\n): Promise<string> {\n\tconst account = client.account;\n\tif (!account) throw new Error(\"Account required\");\n\n\t// Validate the contract id up front so both the provider and local paths\n\t// reject malformed input instead of forwarding it to the wallet.\n\tconst [contractAddress, contractName] = parseContractId(params.contract);\n\n\t// Provider: delegate to wallet\n\tif (isProviderAccount(account)) {\n\t\tassertNoFeeTierForProvider(params.fee);\n\t\tconst result = await account.provider.request(\"stx_callContract\", {\n\t\t\tcontract: params.contract,\n\t\t\tfunctionName: params.functionName,\n\t\t\tfunctionArgs: params.functionArgs ?? [],\n\t\t});\n\t\treturn result.txid;\n\t}\n\n\t// Local/Custom: build → sign → broadcast\n\tconst managed =\n\t\tparams.nonce === undefined && client.nonceManager !== undefined;\n\tconst nonce = params.nonce ?? (await resolveNonce(client, account.address));\n\n\ttry {\n\t\tconst needsFeeResolution =\n\t\t\tparams.fee === undefined || isFeeTier(params.fee);\n\n\t\tconst unsigned = buildContractCall({\n\t\t\tcontractAddress,\n\t\t\tcontractName,\n\t\t\tfunctionName: params.functionName,\n\t\t\tfunctionArgs: params.functionArgs ?? [],\n\t\t\tfee: needsFeeResolution ? 0n : (params.fee as IntegerType),\n\t\t\tnonce,\n\t\t\tpublicKey: account.publicKey,\n\t\t\tchain: client.chain,\n\t\t\tpostConditionMode: params.postConditionMode,\n\t\t\tpostConditions: params.postConditions,\n\t\t});\n\n\t\tif (needsFeeResolution) {\n\t\t\tconst { fee } = await resolveFee(client, unsigned, params.fee);\n\t\t\tsetUnsignedFee(unsigned, fee);\n\t\t}\n\n\t\tconst signed = await signTransactionWithAccount(unsigned, account);\n\t\treturn await broadcastWithNonceReset(client, {\n\t\t\ttransaction: signed,\n\t\t\taddress: account.address,\n\t\t});\n\t} catch (error) {\n\t\t// Anything that fails between reserving the nonce and a 2xx broadcast\n\t\t// (fee estimate, signing, FeeTooLow, transport) never reached the\n\t\t// mempool: hand the nonce back so the next send does not skip it.\n\t\tif (managed) await releaseNonce(client, account.address, nonce as bigint);\n\t\tthrow error;\n\t}\n}\n"
|
|
19
|
+
],
|
|
20
|
+
"mappings": ";AAkBA,SAAS,iBAAiB,CACzB,GAC2D;AAAA,EAC3D,OACC,OAAO,MAAM,YACb,MAAM,QACN,cAAc,KACd,SAAS,MACR,OAAQ,EAA8B,aAAa,YACnD,OAAQ,EAA8B,aAAa,cACnD,OAAQ,EAA8B,QAAQ,YAC9C,OAAQ,EAA8B,QAAQ;AAAA;AAIjD,eAAsB,WAAW,CAChC,QACA,QAC2B;AAAA,EAC3B,MAAM,aAAa,WAAW,iBAAiB,OAAO,YAAY,OAAO,CAAC;AAAA,EAC1E,MAAM,QAAQ,WAAW,qBAAqB,OAAO,WAAW,CAAC;AAAA,EAEjE,MAAM,OAAO,MAAM,OAAO,QAAQ,wBAAwB;AAAA,IACzD,QAAQ;AAAA,IACR,MAAM;AAAA,MACL,eAAe,KAAK,KAAK,MAAM,SAAS,CAAC;AAAA,MACzC,q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M,2BAA2B,UAAU,OAAO;AAAA,IACjE,OAAO,MAAM,wBAAwB,QAAQ;AAAA,MAC5C,aAAa;AAAA,MACb,SAAS,QAAQ;AAAA,IAClB,CAAC;AAAA,IACA,OAAO,OAAO;AAAA,IAIf,IAAI;AAAA,MAAS,MAAM,aAAa,QAAQ,QAAQ,SAAS,KAAe;AAAA,IACxE,MAAM;AAAA;AAAA;",
|
|
21
|
+
"debugId": "DC00E5DBCD8CE8AA64756E2164756E21",
|
|
22
|
+
"names": []
|
|
23
|
+
}
|
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
import {
|
|
2
2
|
callContract,
|
|
3
|
-
estimateFee,
|
|
4
3
|
getMapEntry,
|
|
5
|
-
|
|
4
|
+
getNonce,
|
|
5
|
+
resolveFee,
|
|
6
6
|
setUnsignedFee
|
|
7
|
-
} from "./stacks-
|
|
7
|
+
} from "./stacks-n4d8j8q3.js";
|
|
8
8
|
import {
|
|
9
9
|
readContract
|
|
10
|
-
} from "./stacks-
|
|
10
|
+
} from "./stacks-ga026yxz.js";
|
|
11
11
|
import {
|
|
12
12
|
clarityValueToJSUntyped,
|
|
13
13
|
jsToClarityValue,
|
|
14
14
|
toCamelCase
|
|
15
|
-
} from "./stacks-
|
|
15
|
+
} from "./stacks-x0qqwrev.js";
|
|
16
16
|
import {
|
|
17
17
|
buildContractCall
|
|
18
|
-
} from "./stacks-
|
|
18
|
+
} from "./stacks-9c1yam8b.js";
|
|
19
19
|
import {
|
|
20
20
|
publicKeyToAddress
|
|
21
|
-
} from "./stacks-
|
|
21
|
+
} from "./stacks-4d7c3x27.js";
|
|
22
22
|
|
|
23
23
|
// src/actions/getContract.ts
|
|
24
24
|
function getContract(params) {
|
|
@@ -97,7 +97,9 @@ function getContract(params) {
|
|
|
97
97
|
}
|
|
98
98
|
const functionArgs = buildFunctionArgs(fn, args);
|
|
99
99
|
const network = client.chain?.network ?? "mainnet";
|
|
100
|
-
const nonce = options?.nonce ?? await
|
|
100
|
+
const nonce = options?.nonce ?? await getNonce(client, {
|
|
101
|
+
address: publicKeyToAddress(publicKey, network)
|
|
102
|
+
});
|
|
101
103
|
const unsigned = buildContractCall({
|
|
102
104
|
contractAddress: address,
|
|
103
105
|
contractName,
|
|
@@ -112,13 +114,8 @@ function getContract(params) {
|
|
|
112
114
|
sponsored: options?.sponsored
|
|
113
115
|
});
|
|
114
116
|
if (options?.fee === undefined) {
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
});
|
|
118
|
-
const mid = estimates[1] ?? estimates[0];
|
|
119
|
-
if (mid) {
|
|
120
|
-
setUnsignedFee(unsigned, BigInt(mid.fee));
|
|
121
|
-
}
|
|
117
|
+
const { fee } = await resolveFee(client, unsigned, undefined);
|
|
118
|
+
setUnsignedFee(unsigned, fee);
|
|
122
119
|
}
|
|
123
120
|
return unsigned;
|
|
124
121
|
};
|
|
@@ -187,5 +184,5 @@ class ContractResponseError extends Error {
|
|
|
187
184
|
|
|
188
185
|
export { getContract, resolveNetworkContract, buildFunctionArgs, isResponseOutput, ContractResponseError };
|
|
189
186
|
|
|
190
|
-
//# debugId=
|
|
191
|
-
//# sourceMappingURL=stacks-
|
|
187
|
+
//# debugId=68BE202E22097C6C64756E2164756E21
|
|
188
|
+
//# sourceMappingURL=stacks-e3nwm1dz.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/actions/getContract.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type {\n\tAbiContract,\n\tAbiFunction,\n\tAbiMap,\n\tAbiType,\n\tAbiTypesOf,\n\tContractTypes,\n\tExtractFunctionArgs,\n\tExtractFunctionOutput,\n\tExtractMapKey,\n\tExtractMapNames,\n\tExtractMapValue,\n\tExtractPublicFunctions,\n\tExtractReadOnlyFunctions,\n} from \"../clarity/abi/index.ts\";\nimport { type ToCamelCase, toCamelCase } from \"../clarity/abi/utils.ts\";\nimport {\n\tclarityValueToJSUntyped,\n\tjsToClarityValue,\n} from \"../clarity/bridge.ts\";\nimport type { ClarityValue } from \"../clarity/types.ts\";\nimport type { Client } from \"../clients/types.ts\";\nimport type {\n\tPostConditionInput,\n\tPostConditionMode,\n} from \"../postconditions/types.ts\";\nimport { buildContractCall } from \"../transactions/build.ts\";\nimport type { StacksTransaction } from \"../transactions/types.ts\";\nimport { publicKeyToAddress } from \"../utils/address.ts\";\nimport type { IntegerType } from \"../utils/encoding.ts\";\nimport { getMapEntry } from \"./public/getMapEntry.ts\";\nimport { getNonce } from \"./public/getNonce.ts\";\nimport { readContract } from \"./public/readContract.ts\";\nimport { callContract } from \"./wallet/callContract.ts\";\nimport { resolveFee, setUnsignedFee } from \"./wallet/utils.ts\";\n\n// --- Type helpers for unwrapping response types ---\n\n/**\n * Unwrap `(response ok err)` → just the `ok` branch type. Distributes over the\n * `{ ok } | { err }` union: the `err` branch maps to `never` (it throws\n * `ContractResponseError` at runtime, so it never reaches the caller).\n */\nexport type UnwrapResponse<T> = T extends { ok: infer O }\n\t? O\n\t: T extends { err: unknown }\n\t\t? never\n\t\t: T;\n\ntype ReadMethodReturn<\n\tC extends AbiContract,\n\tN extends ExtractReadOnlyFunctions<C>,\n> = UnwrapResponse<ExtractFunctionOutput<C, N>>;\n\n// --- Public type for the contract instance ---\n\n/**\n * When the ABI carries a codegen brand (`TypedAbi`), method types resolve to\n * the generated named aliases — cleaner hovers and error messages. Un-branded\n * ABIs fall back to structural inference over the as-const literal.\n */\ntype TypedReadMethods<T extends ContractTypes> = {\n\t[K in keyof T[\"functions\"] as T[\"functions\"][K][\"access\"] extends \"read-only\"\n\t\t? K\n\t\t: never]: (\n\t\targs: T[\"functions\"][K][\"args\"],\n\t) => Promise<UnwrapResponse<T[\"functions\"][K][\"ret\"]>>;\n};\n\ntype TypedCallMethods<T extends ContractTypes> = {\n\t[K in keyof T[\"functions\"] as T[\"functions\"][K][\"access\"] extends \"public\"\n\t\t? K\n\t\t: never]: (\n\t\targs: T[\"functions\"][K][\"args\"],\n\t\toptions?: ContractCallOptions,\n\t) => Promise<string>;\n};\n\ntype TypedMapMethods<T extends ContractTypes> = {\n\t[K in keyof NonNullable<T[\"maps\"]>]: (\n\t\tkey: NonNullable<T[\"maps\"]>[K][\"key\"],\n\t) => Promise<NonNullable<T[\"maps\"]>[K][\"value\"] | null>;\n};\n\ntype ReadMethods<C extends AbiContract> = [AbiTypesOf<C>] extends [never]\n\t? {\n\t\t\t[N in ExtractReadOnlyFunctions<C> as ToCamelCase<N>]: (\n\t\t\t\targs: ExtractFunctionArgs<C, N>,\n\t\t\t) => Promise<ReadMethodReturn<C, N>>;\n\t\t}\n\t: TypedReadMethods<AbiTypesOf<C>>;\n\ntype CallMethods<C extends AbiContract> = [AbiTypesOf<C>] extends [never]\n\t? {\n\t\t\t[N in ExtractPublicFunctions<C> as ToCamelCase<N>]: (\n\t\t\t\targs: ExtractFunctionArgs<C, N>,\n\t\t\t\toptions?: ContractCallOptions,\n\t\t\t) => Promise<string>;\n\t\t}\n\t: TypedCallMethods<AbiTypesOf<C>>;\n\ntype MapMethods<C extends AbiContract> = [AbiTypesOf<C>] extends [never]\n\t? {\n\t\t\t[N in ExtractMapNames<C> as ToCamelCase<N>]: (\n\t\t\t\tkey: ExtractMapKey<C, N>,\n\t\t\t) => Promise<ExtractMapValue<C, N> | null>;\n\t\t}\n\t: TypedMapMethods<AbiTypesOf<C>>;\n\nexport type ContractCallOptions = {\n\tfee?: IntegerType;\n\tnonce?: IntegerType;\n\tpostConditionMode?: PostConditionMode;\n\tpostConditions?: PostConditionInput[];\n};\n\n/**\n * Options for `buildCall.*`, building an unsigned transaction for\n * wallet-signs-later flows. `publicKey` defaults to the client account's\n * public key. When omitted, `nonce` is the confirmed on-chain nonce read\n * straight from the node (the client's nonce manager is never consumed for\n * a transaction that may never be sent) and `fee` is the mid estimate,\n * falling back to the relay floor only on `NoEstimateAvailable`.\n */\nexport type ContractBuildCallOptions = ContractCallOptions & {\n\tpublicKey?: string;\n\tsponsored?: boolean;\n};\n\ntype TypedBuildCallMethods<T extends ContractTypes> = {\n\t[K in keyof T[\"functions\"] as T[\"functions\"][K][\"access\"] extends \"public\"\n\t\t? K\n\t\t: never]: (\n\t\targs: T[\"functions\"][K][\"args\"],\n\t\toptions?: ContractBuildCallOptions,\n\t) => Promise<StacksTransaction>;\n};\n\ntype BuildCallMethods<C extends AbiContract> = [AbiTypesOf<C>] extends [never]\n\t? {\n\t\t\t[N in ExtractPublicFunctions<C> as ToCamelCase<N>]: (\n\t\t\t\targs: ExtractFunctionArgs<C, N>,\n\t\t\t\toptions?: ContractBuildCallOptions,\n\t\t\t) => Promise<StacksTransaction>;\n\t\t}\n\t: TypedBuildCallMethods<AbiTypesOf<C>>;\n\nexport type ContractInstance<C extends AbiContract> = {\n\tread: ReadMethods<C>;\n\tcall: CallMethods<C>;\n\t/** Build unsigned transactions (wallet-signs-later) — never broadcasts. */\n\tbuildCall: BuildCallMethods<C>;\n\tmaps: MapMethods<C>;\n};\n\nexport type GetContractParams<C extends AbiContract> = {\n\tclient: Client;\n\taddress: string;\n\tname: string;\n\tabi: C;\n};\n\nexport function getContract<const TAbi extends AbiContract>(\n\tparams: GetContractParams<TAbi>,\n): ContractInstance<TAbi> {\n\tconst { client, address, name: contractName, abi } = params;\n\tconst contractId = `${address}.${contractName}`;\n\n\t// Index functions/maps by name for fast lookup\n\tconst fnByName = new Map<string, AbiFunction>();\n\tfor (const fn of abi.functions) {\n\t\tfnByName.set(fn.name, fn as AbiFunction);\n\t}\n\n\tconst mapByName = new Map<string, AbiMap>();\n\tif (abi.maps) {\n\t\tfor (const m of abi.maps) {\n\t\t\tmapByName.set(m.name, m as AbiMap);\n\t\t}\n\t}\n\n\t// Build kebab→camel reverse map for function/map names\n\tconst camelToKebab = new Map<string, string>();\n\tfor (const fn of abi.functions) {\n\t\tcamelToKebab.set(toCamelCase(fn.name), fn.name);\n\t}\n\tif (abi.maps) {\n\t\tfor (const m of abi.maps) {\n\t\t\tcamelToKebab.set(toCamelCase(m.name), m.name);\n\t\t}\n\t}\n\n\tconst read = new Proxy({} as ReadMethods<TAbi>, {\n\t\tget(_target, prop: string) {\n\t\t\tconst fnName = camelToKebab.get(prop) ?? prop;\n\t\t\tconst fn = fnByName.get(fnName);\n\t\t\tif (!fn || fn.access !== \"read-only\") return undefined;\n\n\t\t\treturn async (args: Record<string, unknown>) => {\n\t\t\t\tconst clarityArgs = buildFunctionArgs(fn, args);\n\t\t\t\tconst result = await readContract(client, {\n\t\t\t\t\tcontract: contractId,\n\t\t\t\t\tfunctionName: fn.name,\n\t\t\t\t\targs: clarityArgs,\n\t\t\t\t});\n\n\t\t\t\tconst jsValue = clarityValueToJSUntyped(fn.outputs as AbiType, result);\n\n\t\t\t\t// Auto-unwrap: if output is response type, unwrap ok / throw on err\n\t\t\t\tif (isResponseOutput(fn.outputs as AbiType)) {\n\t\t\t\t\tconst resp = jsValue as { ok?: unknown; err?: unknown };\n\t\t\t\t\tif (\"ok\" in resp) return resp.ok;\n\t\t\t\t\tthrow new ContractResponseError(\n\t\t\t\t\t\t`${contractId}::${fn.name} returned (err ${formatErrValue(resp.err)})`,\n\t\t\t\t\t\tresp.err,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn jsValue;\n\t\t\t};\n\t\t},\n\t});\n\n\tconst call = new Proxy({} as CallMethods<TAbi>, {\n\t\tget(_target, prop: string) {\n\t\t\tconst fnName = camelToKebab.get(prop) ?? prop;\n\t\t\tconst fn = fnByName.get(fnName);\n\t\t\tif (!fn || fn.access !== \"public\") return undefined;\n\n\t\t\treturn async (\n\t\t\t\targs: Record<string, unknown>,\n\t\t\t\toptions?: ContractCallOptions,\n\t\t\t) => {\n\t\t\t\tconst clarityArgs = buildFunctionArgs(fn, args);\n\t\t\t\treturn callContract(client, {\n\t\t\t\t\tcontract: contractId,\n\t\t\t\t\tfunctionName: fn.name,\n\t\t\t\t\tfunctionArgs: clarityArgs,\n\t\t\t\t\t...options,\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t});\n\n\tconst buildCall = new Proxy({} as BuildCallMethods<TAbi>, {\n\t\tget(_target, prop: string) {\n\t\t\tconst fnName = camelToKebab.get(prop) ?? prop;\n\t\t\tconst fn = fnByName.get(fnName);\n\t\t\tif (!fn || fn.access !== \"public\") return undefined;\n\n\t\t\treturn async (\n\t\t\t\targs: Record<string, unknown>,\n\t\t\t\toptions?: ContractBuildCallOptions,\n\t\t\t) => {\n\t\t\t\tconst publicKey = options?.publicKey ?? client.account?.publicKey;\n\t\t\t\tif (!publicKey) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"buildCall requires a publicKey (pass options.publicKey or configure a client account)\",\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst functionArgs = buildFunctionArgs(fn, args);\n\t\t\t\tconst network = client.chain?.network ?? \"mainnet\";\n\t\t\t\tconst nonce =\n\t\t\t\t\toptions?.nonce ??\n\t\t\t\t\t(await getNonce(client, {\n\t\t\t\t\t\taddress: publicKeyToAddress(publicKey, network),\n\t\t\t\t\t}));\n\n\t\t\t\tconst unsigned = buildContractCall({\n\t\t\t\t\tcontractAddress: address,\n\t\t\t\t\tcontractName,\n\t\t\t\t\tfunctionName: fn.name,\n\t\t\t\t\tfunctionArgs,\n\t\t\t\t\tfee: options?.fee ?? 0n,\n\t\t\t\t\tnonce,\n\t\t\t\t\tpublicKey,\n\t\t\t\t\tchain: client.chain,\n\t\t\t\t\tpostConditionMode: options?.postConditionMode,\n\t\t\t\t\tpostConditions: options?.postConditions,\n\t\t\t\t\tsponsored: options?.sponsored,\n\t\t\t\t});\n\n\t\t\t\tif (options?.fee === undefined) {\n\t\t\t\t\tconst { fee } = await resolveFee(client, unsigned, undefined);\n\t\t\t\t\tsetUnsignedFee(unsigned, fee);\n\t\t\t\t}\n\n\t\t\t\treturn unsigned;\n\t\t\t};\n\t\t},\n\t});\n\n\tconst maps = new Proxy({} as MapMethods<TAbi>, {\n\t\tget(_target, prop: string) {\n\t\t\tconst mapName = camelToKebab.get(prop) ?? prop;\n\t\t\tconst map = mapByName.get(mapName);\n\t\t\tif (!map) return undefined;\n\n\t\t\treturn async (key: unknown) => {\n\t\t\t\tconst clarityKey = jsToClarityValue(map.key as AbiType, key);\n\t\t\t\tconst result = await getMapEntry(client, {\n\t\t\t\t\tcontract: contractId,\n\t\t\t\t\tmapName: map.name,\n\t\t\t\t\tkey: clarityKey,\n\t\t\t\t});\n\n\t\t\t\t// Map entries come back as (optional ...). If none, return null.\n\t\t\t\tif (result.type === \"none\") return null;\n\t\t\t\tif (result.type === \"some\") {\n\t\t\t\t\treturn clarityValueToJSUntyped(map.value as AbiType, result.value);\n\t\t\t\t}\n\t\t\t\t// Direct value (shouldn't normally happen, but handle gracefully)\n\t\t\t\treturn clarityValueToJSUntyped(map.value as AbiType, result);\n\t\t\t};\n\t\t},\n\t});\n\n\treturn { read, call, buildCall, maps };\n}\n\n/**\n * Resolve a network-keyed contract config for the client's chain. The contracts\n * map is keyed by network (\"mainnet\" | \"testnet\"), so selection is a direct\n * index — no per-call ternary. Throws if the client has no chain configured.\n */\nexport function resolveNetworkContract<\n\tT extends Record<\"mainnet\" | \"testnet\", { address: string }>,\n>(client: Client, contracts: T): T[\"mainnet\"] | T[\"testnet\"] {\n\tif (!client.chain) {\n\t\tthrow new Error(\"Client must have a chain configured\");\n\t}\n\treturn contracts[client.chain.network];\n}\n\n// --- Helpers ---\n\n/**\n * Encode an ABI function's named args into positional ClarityValues. Exported\n * so a caller that needs the raw ClarityValue result (to cache or re-serialize\n * it) can reuse the same encoding this module's read methods use, instead of\n * maintaining a second one that drifts.\n */\nexport function buildFunctionArgs(\n\tfn: AbiFunction,\n\targs: Record<string, unknown>,\n): ClarityValue[] {\n\treturn fn.args.map((arg) => {\n\t\tconst camelKey = toCamelCase(arg.name);\n\t\tconst hasOriginal = arg.name in args;\n\t\tconst hasCamel = camelKey in args;\n\t\tconst value = hasOriginal\n\t\t\t? args[arg.name]\n\t\t\t: hasCamel\n\t\t\t\t? args[camelKey]\n\t\t\t\t: undefined;\n\t\tif (value === undefined) throw new Error(`Missing argument: ${arg.name}`);\n\t\treturn jsToClarityValue(arg.type as AbiType, value);\n\t});\n}\n\n/** True when an ABI output is a `(response ok err)` and needs unwrapping. */\nexport function isResponseOutput(type: AbiType): boolean {\n\treturn typeof type === \"object\" && type !== null && \"response\" in type;\n}\n\nfunction formatErrValue(value: unknown): string {\n\tif (typeof value === \"bigint\") return value.toString();\n\tif (typeof value === \"string\") return `\"${value}\"`;\n\treturn String(value);\n}\n\nexport class ContractResponseError extends Error {\n\toverride name = \"ContractResponseError\";\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly errorValue: unknown,\n\t) {\n\t\tsuper(message);\n\t}\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;AAkKO,SAAS,WAA2C,CAC1D,QACyB;AAAA,EACzB,QAAQ,QAAQ,SAAS,MAAM,cAAc,QAAQ;AAAA,EACrD,MAAM,aAAa,GAAG,WAAW;AAAA,EAGjC,MAAM,WAAW,IAAI;AAAA,EACrB,WAAW,MAAM,IAAI,WAAW;AAAA,IAC/B,SAAS,IAAI,GAAG,MAAM,EAAiB;AAAA,EACxC;AAAA,EAEA,MAAM,YAAY,IAAI;AAAA,EACtB,IAAI,IAAI,MAAM;AAAA,IACb,WAAW,KAAK,IAAI,MAAM;AAAA,MACzB,UAAU,IAAI,EAAE,MAAM,CAAW;AAAA,IAClC;AAAA,EACD;AAAA,EAGA,MAAM,eAAe,IAAI;AAAA,EACzB,WAAW,MAAM,IAAI,WAAW;AAAA,IAC/B,aAAa,IAAI,YAAY,GAAG,IAAI,GAAG,GAAG,IAAI;AAAA,EAC/C;AAAA,EACA,IAAI,IAAI,MAAM;AAAA,IACb,WAAW,KAAK,IAAI,MAAM;AAAA,MACzB,aAAa,IAAI,YAAY,EAAE,IAAI,GAAG,EAAE,IAAI;AAAA,IAC7C;AAAA,EACD;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IAAU,OAAO,MAAM,SAAS;AAAA,EACrD,IAAI,OAAO,UAAU;AAAA,IAAU,OAAO,IAAI;AAAA,EAC1C,OAAO,OAAO,KAAK;AAAA;AAAA;AAGb,MAAM,8BAA8B,MAAM;AAAA,EAI/B;AAAA,EAHR,OAAO;AAAA,EAChB,WAAW,CACV,SACgB,YACf;AAAA,IACD,MAAM,OAAO;AAAA,IAFG;AAAA;AAIlB;",
|
|
8
|
+
"debugId": "68BE202E22097C6C64756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -134,11 +134,13 @@ function cvToJSON(val) {
|
|
|
134
134
|
return { type: "int", value: val.value.toString() };
|
|
135
135
|
case "uint":
|
|
136
136
|
return { type: "uint", value: val.value.toString() };
|
|
137
|
-
case "buffer":
|
|
137
|
+
case "buffer": {
|
|
138
|
+
const hex = without0x(val.value);
|
|
138
139
|
return {
|
|
139
|
-
type: `(buff ${Math.ceil(
|
|
140
|
-
value: `0x${
|
|
140
|
+
type: `(buff ${Math.ceil(hex.length / 2)})`,
|
|
141
|
+
value: `0x${hex}`
|
|
141
142
|
};
|
|
143
|
+
}
|
|
142
144
|
case "none":
|
|
143
145
|
return { type: "(optional none)", value: null };
|
|
144
146
|
case "some":
|
|
@@ -555,6 +557,25 @@ function normalizeVariable(variable) {
|
|
|
555
557
|
access: variable.access
|
|
556
558
|
};
|
|
557
559
|
}
|
|
560
|
+
function normalizeFungibleToken(token) {
|
|
561
|
+
return { name: token.name };
|
|
562
|
+
}
|
|
563
|
+
function normalizeNonFungibleToken(token) {
|
|
564
|
+
return { name: token.name, type: normalizeType(token.type) };
|
|
565
|
+
}
|
|
566
|
+
function normalizeTraitDefinition(trait) {
|
|
567
|
+
const rawFunctions = Array.isArray(trait.functions) ? trait.functions : [];
|
|
568
|
+
const functions = [];
|
|
569
|
+
for (const func of rawFunctions) {
|
|
570
|
+
if (typeof func !== "object" || func === null)
|
|
571
|
+
continue;
|
|
572
|
+
const normalized = normalizeFunction(func);
|
|
573
|
+
if (normalized.access === "private")
|
|
574
|
+
continue;
|
|
575
|
+
functions.push(normalized);
|
|
576
|
+
}
|
|
577
|
+
return { name: trait.name, functions };
|
|
578
|
+
}
|
|
558
579
|
function normalizeAbi(abi) {
|
|
559
580
|
if (typeof abi !== "object" || abi === null) {
|
|
560
581
|
return { functions: [] };
|
|
@@ -563,6 +584,10 @@ function normalizeAbi(abi) {
|
|
|
563
584
|
const functions = [];
|
|
564
585
|
const maps = [];
|
|
565
586
|
const variables = [];
|
|
587
|
+
const fungibleTokens = [];
|
|
588
|
+
const nonFungibleTokens = [];
|
|
589
|
+
const implementedTraits = [];
|
|
590
|
+
const definedTraits = [];
|
|
566
591
|
if (Array.isArray(abiObj.functions)) {
|
|
567
592
|
for (const func of abiObj.functions) {
|
|
568
593
|
if (typeof func === "object" && func !== null) {
|
|
@@ -584,12 +609,43 @@ function normalizeAbi(abi) {
|
|
|
584
609
|
}
|
|
585
610
|
}
|
|
586
611
|
}
|
|
612
|
+
if (Array.isArray(abiObj.fungible_tokens)) {
|
|
613
|
+
for (const token of abiObj.fungible_tokens) {
|
|
614
|
+
if (typeof token === "object" && token !== null) {
|
|
615
|
+
fungibleTokens.push(normalizeFungibleToken(token));
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
if (Array.isArray(abiObj.non_fungible_tokens)) {
|
|
620
|
+
for (const token of abiObj.non_fungible_tokens) {
|
|
621
|
+
if (typeof token === "object" && token !== null) {
|
|
622
|
+
nonFungibleTokens.push(normalizeNonFungibleToken(token));
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
if (Array.isArray(abiObj.implemented_traits)) {
|
|
627
|
+
for (const trait of abiObj.implemented_traits) {
|
|
628
|
+
if (typeof trait === "string")
|
|
629
|
+
implementedTraits.push(trait);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
if (Array.isArray(abiObj.defined_traits)) {
|
|
633
|
+
for (const trait of abiObj.defined_traits) {
|
|
634
|
+
if (typeof trait === "object" && trait !== null) {
|
|
635
|
+
definedTraits.push(normalizeTraitDefinition(trait));
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
587
639
|
return {
|
|
588
640
|
functions,
|
|
589
641
|
maps: maps.length > 0 ? maps : undefined,
|
|
590
|
-
variables: variables.length > 0 ? variables : undefined
|
|
642
|
+
variables: variables.length > 0 ? variables : undefined,
|
|
643
|
+
fungible_tokens: fungibleTokens.length > 0 ? fungibleTokens : undefined,
|
|
644
|
+
non_fungible_tokens: nonFungibleTokens.length > 0 ? nonFungibleTokens : undefined,
|
|
645
|
+
implemented_traits: implementedTraits.length > 0 ? implementedTraits : undefined,
|
|
646
|
+
defined_traits: definedTraits.length > 0 ? definedTraits : undefined
|
|
591
647
|
};
|
|
592
648
|
}
|
|
593
649
|
|
|
594
|
-
//# debugId=
|
|
595
|
-
//# sourceMappingURL=stacks-
|
|
650
|
+
//# debugId=80FCD2146E22850B64756E2164756E21
|
|
651
|
+
//# sourceMappingURL=stacks-ee53k9j2.cjs.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/clarity/prettyPrint.ts", "../src/clarity/abi/converters.ts", "../src/clarity/abi/classify.ts", "../src/clarity/abi/normalize.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import {\n\tasciiToBytes,\n\tbytesToAscii,\n\thexToBytes,\n\tutf8ToBytes,\n\twithout0x,\n} from \"../utils/encoding.ts\";\nimport type { ClarityValue } from \"./types.ts\";\n\nexport function prettyPrint(\n\tval: ClarityValue,\n\tencoding: \"tryAscii\" | \"hex\" = \"hex\",\n): string | undefined {\n\tswitch (val.type) {\n\t\tcase \"true\":\n\t\t\treturn \"true\";\n\t\tcase \"false\":\n\t\t\treturn \"false\";\n\t\tcase \"int\":\n\t\t\treturn val.value.toString();\n\t\tcase \"uint\":\n\t\t\treturn `u${val.value.toString()}`;\n\t\tcase \"buffer\":\n\t\t\tif (encoding === \"tryAscii\") {\n\t\t\t\tconst str = bytesToAscii(hexToBytes(val.value));\n\t\t\t\tif (/^[ -~]*$/.test(str)) return JSON.stringify(str);\n\t\t\t}\n\t\t\treturn `0x${val.value}`;\n\t\tcase \"none\":\n\t\t\treturn \"none\";\n\t\tcase \"some\":\n\t\t\treturn `(some ${prettyPrint(val.value, encoding)})`;\n\t\tcase \"ok\":\n\t\t\treturn `(ok ${prettyPrint(val.value, encoding)})`;\n\t\tcase \"err\":\n\t\t\treturn `(err ${prettyPrint(val.value, encoding)})`;\n\t\tcase \"address\":\n\t\tcase \"contract\":\n\t\t\treturn val.value;\n\t\tcase \"list\":\n\t\t\treturn `(list ${val.value.map((v) => prettyPrint(v, encoding)).join(\" \")})`;\n\t\tcase \"tuple\":\n\t\t\treturn `(tuple ${Object.keys(val.value)\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\t\t.map((key) => `(${key} ${prettyPrint(val.value[key]!, encoding)})`)\n\t\t\t\t.join(\" \")})`;\n\t\tcase \"ascii\":\n\t\t\treturn `\"${val.value}\"`;\n\t\tcase \"utf8\":\n\t\t\treturn `u\"${val.value}\"`;\n\t}\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\nexport function cvToJSON(val: ClarityValue): any {\n\tswitch (val.type) {\n\t\tcase \"true\":\n\t\t\treturn { type: \"bool\", value: true };\n\t\tcase \"false\":\n\t\t\treturn { type: \"bool\", value: false };\n\t\tcase \"int\":\n\t\t\treturn { type: \"int\", value: val.value.toString() };\n\t\tcase \"uint\":\n\t\t\treturn { type: \"uint\", value: val.value.toString() };\n\t\tcase \"buffer\": {\n\t\t\tconst hex = without0x(val.value);\n\t\t\treturn {\n\t\t\t\ttype: `(buff ${Math.ceil(hex.length / 2)})`,\n\t\t\t\tvalue: `0x${hex}`,\n\t\t\t};\n\t\t}\n\t\tcase \"none\":\n\t\t\treturn { type: \"(optional none)\", value: null };\n\t\tcase \"some\":\n\t\t\treturn { type: \"(optional)\", value: cvToJSON(val.value) };\n\t\tcase \"ok\":\n\t\t\treturn { type: \"(response)\", value: cvToJSON(val.value), success: true };\n\t\tcase \"err\":\n\t\t\treturn { type: \"(response)\", value: cvToJSON(val.value), success: false };\n\t\tcase \"address\":\n\t\tcase \"contract\":\n\t\t\treturn { type: \"principal\", value: val.value };\n\t\tcase \"list\":\n\t\t\treturn { type: \"(list)\", value: val.value.map(cvToJSON) };\n\t\tcase \"tuple\": {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\t\t\tconst result: Record<string, any> = {};\n\t\t\tfor (const key of Object.keys(val.value)) {\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\t\tresult[key] = cvToJSON(val.value[key]!);\n\t\t\t}\n\t\t\treturn { type: \"(tuple)\", value: result };\n\t\t}\n\t\tcase \"ascii\":\n\t\t\treturn {\n\t\t\t\ttype: `(string-ascii ${asciiToBytes(val.value).length})`,\n\t\t\t\tvalue: val.value,\n\t\t\t};\n\t\tcase \"utf8\":\n\t\t\treturn {\n\t\t\t\ttype: `(string-utf8 ${utf8ToBytes(val.value).length})`,\n\t\t\t\tvalue: val.value,\n\t\t\t};\n\t}\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\nexport function cvToValue(val: ClarityValue): any {\n\tswitch (val.type) {\n\t\tcase \"true\":\n\t\t\treturn true;\n\t\tcase \"false\":\n\t\t\treturn false;\n\t\tcase \"int\":\n\t\tcase \"uint\":\n\t\t\treturn val.value;\n\t\tcase \"buffer\":\n\t\t\treturn `0x${val.value}`;\n\t\tcase \"none\":\n\t\t\treturn null;\n\t\tcase \"some\":\n\t\t\treturn cvToValue(val.value);\n\t\tcase \"ok\":\n\t\tcase \"err\":\n\t\t\treturn cvToValue(val.value);\n\t\tcase \"address\":\n\t\tcase \"contract\":\n\t\t\treturn val.value;\n\t\tcase \"list\":\n\t\t\treturn val.value.map(cvToValue);\n\t\tcase \"tuple\": {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: interop boundary or dynamic-shape value where typing adds friction without runtime safety\n\t\t\tconst result: Record<string, any> = {};\n\t\t\tfor (const key of Object.keys(val.value)) {\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\t\tresult[key] = cvToValue(val.value[key]!);\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\tcase \"ascii\":\n\t\tcase \"utf8\":\n\t\t\treturn val.value;\n\t}\n}\n\n/** Narrow to bigint; throws unless `val` is an int or uint. */\nexport function cvToBigInt(val: ClarityValue): bigint {\n\tif (val.type !== \"int\" && val.type !== \"uint\") {\n\t\tthrow new Error(`cvToBigInt: expected int or uint, got ${val.type}`);\n\t}\n\treturn val.value;\n}\n\n/** Narrow to string; throws unless `val` is an ascii or utf8 string. */\nexport function cvToString(val: ClarityValue): string {\n\tif (val.type !== \"ascii\" && val.type !== \"utf8\") {\n\t\tthrow new Error(`cvToString: expected ascii or utf8, got ${val.type}`);\n\t}\n\treturn val.value;\n}\n\n/** Narrow to hex string (no 0x prefix); throws unless `val` is a buffer. */\nexport function cvToBuffer(val: ClarityValue): string {\n\tif (val.type !== \"buffer\") {\n\t\tthrow new Error(`cvToBuffer: expected buffer, got ${val.type}`);\n\t}\n\treturn val.value;\n}\n\n/** Narrow to boolean; throws unless `val` is a bool. */\nexport function cvToBoolean(val: ClarityValue): boolean {\n\tif (val.type !== \"true\" && val.type !== \"false\") {\n\t\tthrow new Error(`cvToBoolean: expected bool, got ${val.type}`);\n\t}\n\treturn val.type === \"true\";\n}\n\n/** Narrow to principal string; throws unless `val` is a standard or contract principal. */\nexport function cvToPrincipal(val: ClarityValue): string {\n\tif (val.type !== \"address\" && val.type !== \"contract\") {\n\t\tthrow new Error(\n\t\t\t`cvToPrincipal: expected principal or contract, got ${val.type}`,\n\t\t);\n\t}\n\treturn val.value;\n}\n",
|
|
6
|
+
"import type { AbiFunction } from \"./contract.ts\";\nimport {\n\tisAbiBuffer,\n\tisAbiList,\n\tisAbiOptional,\n\tisAbiResponse,\n\tisAbiStringAscii,\n\tisAbiStringUtf8,\n\tisAbiTuple,\n\tisBool,\n\tisInt128,\n\tisPrincipal,\n\tisString,\n\tisUint8Array,\n\tisUint128,\n} from \"./guards.ts\";\nimport type { AbiType } from \"./types.ts\";\nimport { toCamelCase } from \"./utils.ts\";\n\nexport class ClarityConversionError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly type: AbiType,\n\t\tpublic readonly value: unknown,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"ClarityConversionError\";\n\t}\n}\n\nexport function jsToClarity(type: AbiType, value: unknown): unknown {\n\tif (type === \"none\") return null;\n\n\tif (type === \"uint128\") {\n\t\tif (!isUint128(value))\n\t\t\tthrow new ClarityConversionError(\"Invalid uint128 value\", type, value);\n\t\treturn value;\n\t}\n\n\tif (type === \"int128\") {\n\t\tif (!isInt128(value))\n\t\t\tthrow new ClarityConversionError(\"Invalid int128 value\", type, value);\n\t\treturn value;\n\t}\n\n\tif (type === \"bool\") {\n\t\tif (!isBool(value))\n\t\t\tthrow new ClarityConversionError(\"Invalid bool value\", type, value);\n\t\treturn value;\n\t}\n\n\tif (type === \"principal\") {\n\t\tif (!isPrincipal(value))\n\t\t\tthrow new ClarityConversionError(\"Invalid principal value\", type, value);\n\t\treturn value;\n\t}\n\n\tif (type === \"trait_reference\") {\n\t\tif (!isPrincipal(value))\n\t\t\tthrow new ClarityConversionError(\n\t\t\t\t\"Invalid trait_reference value\",\n\t\t\t\ttype,\n\t\t\t\tvalue,\n\t\t\t);\n\t\treturn value;\n\t}\n\n\tif (isAbiStringAscii(type)) {\n\t\tif (!isString(value))\n\t\t\tthrow new ClarityConversionError(\n\t\t\t\t\"Invalid string-ascii value\",\n\t\t\t\ttype,\n\t\t\t\tvalue,\n\t\t\t);\n\t\tconst str = value as string;\n\t\tfor (let i = 0; i < str.length; i++) {\n\t\t\tif (str.charCodeAt(i) > 127) {\n\t\t\t\tthrow new ClarityConversionError(\n\t\t\t\t\t`Non-ASCII character at position ${i}: '${str[i]}' (code ${str.charCodeAt(i)})`,\n\t\t\t\t\ttype,\n\t\t\t\t\tvalue,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (str.length > type[\"string-ascii\"].length) {\n\t\t\tthrow new ClarityConversionError(\n\t\t\t\t`String length ${str.length} exceeds max ${type[\"string-ascii\"].length}`,\n\t\t\t\ttype,\n\t\t\t\tvalue,\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\n\tif (isAbiStringUtf8(type)) {\n\t\tif (!isString(value))\n\t\t\tthrow new ClarityConversionError(\n\t\t\t\t\"Invalid string-utf8 value\",\n\t\t\t\ttype,\n\t\t\t\tvalue,\n\t\t\t);\n\t\tconst str = value as string;\n\t\tconst byteLength = new TextEncoder().encode(str).length;\n\t\tif (byteLength > type[\"string-utf8\"].length) {\n\t\t\tthrow new ClarityConversionError(\n\t\t\t\t`String byte length ${byteLength} exceeds max ${type[\"string-utf8\"].length}`,\n\t\t\t\ttype,\n\t\t\t\tvalue,\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\n\tif (isAbiBuffer(type)) {\n\t\tif (!isUint8Array(value))\n\t\t\tthrow new ClarityConversionError(\"Invalid buffer value\", type, value);\n\t\tconst buff = value as Uint8Array;\n\t\tif (buff.length > type.buff.length) {\n\t\t\tthrow new ClarityConversionError(\n\t\t\t\t`Buffer length ${buff.length} exceeds max ${type.buff.length}`,\n\t\t\t\ttype,\n\t\t\t\tvalue,\n\t\t\t);\n\t\t}\n\t\treturn value;\n\t}\n\n\tif (isAbiList(type)) {\n\t\tif (!Array.isArray(value))\n\t\t\tthrow new ClarityConversionError(\n\t\t\t\t\"Expected array for list type\",\n\t\t\t\ttype,\n\t\t\t\tvalue,\n\t\t\t);\n\t\tif (value.length > type.list.length) {\n\t\t\tthrow new ClarityConversionError(\n\t\t\t\t`List length ${value.length} exceeds max ${type.list.length}`,\n\t\t\t\ttype,\n\t\t\t\tvalue,\n\t\t\t);\n\t\t}\n\t\treturn value.map((item) => jsToClarity(type.list.type, item));\n\t}\n\n\tif (isAbiTuple(type)) {\n\t\tif (typeof value !== \"object\" || value === null)\n\t\t\tthrow new ClarityConversionError(\n\t\t\t\t\"Expected object for tuple type\",\n\t\t\t\ttype,\n\t\t\t\tvalue,\n\t\t\t);\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const field of type.tuple) {\n\t\t\tconst camelKey = toCamelCase(field.name);\n\t\t\tconst hasOriginal = field.name in (value as object);\n\t\t\tconst hasCamel = camelKey in (value as object);\n\t\t\tif (!hasOriginal && !hasCamel) {\n\t\t\t\tthrow new ClarityConversionError(\n\t\t\t\t\t`Missing tuple field: ${field.name}`,\n\t\t\t\t\ttype,\n\t\t\t\t\tvalue,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst fieldValue = hasOriginal\n\t\t\t\t? (value as Record<string, unknown>)[field.name]\n\t\t\t\t: (value as Record<string, unknown>)[camelKey];\n\t\t\tresult[field.name] = jsToClarity(field.type, fieldValue);\n\t\t}\n\t\treturn result;\n\t}\n\n\tif (isAbiOptional(type)) {\n\t\tif (value === null || value === undefined) return null;\n\t\treturn jsToClarity(type.optional, value);\n\t}\n\n\tif (isAbiResponse(type)) {\n\t\tif (typeof value !== \"object\" || value === null)\n\t\t\tthrow new ClarityConversionError(\n\t\t\t\t\"Expected object for response type\",\n\t\t\t\ttype,\n\t\t\t\tvalue,\n\t\t\t);\n\t\tconst hasOk = \"ok\" in value;\n\t\tconst hasErr = \"err\" in value;\n\t\tif (hasOk && !hasErr) {\n\t\t\treturn {\n\t\t\t\tok: jsToClarity(type.response.ok, (value as { ok: unknown }).ok),\n\t\t\t};\n\t\t}\n\t\tif (hasErr && !hasOk) {\n\t\t\treturn {\n\t\t\t\terr: jsToClarity(type.response.error, (value as { err: unknown }).err),\n\t\t\t};\n\t\t}\n\t\tthrow new ClarityConversionError(\n\t\t\t\"Response must have exactly 'ok' or 'err' property\",\n\t\t\ttype,\n\t\t\tvalue,\n\t\t);\n\t}\n\n\tthrow new ClarityConversionError(\"Unknown Clarity type\", type, value);\n}\n\nexport function prepareArgs<F extends AbiFunction>(\n\tfunc: F,\n\targs: Record<string, unknown>,\n): unknown[] {\n\treturn func.args.map((arg) => {\n\t\tif (!(arg.name in args)) {\n\t\t\tthrow new ClarityConversionError(\n\t\t\t\t`Missing argument: ${arg.name}`,\n\t\t\t\targ.type,\n\t\t\t\tundefined,\n\t\t\t);\n\t\t}\n\t\treturn jsToClarity(arg.type, args[arg.name]);\n\t});\n}\n\nexport function validateArgs<F extends AbiFunction>(\n\tfunc: F,\n\targs: Record<string, unknown>,\n): void {\n\tfor (const arg of func.args) {\n\t\tif (!(arg.name in args)) {\n\t\t\tthrow new ClarityConversionError(\n\t\t\t\t`Missing argument: ${arg.name}`,\n\t\t\t\targ.type,\n\t\t\t\tundefined,\n\t\t\t);\n\t\t}\n\t\tjsToClarity(arg.type, args[arg.name]);\n\t}\n}\n\nexport function validateArgsArray<F extends AbiFunction>(\n\tfunc: F,\n\targs: unknown[],\n): void {\n\tif (args.length !== func.args.length) {\n\t\tthrow new ClarityConversionError(\n\t\t\t`Expected ${func.args.length} arguments, got ${args.length}`,\n\t\t\tfunc.args[0]?.type ?? \"bool\",\n\t\t\targs,\n\t\t);\n\t}\n\tfunc.args.forEach((arg, i) => {\n\t\tjsToClarity(arg.type, args[i]);\n\t});\n}\n",
|
|
7
|
+
"import type { AbiContract, AbiFunction } from \"./contract.ts\";\nimport { SIP009_ABI, SIP010_ABI, SIP013_ABI } from \"./standards.ts\";\n\n/**\n * Static conformance classification — \"does this contract's ABI look like a\n * SIP-009/010/013 token?\". Powers trait-based discovery for the (many) contracts\n * that conform to a standard without declaring its trait. Lean match: every\n * REQUIRED standard function must be present with the same access + arg arity\n * (optional functions like get-token-uri are ignored). Loose on exact arg/return\n * types to catch real-world variants; consumers wanting certainty use the\n * `declared` traits parsed from source instead.\n */\n\n/** The canonical SIP trait standards this package can classify/scaffold against.\n * Single source of truth — the `SipStandard` type, CLI `--trait` validation, and\n * the MCP traits resource all derive from this so the vocabulary can't drift. */\nexport const TRAIT_STANDARDS = [\"sip-009\", \"sip-010\", \"sip-013\"] as const;\n\nexport type SipStandard = (typeof TRAIT_STANDARDS)[number];\n\ninterface StandardSpec {\n\tid: SipStandard;\n\tabi: AbiContract;\n\t/** Functions in the reference ABI that real tokens may omit. */\n\toptional: ReadonlySet<string>;\n}\n\nconst STANDARDS: ReadonlyArray<StandardSpec> = [\n\t{ id: \"sip-010\", abi: SIP010_ABI, optional: new Set([\"get-token-uri\"]) },\n\t{ id: \"sip-009\", abi: SIP009_ABI, optional: new Set([\"get-token-uri\"]) },\n\t{\n\t\tid: \"sip-013\",\n\t\tabi: SIP013_ABI,\n\t\toptional: new Set([\n\t\t\t\"transfer-memo\",\n\t\t\t\"transfer-many\",\n\t\t\t\"transfer-many-memo\",\n\t\t\t\"get-token-uri\",\n\t\t\t\"get-overall-balance\",\n\t\t\t\"get-overall-supply\",\n\t\t]),\n\t},\n];\n\nfunction indexByName(abi: AbiContract): Map<string, AbiFunction> {\n\tconst m = new Map<string, AbiFunction>();\n\tfor (const f of abi.functions) m.set(f.name, f);\n\treturn m;\n}\n\nfunction conformsTo(candidate: AbiContract, spec: StandardSpec): boolean {\n\tconst fns = indexByName(candidate);\n\tfor (const required of spec.abi.functions) {\n\t\tif (spec.optional.has(required.name)) continue;\n\t\tconst got = fns.get(required.name);\n\t\tif (!got) return false;\n\t\tif (got.access !== required.access) return false;\n\t\tif (got.args.length !== required.args.length) return false;\n\t}\n\treturn true;\n}\n\n/** Return the SIP standards a contract's ABI statically conforms to. */\nexport function classifyContract(abi: AbiContract): SipStandard[] {\n\tif (!abi || !Array.isArray(abi.functions)) return [];\n\treturn STANDARDS.filter((s) => conformsTo(abi, s)).map((s) => s.id);\n}\n\n/**\n * Parse the standards a contract *declares* via `(impl-trait …)` in its Clarity\n * source. Matched heuristically on the trait-reference name (robust across\n * mainnet/testnet principals + community variants) rather than an exact principal\n * allowlist. The ABI/RPC doesn't carry trait info, so source is the only declared\n * signal. `declared` is the high-confidence signal; `classifyContract` is the\n * catch-all for conforming-but-undeclared contracts.\n */\nexport function parseDeclaredStandards(claritySource: string): SipStandard[] {\n\tconst out = new Set<SipStandard>();\n\tconst matches = claritySource.matchAll(/\\(impl-trait\\s+[^)]+\\)/gi);\n\tfor (const m of matches) {\n\t\tconst ref = m[0].toLowerCase();\n\t\tif (ref.includes(\"sip-010\") || ref.includes(\".ft-trait\"))\n\t\t\tout.add(\"sip-010\");\n\t\tif (ref.includes(\"sip-009\") || ref.includes(\"nft-trait\"))\n\t\t\tout.add(\"sip-009\");\n\t\tif (ref.includes(\"sip-013\") || ref.includes(\"semi-fungible\"))\n\t\t\tout.add(\"sip-013\");\n\t}\n\treturn [...out];\n}\n",
|
|
8
|
+
"/**\n * Normalize a Clarity ABI from any source into the canonical `AbiContract`\n * shape this package's type extractors expect.\n *\n * Sources differ in small, load-bearing ways: the Hiro API and Clarinet SDK\n * emit `buffer`/`read_only` and wrap function outputs as `{ type: … }`, while\n * the canonical shape uses `buff`/`read-only` and a bare `AbiType`. Passing a\n * raw ABI straight through produces a value that LOOKS right and silently\n * fails the `AbiContract` constraint, so `event.input` / `.read.x()` typing\n * quietly degrades. Run it through here first.\n *\n * Lives in `@secondlayer/stacks/clarity` (not the CLI) so a raw ABI can be\n * normalized anywhere — scaffolds, MCP, a user's own script — without the CLI\n * installed.\n */\n\nimport type {\n\tAbiContract,\n\tAbiFunction,\n\tAbiFungibleToken,\n\tAbiMap,\n\tAbiNonFungibleToken,\n\tAbiTraitDefinition,\n\tAbiTraitFunction,\n\tAbiVariable,\n} from \"./contract.ts\";\nimport type { AbiType } from \"./types.ts\";\n\n/**\n * Normalize function access type from various formats to internal format\n */\nexport function normalizeAccess(\n\taccess: string,\n): \"public\" | \"read-only\" | \"private\" {\n\tif (access === \"read_only\") return \"read-only\";\n\treturn access as \"public\" | \"read-only\" | \"private\";\n}\n\n/**\n * Normalize a Clarity type from API format to internal format\n * Handles buffer vs buff, and recursively normalizes nested types\n */\nexport function normalizeType(type: unknown): AbiType {\n\tif (typeof type === \"string\") {\n\t\t// Handle string primitive types\n\t\tswitch (type) {\n\t\t\tcase \"uint128\":\n\t\t\tcase \"int128\":\n\t\t\tcase \"bool\":\n\t\t\tcase \"principal\":\n\t\t\tcase \"trait_reference\":\n\t\t\t\treturn type;\n\t\t\tdefault:\n\t\t\t\t// Unknown string type, return as-is\n\t\t\t\treturn type as AbiType;\n\t\t}\n\t}\n\n\tif (typeof type !== \"object\" || type === null) {\n\t\tthrow new Error(`Invalid ABI type: expected object, got ${typeof type}`);\n\t}\n\n\tconst typeObj = type as Record<string, unknown>;\n\n\t// Handle buffer vs buff (API uses buffer, we use buff)\n\tif (\"buffer\" in typeObj) {\n\t\tconst buffer = typeObj.buffer as { length?: number };\n\t\treturn {\n\t\t\tbuff: {\n\t\t\t\tlength: buffer?.length ?? 32,\n\t\t\t},\n\t\t};\n\t}\n\n\t// Already in internal format\n\tif (\"buff\" in typeObj) {\n\t\tconst buff = typeObj.buff as { length?: number };\n\t\treturn {\n\t\t\tbuff: {\n\t\t\t\tlength: buff?.length ?? 32,\n\t\t\t},\n\t\t};\n\t}\n\n\t// String types\n\tif (\"string-ascii\" in typeObj) {\n\t\tconst strAscii = typeObj[\"string-ascii\"] as { length?: number };\n\t\treturn {\n\t\t\t\"string-ascii\": {\n\t\t\t\tlength: strAscii?.length ?? 256,\n\t\t\t},\n\t\t};\n\t}\n\n\tif (\"string-utf8\" in typeObj) {\n\t\tconst strUtf8 = typeObj[\"string-utf8\"] as { length?: number };\n\t\treturn {\n\t\t\t\"string-utf8\": {\n\t\t\t\tlength: strUtf8?.length ?? 256,\n\t\t\t},\n\t\t};\n\t}\n\n\t// Response type - recursively normalize ok and error types\n\tif (\"response\" in typeObj) {\n\t\tconst response = typeObj.response as { ok?: unknown; error?: unknown };\n\t\treturn {\n\t\t\tresponse: {\n\t\t\t\tok: normalizeType(response?.ok ?? \"bool\"),\n\t\t\t\terror: normalizeType(response?.error ?? \"uint128\"),\n\t\t\t},\n\t\t};\n\t}\n\n\t// Optional type - recursively normalize inner type\n\tif (\"optional\" in typeObj) {\n\t\treturn {\n\t\t\toptional: normalizeType(typeObj.optional),\n\t\t};\n\t}\n\n\t// List type - recursively normalize element type\n\tif (\"list\" in typeObj) {\n\t\tconst list = typeObj.list as { type?: unknown; length?: number };\n\t\treturn {\n\t\t\tlist: {\n\t\t\t\ttype: normalizeType(list?.type ?? \"uint128\"),\n\t\t\t\tlength: list?.length ?? 100,\n\t\t\t},\n\t\t};\n\t}\n\n\t// Tuple type - recursively normalize field types\n\tif (\"tuple\" in typeObj) {\n\t\tconst tuple = typeObj.tuple as Array<{ name: string; type: unknown }>;\n\t\treturn {\n\t\t\ttuple: tuple.map((field) => ({\n\t\t\t\tname: field.name,\n\t\t\t\ttype: normalizeType(field.type),\n\t\t\t})),\n\t\t};\n\t}\n\n\t// Unknown type - fail explicitly\n\tthrow new Error(`Unknown ABI type structure: ${JSON.stringify(type)}`);\n}\n\n/**\n * Normalize a function definition from API format to internal format\n */\nexport function normalizeFunction(func: Record<string, unknown>): AbiFunction {\n\tconst access = normalizeAccess(func.access as string);\n\tconst args = (func.args as Array<{ name: string; type: unknown }>) ?? [];\n\tconst outputs = func.outputs as { type?: unknown } | unknown;\n\n\treturn {\n\t\tname: func.name as string,\n\t\taccess,\n\t\targs: args.map((arg) => ({\n\t\t\tname: arg.name,\n\t\t\ttype: normalizeType(arg.type),\n\t\t})),\n\t\toutputs: normalizeType(\n\t\t\ttypeof outputs === \"object\" && outputs !== null && \"type\" in outputs\n\t\t\t\t? (outputs as { type: unknown }).type\n\t\t\t\t: outputs,\n\t\t),\n\t};\n}\n\n/**\n * Normalize a map definition from API format to internal format\n */\nexport function normalizeMap(map: Record<string, unknown>): AbiMap {\n\treturn {\n\t\tname: map.name as string,\n\t\tkey: normalizeType(map.key),\n\t\tvalue: normalizeType(map.value),\n\t};\n}\n\n/**\n * Normalize a variable definition from API format to internal format\n */\nexport function normalizeVariable(\n\tvariable: Record<string, unknown>,\n): AbiVariable {\n\treturn {\n\t\tname: variable.name as string,\n\t\ttype: normalizeType(variable.type),\n\t\taccess: variable.access as \"constant\" | \"variable\",\n\t};\n}\n\n/**\n * Normalize a fungible-token definition. Only the name is carried on the wire.\n */\nexport function normalizeFungibleToken(\n\ttoken: Record<string, unknown>,\n): AbiFungibleToken {\n\treturn { name: token.name as string };\n}\n\n/**\n * Normalize a non-fungible-token definition, including its identifier type.\n */\nexport function normalizeNonFungibleToken(\n\ttoken: Record<string, unknown>,\n): AbiNonFungibleToken {\n\treturn { name: token.name as string, type: normalizeType(token.type) };\n}\n\n/**\n * Normalize a `define-trait` definition. A trait cannot declare private\n * functions, so any that show up are dropped rather than cast through.\n */\nexport function normalizeTraitDefinition(\n\ttrait: Record<string, unknown>,\n): AbiTraitDefinition {\n\tconst rawFunctions = Array.isArray(trait.functions) ? trait.functions : [];\n\tconst functions: AbiTraitFunction[] = [];\n\n\tfor (const func of rawFunctions) {\n\t\tif (typeof func !== \"object\" || func === null) continue;\n\t\tconst normalized = normalizeFunction(func as Record<string, unknown>);\n\t\tif (normalized.access === \"private\") continue;\n\t\tfunctions.push(normalized as AbiTraitFunction);\n\t}\n\n\treturn { name: trait.name as string, functions };\n}\n\n/**\n * Normalize an entire ABI from various sources to consistent internal format\n *\n * This handles ABIs from:\n * - Hiro API responses\n * - Clarinet SDK\n * - Upstream @secondlayer/stacks types\n */\nexport function normalizeAbi(abi: unknown): AbiContract {\n\tif (typeof abi !== \"object\" || abi === null) {\n\t\treturn { functions: [] };\n\t}\n\n\tconst abiObj = abi as Record<string, unknown>;\n\n\tconst functions: AbiFunction[] = [];\n\tconst maps: AbiMap[] = [];\n\tconst variables: AbiVariable[] = [];\n\tconst fungibleTokens: AbiFungibleToken[] = [];\n\tconst nonFungibleTokens: AbiNonFungibleToken[] = [];\n\tconst implementedTraits: string[] = [];\n\tconst definedTraits: AbiTraitDefinition[] = [];\n\n\t// Normalize functions\n\tif (Array.isArray(abiObj.functions)) {\n\t\tfor (const func of abiObj.functions) {\n\t\t\tif (typeof func === \"object\" && func !== null) {\n\t\t\t\tfunctions.push(normalizeFunction(func as Record<string, unknown>));\n\t\t\t}\n\t\t}\n\t}\n\n\t// Normalize maps\n\tif (Array.isArray(abiObj.maps)) {\n\t\tfor (const map of abiObj.maps) {\n\t\t\tif (typeof map === \"object\" && map !== null) {\n\t\t\t\tmaps.push(normalizeMap(map as Record<string, unknown>));\n\t\t\t}\n\t\t}\n\t}\n\n\t// Normalize variables\n\tif (Array.isArray(abiObj.variables)) {\n\t\tfor (const variable of abiObj.variables) {\n\t\t\tif (typeof variable === \"object\" && variable !== null) {\n\t\t\t\tvariables.push(normalizeVariable(variable as Record<string, unknown>));\n\t\t\t}\n\t\t}\n\t}\n\n\t// Token and trait definitions are declarations, not shapes to convert — but\n\t// dropping them makes a normalized ABI lossy, and callers do read them (an\n\t// `ft_transfer` filter needs `contract::asset`, not just the contract).\n\tif (Array.isArray(abiObj.fungible_tokens)) {\n\t\tfor (const token of abiObj.fungible_tokens) {\n\t\t\tif (typeof token === \"object\" && token !== null) {\n\t\t\t\tfungibleTokens.push(\n\t\t\t\t\tnormalizeFungibleToken(token as Record<string, unknown>),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (Array.isArray(abiObj.non_fungible_tokens)) {\n\t\tfor (const token of abiObj.non_fungible_tokens) {\n\t\t\tif (typeof token === \"object\" && token !== null) {\n\t\t\t\tnonFungibleTokens.push(\n\t\t\t\t\tnormalizeNonFungibleToken(token as Record<string, unknown>),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Neither the Clarinet SDK's `IContractInterface` nor the Hiro interface\n\t// response carries traits today; these two branches keep an ABI that does\n\t// have them (a hand-written config, a source-read ABI) round-tripping.\n\tif (Array.isArray(abiObj.implemented_traits)) {\n\t\tfor (const trait of abiObj.implemented_traits) {\n\t\t\tif (typeof trait === \"string\") implementedTraits.push(trait);\n\t\t}\n\t}\n\n\tif (Array.isArray(abiObj.defined_traits)) {\n\t\tfor (const trait of abiObj.defined_traits) {\n\t\t\tif (typeof trait === \"object\" && trait !== null) {\n\t\t\t\tdefinedTraits.push(\n\t\t\t\t\tnormalizeTraitDefinition(trait as Record<string, unknown>),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tfunctions,\n\t\tmaps: maps.length > 0 ? maps : undefined,\n\t\tvariables: variables.length > 0 ? variables : undefined,\n\t\tfungible_tokens: fungibleTokens.length > 0 ? fungibleTokens : undefined,\n\t\tnon_fungible_tokens:\n\t\t\tnonFungibleTokens.length > 0 ? nonFungibleTokens : undefined,\n\t\timplemented_traits:\n\t\t\timplementedTraits.length > 0 ? implementedTraits : undefined,\n\t\tdefined_traits: definedTraits.length > 0 ? definedTraits : undefined,\n\t};\n}\n"
|
|
9
|
+
],
|
|
10
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASO,SAAS,WAAW,CAC1B,KACA,WAA+B,OACV;AAAA,EACrB,QAAQ,IAAI;AAAA,SACN;AAAA,MACJ,OAAO;AAAA,SACH;AAAA,MACJ,OAAO;AAAA,SACH;AAAA,MACJ,OAAO,IAAI,MAAM,SAAS;AAAA,SACtB;AAAA,MACJ,OAAO,IAAI,IAAI,MAAM,SAAS;AAAA,SAC1B;AAAA,MACJ,IAAI,aAAa,YAAY;AAAA,QAC5B,MAAM,MAAM,aAA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AAW,SAAS,OAAO,qBAAqB;AAAA,MAC/C,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAAA,QAChD,kBAAkB,KACjB,0BAA0B,KAAgC,CAC3D;AAAA,MACD;AAAA,IACD;AAAA,EACD;AAAA,EAKA,IAAI,MAAM,QAAQ,OAAO,kBAAkB,GAAG;AAAA,IAC7C,WAAW,SAAS,OAAO,oBAAoB;AAAA,MAC9C,IAAI,OAAO,UAAU;AAAA,QAAU,kBAAkB,KAAK,KAAK;AAAA,IAC5D;AAAA,EACD;AAAA,EAEA,IAAI,MAAM,QAAQ,OAAO,cAAc,GAAG;AAAA,IACzC,WAAW,SAAS,OAAO,gBAAgB;AAAA,MAC1C,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAAA,QAChD,cAAc,KACb,yBAAyB,KAAgC,CAC1D;AAAA,MACD;AAAA,IACD;AAAA,EACD;AAAA,EAEA,OAAO;AAAA,IACN;AAAA,IACA,MAAM,KAAK,SAAS,IAAI,OAAO;AAAA,IAC/B,WAAW,UAAU,SAAS,IAAI,YAAY;AAAA,IAC9C,iBAAiB,eAAe,SAAS,IAAI,iBAAiB;AAAA,IAC9D,qBACC,kBAAkB,SAAS,IAAI,oBAAoB;AAAA,IACpD,oBACC,kBAAkB,SAAS,IAAI,oBAAoB;AAAA,IACpD,gBAAgB,cAAc,SAAS,IAAI,gBAAgB;AAAA,EAC5D;AAAA;",
|
|
11
|
+
"debugId": "80FCD2146E22850B64756E2164756E21",
|
|
12
|
+
"names": []
|
|
13
|
+
}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
BaseError
|
|
3
|
-
} from "./stacks-709tra19.js";
|
|
4
1
|
import {
|
|
5
2
|
deserializeCVBytes,
|
|
6
3
|
serializeCVBytes
|
|
7
|
-
} from "./stacks-
|
|
4
|
+
} from "./stacks-69nq48jp.js";
|
|
5
|
+
import {
|
|
6
|
+
BaseError
|
|
7
|
+
} from "./stacks-4hs8r4q2.js";
|
|
8
8
|
import {
|
|
9
9
|
parseContractId
|
|
10
|
-
} from "./stacks-
|
|
10
|
+
} from "./stacks-4d7c3x27.js";
|
|
11
11
|
import {
|
|
12
12
|
bytesToHex,
|
|
13
13
|
with0x
|
|
@@ -23,8 +23,8 @@ async function readContract(client, params) {
|
|
|
23
23
|
const [address, name] = parseContractId(params.contract);
|
|
24
24
|
const sender = params.sender ?? address;
|
|
25
25
|
const serializedArgs = (params.args ?? []).map((arg) => with0x(bytesToHex(serializeCVBytes(arg))));
|
|
26
|
-
const path = `/v2/contracts/call-read/${address}/${name}/${params.functionName}`;
|
|
27
|
-
const data = await client.request(params.tip ? `${path}?tip=${params.tip}` : path, {
|
|
26
|
+
const path = `/v2/contracts/call-read/${encodeURIComponent(address)}/${encodeURIComponent(name)}/${encodeURIComponent(params.functionName)}`;
|
|
27
|
+
const data = await client.request(params.tip ? `${path}?tip=${encodeURIComponent(params.tip)}` : path, {
|
|
28
28
|
method: "POST",
|
|
29
29
|
body: {
|
|
30
30
|
sender,
|
|
@@ -39,5 +39,5 @@ async function readContract(client, params) {
|
|
|
39
39
|
|
|
40
40
|
export { MalformedResponseError, readContract };
|
|
41
41
|
|
|
42
|
-
//# debugId=
|
|
43
|
-
//# sourceMappingURL=stacks-
|
|
42
|
+
//# debugId=779EB9422D78AD1664756E2164756E21
|
|
43
|
+
//# sourceMappingURL=stacks-ga026yxz.js.map
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
"sources": ["../src/errors/response.ts", "../src/actions/public/readContract.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"import { BaseError } from \"./base.ts\";\n\n/** Thrown when a node/API response is missing an expected field. */\nexport class MalformedResponseError extends BaseError {\n\toverride name = \"MalformedResponseError\";\n}\n",
|
|
6
|
-
"import { deserializeCVBytes } from \"../../clarity/deserialize.ts\";\nimport { serializeCVBytes } from \"../../clarity/serialize.ts\";\nimport type { ClarityValue } from \"../../clarity/types.ts\";\nimport type { Client } from \"../../clients/types.ts\";\nimport { parseContractId } from \"../../utils/address.ts\";\nimport { bytesToHex, with0x } from \"../../utils/encoding.ts\";\n\nexport type ReadContractParams = {\n\tcontract: string; // \"address.name\"\n\tfunctionName: string;\n\targs?: ClarityValue[];\n\tsender?: string;\n\t/**\n\t * Nakamoto StacksBlockId to evaluate against. Without it the node answers\n\t * at its own moving tip, which makes a read non-deterministic — the same\n\t * reindex of the same block can return a different value.\n\t */\n\ttip?: string;\n};\n\nexport async function readContract<T extends ClarityValue = ClarityValue>(\n\tclient: Client,\n\tparams: ReadContractParams,\n): Promise<T> {\n\tconst [address, name] = parseContractId(params.contract);\n\tconst sender = params.sender ?? address;\n\n\tconst serializedArgs = (params.args ?? []).map((arg) =>\n\t\twith0x(bytesToHex(serializeCVBytes(arg))),\n\t);\n\n\tconst path = `/v2/contracts/call-read/${address}/${name}/${params.functionName}`;\n\tconst data = await client.request(\n\t\tparams.tip ? `${path}?tip=${params.tip}` : path,\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tbody: {\n\t\t\t\tsender,\n\t\t\t\targuments: serializedArgs,\n\t\t\t},\n\t\t},\n\t);\n\n\tif (data.okay) {\n\t\treturn deserializeCVBytes<T>(data.result);\n\t}\n\tthrow new Error(data.cause ?? \"Read-only call failed\");\n}\n"
|
|
6
|
+
"import { deserializeCVBytes } from \"../../clarity/deserialize.ts\";\nimport { serializeCVBytes } from \"../../clarity/serialize.ts\";\nimport type { ClarityValue } from \"../../clarity/types.ts\";\nimport type { Client } from \"../../clients/types.ts\";\nimport { parseContractId } from \"../../utils/address.ts\";\nimport { bytesToHex, with0x } from \"../../utils/encoding.ts\";\n\nexport type ReadContractParams = {\n\tcontract: string; // \"address.name\"\n\tfunctionName: string;\n\targs?: ClarityValue[];\n\tsender?: string;\n\t/**\n\t * Nakamoto StacksBlockId to evaluate against. Without it the node answers\n\t * at its own moving tip, which makes a read non-deterministic — the same\n\t * reindex of the same block can return a different value.\n\t */\n\ttip?: string;\n};\n\nexport async function readContract<T extends ClarityValue = ClarityValue>(\n\tclient: Client,\n\tparams: ReadContractParams,\n): Promise<T> {\n\tconst [address, name] = parseContractId(params.contract);\n\tconst sender = params.sender ?? address;\n\n\tconst serializedArgs = (params.args ?? []).map((arg) =>\n\t\twith0x(bytesToHex(serializeCVBytes(arg))),\n\t);\n\n\tconst path = `/v2/contracts/call-read/${encodeURIComponent(address)}/${encodeURIComponent(name)}/${encodeURIComponent(params.functionName)}`;\n\tconst data = await client.request(\n\t\tparams.tip ? `${path}?tip=${encodeURIComponent(params.tip)}` : path,\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tbody: {\n\t\t\t\tsender,\n\t\t\t\targuments: serializedArgs,\n\t\t\t},\n\t\t},\n\t);\n\n\tif (data.okay) {\n\t\treturn deserializeCVBytes<T>(data.result);\n\t}\n\tthrow new Error(data.cause ?? \"Read-only call failed\");\n}\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": ";;;;;;;;;;;;;;;;AAGO,MAAM,+BAA+B,UAAU;AAAA,EAC5C,OAAO;AACjB;;;ACeA,eAAsB,YAAmD,CACxE,QACA,QACa;AAAA,EACb,OAAO,SAAS,QAAQ,gBAAgB,OAAO,QAAQ;AAAA,EACvD,MAAM,SAAS,OAAO,UAAU;AAAA,EAEhC,MAAM,kBAAkB,OAAO,QAAQ,CAAC,GAAG,IAAI,CAAC,QAC/C,OAAO,WAAW,iBAAiB,GAAG,CAAC,CAAC,CACzC;AAAA,EAEA,MAAM,OAAO,2BAA2B,
|
|
9
|
-
"debugId": "
|
|
8
|
+
"mappings": ";;;;;;;;;;;;;;;;AAGO,MAAM,+BAA+B,UAAU;AAAA,EAC5C,OAAO;AACjB;;;ACeA,eAAsB,YAAmD,CACxE,QACA,QACa;AAAA,EACb,OAAO,SAAS,QAAQ,gBAAgB,OAAO,QAAQ;AAAA,EACvD,MAAM,SAAS,OAAO,UAAU;AAAA,EAEhC,MAAM,kBAAkB,OAAO,QAAQ,CAAC,GAAG,IAAI,CAAC,QAC/C,OAAO,WAAW,iBAAiB,GAAG,CAAC,CAAC,CACzC;AAAA,EAEA,MAAM,OAAO,2BAA2B,mBAAmB,OAAO,KAAK,mBAAmB,IAAI,KAAK,mBAAmB,OAAO,YAAY;AAAA,EACzI,MAAM,OAAO,MAAM,OAAO,QACzB,OAAO,MAAM,GAAG,YAAY,mBAAmB,OAAO,GAAG,MAAM,MAC/D;AAAA,IACC,QAAQ;AAAA,IACR,MAAM;AAAA,MACL;AAAA,MACA,WAAW;AAAA,IACZ;AAAA,EACD,CACD;AAAA,EAEA,IAAI,KAAK,MAAM;AAAA,IACd,OAAO,mBAAsB,KAAK,MAAM;AAAA,EACzC;AAAA,EACA,MAAM,IAAI,MAAM,KAAK,SAAS,uBAAuB;AAAA;",
|
|
9
|
+
"debugId": "779EB9422D78AD1664756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
|
@@ -8,8 +8,8 @@ async function readContract(client, params) {
|
|
|
8
8
|
const [address, name] = parseContractId(params.contract);
|
|
9
9
|
const sender = params.sender ?? address;
|
|
10
10
|
const serializedArgs = (params.args ?? []).map((arg) => with0x(bytesToHex(serializeCVBytes(arg))));
|
|
11
|
-
const path = `/v2/contracts/call-read/${address}/${name}/${params.functionName}`;
|
|
12
|
-
const data = await client.request(params.tip ? `${path}?tip=${params.tip}` : path, {
|
|
11
|
+
const path = `/v2/contracts/call-read/${encodeURIComponent(address)}/${encodeURIComponent(name)}/${encodeURIComponent(params.functionName)}`;
|
|
12
|
+
const data = await client.request(params.tip ? `${path}?tip=${encodeURIComponent(params.tip)}` : path, {
|
|
13
13
|
method: "POST",
|
|
14
14
|
body: {
|
|
15
15
|
sender,
|
|
@@ -22,5 +22,5 @@ async function readContract(client, params) {
|
|
|
22
22
|
throw new Error(data.cause ?? "Read-only call failed");
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
//# debugId=
|
|
26
|
-
//# sourceMappingURL=stacks-
|
|
25
|
+
//# debugId=4D60ABB15BA3624064756E2164756E21
|
|
26
|
+
//# sourceMappingURL=stacks-ggdz96r1.cjs.map
|