@gala-chain/gala-core-sdk 1.2.1 → 1.3.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -5
- package/dist/browser/classes/error_catalog.js +1 -1
- package/dist/browser/classes/error_catalog.js.map +1 -1
- package/dist/browser/classes/error_phase_table.js +1 -1
- package/dist/browser/classes/error_phase_table.js.map +1 -1
- package/dist/browser/index.js +1 -1
- package/dist/browser/utils/dto_operation.js +1 -1
- package/dist/browser/utils/dto_operation.js.map +1 -1
- package/dist/browser/utils/transport.js +1 -1
- package/dist/browser/utils/transport.js.map +1 -1
- package/dist/browser/version.js +1 -1
- package/dist/browser/version.js.map +1 -1
- package/dist/browser/writes/dto_expiry.js +2 -0
- package/dist/browser/writes/dto_expiry.js.map +1 -0
- package/dist/browser/writes/gateway_writes.js +1 -1
- package/dist/browser/writes/gateway_writes.js.map +1 -1
- package/dist/browser/writes/identity.js +1 -1
- package/dist/browser/writes/identity.js.map +1 -1
- package/dist/browser/writes/token_ref.js +1 -1
- package/dist/browser/writes/token_ref.js.map +1 -1
- package/dist/browser/writes/transfer.js +1 -1
- package/dist/browser/writes/transfer.js.map +1 -1
- package/dist/browser/writes/types.js.map +1 -1
- package/dist/index.cjs +124 -20
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +101 -8
- package/dist/index.d.ts +101 -8
- package/dist/index.mjs +121 -21
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{GalaSDKError as e,isGalaError as t,parseJson as n}from"../classes/gala_sdk_error.js";import"../version.js";function r(e,t){if(t===1/0)return()=>void 0;let n=setTimeout(()=>e.abort(),t);return()=>clearTimeout(n)}function i(t,n){if(t===1/0||Number.isFinite(t)&&t>0)return t;throw new e(`INVALID_TIMEOUT`,{field:n,value:t})}const a=/[A-Za-z0-9\-._~!'()*$|:,]/u;function o(e){let t=``;for(let n of e)n===` `?t+=`+`:a.test(n)?t+=n:t+=s(n);return t}function s(e){try{return encodeURIComponent(e)}catch{return`%EF%BF%BD`}}function c(e,t=`standard`){return t===`readable`?Object.entries(e).map(([e,t])=>`${o(e)}=${o(t)}`).join(`&`):new URLSearchParams(e).toString()}function l(e,t={}){let n=/* @__PURE__ */ new Map,r=(e,t=!1)=>{for(let[r,i]of Object.entries(e??{}))t&&n.delete(r.toLowerCase()),n.set(r.toLowerCase(),[r,i])};return e?.userAgent!==!1&&r({"User-Agent":e?.userAgent??`GalaChain-SDK/1.
|
|
1
|
+
import{GalaSDKError as e,isGalaError as t,parseJson as n}from"../classes/gala_sdk_error.js";import"../version.js";function r(e,t){if(t===1/0)return()=>void 0;let n=setTimeout(()=>e.abort(),t);return()=>clearTimeout(n)}function i(t,n){if(t===1/0||Number.isFinite(t)&&t>0)return t;throw new e(`INVALID_TIMEOUT`,{field:n,value:t})}const a=/[A-Za-z0-9\-._~!'()*$|:,]/u;function o(e){let t=``;for(let n of e)n===` `?t+=`+`:a.test(n)?t+=n:t+=s(n);return t}function s(e){try{return encodeURIComponent(e)}catch{return`%EF%BF%BD`}}function c(e,t=`standard`){return t===`readable`?Object.entries(e).map(([e,t])=>`${o(e)}=${o(t)}`).join(`&`):new URLSearchParams(e).toString()}function l(e,t={}){let n=/* @__PURE__ */ new Map,r=(e,t=!1)=>{for(let[r,i]of Object.entries(e??{}))t&&n.delete(r.toLowerCase()),n.set(r.toLowerCase(),[r,i])};return e?.userAgent!==!1&&r({"User-Agent":e?.userAgent??`GalaChain-SDK/1.3.0-rc.0`}),r(t.defaults),r(e?.headers),t.json===!0&&!n.has(`content-type`)&&r({"Content-Type":`application/json`}),r(t.fixed,!0),Object.fromEntries(n.values())}const u=async(t,n)=>{try{return await fetch(t,n)}catch(r){throw n?.signal?.aborted===!0?r:new e(`TRANSPORT_ERROR`,{url:t},{url:t,cause:r})}};async function d(n,i,a,o,s){let c=new AbortController,l=r(c,o),u=a.signal,d=()=>c.abort();u?.addEventListener(`abort`,d,{once:!0});let f=s?.write===!1;try{return await n(i,{...a,signal:c.signal})}catch(n){throw u?.aborted===!0?n:c.signal.aborted?new e(`REQUEST_TIMEOUT`,{url:i,timeoutMs:o},{url:i,cause:n,...f?{write:!1}:{}}):f&&t(n,`TRANSPORT_ERROR`)&&n.write?new e(`TRANSPORT_ERROR`,{url:n.url??i},{url:n.url??i,cause:n.cause,write:!1}):n}finally{l(),u?.removeEventListener(`abort`,d)}}async function f(e){let t=await e.text();return n(t)??t}function p(e,t){let n=e.headers;if(n===void 0)return;if(g(n)){let e=n.get(t);return e===null||e===``?void 0:e}let r=Object.entries(n).find(([e])=>e.toLowerCase()===t.toLowerCase())?.[1];return r===void 0||r===``?void 0:r}function m(e){let t=p(e,`retry-after`);if(t===void 0)return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}function h(e,t=`x-block-number`){let n=p(e,t);if(n===void 0)return;let r=Number(n);return Number.isInteger(r)&&r>=0?r:void 0}function g(e){return`get`in e&&typeof e.get==`function`}export{r as armTimeout,c as buildQueryString,l as buildRequestHeaders,u as fetchRequestor,h as readBlockNumberHeader,p as readHeader,f as readResponseBody,m as readRetryAfter,d as requestWithTimeout,i as validateTimeoutMs};
|
|
2
2
|
//# sourceMappingURL=transport.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.js","names":["armTimeout","timeoutMs","timer","controller","validateTimeoutMs","GalaSDKError","name","READABLE_QUERY_SAFE","encodeReadable","out","char","text","encodeScalar","buildQueryString","encoding","params","key","value","buildRequestHeaders","entries","put","headers","last","wire","parts","fetchRequestor","url","init","error","requestWithTimeout","disarm","externalSignal","options","abortFromCaller","read","kind","requestor","isGalaError","readResponseBody","response","parseJson","readHeader","hasHeaderGetter","readRetryAfter","raw","seconds","timestamp","readBlockNumberHeader","headerName","blockNumber"],"sources":["../../../src/utils/transport.ts"],"sourcesContent":["import type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { GalaSDKError, isGalaError, parseJson } from '../classes/gala_sdk_error.js';\nimport { GALA_CORE_SDK_VERSION } from '../version.js';\n\n/**\n * Arms the abort timer for a request. `Infinity` means \"never time out\": `setTimeout` would turn\n * it into 1 ms, so no timer is armed at all. Returns a function that disarms it.\n */\nexport function armTimeout(controller: AbortController, timeoutMs: number): () => void {\n if (timeoutMs === Infinity) return () => undefined;\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return () => clearTimeout(timer);\n}\n\n/**\n * Validates a request timeout in milliseconds: a positive finite number, or `Infinity` for none.\n *\n * @throws GalaSDKError `INVALID_TIMEOUT` (`params.field` = `name`) otherwise.\n */\nexport function validateTimeoutMs(timeoutMs: number, name: string): number {\n if (timeoutMs === Infinity || (Number.isFinite(timeoutMs) && timeoutMs > 0)) return timeoutMs;\n throw new GalaSDKError('INVALID_TIMEOUT', { field: name, value: timeoutMs });\n}\n\nconst READABLE_QUERY_SAFE = /[A-Za-z0-9\\-._~!'()*$|:,]/u;\n\nfunction encodeReadable(text: string): string {\n let out = '';\n for (const char of text) {\n if (char === ' ') out += '+';\n else if (READABLE_QUERY_SAFE.test(char)) out += char;\n else out += encodeScalar(char);\n }\n return out;\n}\n\n/** Percent-encodes one code point; a lone surrogate becomes U+FFFD, as `URLSearchParams` does. */\nfunction encodeScalar(char: string): string {\n try {\n return encodeURIComponent(char);\n } catch {\n return '%EF%BF%BD';\n }\n}\n\n/** Serializes GET parameters, in insertion order, in the encoding the wire options select. */\nexport function buildQueryString(\n params: Record<string, string>,\n encoding: WireOptions['queryEncoding'] = 'standard',\n): string {\n if (encoding === 'readable') {\n return Object.entries(params)\n .map(([key, value]) => `${encodeReadable(key)}=${encodeReadable(value)}`)\n .join('&');\n }\n return new URLSearchParams(params).toString();\n}\n\n/** What an SDK request adds to the headers the wire options describe. */\nexport interface RequestHeaderParts {\n /** The request carries a JSON body: `Content-Type: application/json` unless `wire.headers` sets one. */\n json?: boolean | undefined;\n /** Headers the SDK sends unless `wire.headers` replaces them (for example `Accept`). */\n defaults?: Record<string, string> | undefined;\n /**\n * Headers that carry the request's meaning (`X-Wallet-Address`, `X-Shadow`). They come last and\n * replace a same-named `wire.headers` entry, so an app's static headers can never re-attribute\n * or un-shadow a write.\n */\n fixed?: Record<string, string> | undefined;\n}\n\n/**\n * The request headers for ANY SDK request, GET or POST, from one place so the wire options reach\n * every request alike. Order, which is the order the requestor sees them in: `User-Agent`\n * (`wire.userAgent`, default `GalaChain-SDK/<version>`, `false` omits it), `parts.defaults`,\n * `wire.headers`, `Content-Type` (JSON bodies only), `parts.fixed`. A later entry replaces an\n * earlier one of the same name regardless of case, so a header is never sent twice.\n */\nexport function buildRequestHeaders(\n wire: WireOptions | undefined,\n parts: RequestHeaderParts = {},\n): Record<string, string> {\n const entries = new Map<string, [name: string, value: string]>();\n const put = (headers: Record<string, string> | undefined, last = false): void => {\n for (const [name, value] of Object.entries(headers ?? {})) {\n // A fixed header leaves any earlier same-named entry behind, so it also keeps its place at the end.\n if (last) entries.delete(name.toLowerCase());\n entries.set(name.toLowerCase(), [name, value]);\n }\n };\n if (wire?.userAgent !== false) {\n put({ 'User-Agent': wire?.userAgent ?? `GalaChain-SDK/${GALA_CORE_SDK_VERSION}` });\n }\n put(parts.defaults);\n put(wire?.headers);\n if (parts.json === true && !entries.has('content-type')) {\n put({ 'Content-Type': 'application/json' });\n }\n put(parts.fixed, true);\n return Object.fromEntries(entries.values());\n}\n\n/**\n * The default requestor: the global `fetch`, with a failure before any answer (offline, DNS,\n * CORS) coded as `TRANSPORT_ERROR` and the original error kept as `cause`. An aborted request is\n * left to {@link requestWithTimeout}, which knows whether the timeout or the caller aborted it.\n * A requestor the app supplies is not wrapped: its rejection reaches the caller unchanged.\n */\nexport const fetchRequestor: HttpRequestor = async (url, init) => {\n try {\n return await fetch(url, init);\n } catch (error: unknown) {\n if (init?.signal?.aborted === true) throw error;\n throw new GalaSDKError('TRANSPORT_ERROR', { url }, { url, cause: error });\n }\n};\n\n/** What a request is, for the failures the transport raises itself (see {@link requestWithTimeout}). */\nexport interface RequestKind {\n /** `false` for a read: nothing it sends is applied, so its failures say `write: false`. */\n write: boolean;\n}\n\n/**\n * Sends one request through `requestor`, aborting it after `timeoutMs` (`REQUEST_TIMEOUT`). The\n * caller's own abort passes through as it is. `kind: { write: false }` marks a read: its\n * `REQUEST_TIMEOUT`, and a `TRANSPORT_ERROR` of the default requestors (which cannot tell a read\n * from a write), then say `write: false`. Without it they are judged as a write's (fail-closed),\n * which is what a write's transport needs before it decides what an unanswered write means.\n */\nexport async function requestWithTimeout(\n requestor: HttpRequestor,\n url: string,\n options: RequestInit,\n timeoutMs: number,\n kind?: RequestKind,\n): Promise<HTTPResponse> {\n const controller = new AbortController();\n const disarm = armTimeout(controller, timeoutMs);\n const externalSignal = options.signal;\n const abortFromCaller = (): void => controller.abort();\n externalSignal?.addEventListener('abort', abortFromCaller, { once: true });\n const read = kind?.write === false;\n try {\n return await requestor(url, { ...options, signal: controller.signal });\n } catch (error: unknown) {\n // The caller's own abort is theirs: it passes through as the abort it is, never as a timeout.\n if (externalSignal?.aborted === true) throw error;\n if (controller.signal.aborted) {\n throw new GalaSDKError(\n 'REQUEST_TIMEOUT',\n { url, timeoutMs },\n { url, cause: error, ...(read ? { write: false } : {}) },\n );\n }\n if (read && isGalaError(error, 'TRANSPORT_ERROR') && error.write) {\n throw new GalaSDKError(\n 'TRANSPORT_ERROR',\n { url: error.url ?? url },\n { url: error.url ?? url, cause: error.cause, write: false },\n );\n }\n // Anything else is the requestor's own rejection (an app's axios interceptor error, say):\n // rethrown as it is, because the app's error handling produced it.\n throw error;\n } finally {\n disarm();\n externalSignal?.removeEventListener('abort', abortFromCaller);\n }\n}\n\nexport async function readResponseBody(response: HTTPResponse): Promise<unknown> {\n const text = await response.text();\n return parseJson(text) ?? text;\n}\n\n/** Read a case-insensitive response header from either supported header shape. */\nexport function readHeader(response: HTTPResponse, name: string): string | undefined {\n const headers = response.headers;\n if (headers === undefined) return undefined;\n if (hasHeaderGetter(headers)) {\n const value = headers.get(name);\n return value === null || value === '' ? undefined : value;\n }\n const value = Object.entries(headers).find(\n ([key]) => key.toLowerCase() === name.toLowerCase(),\n )?.[1];\n return value === undefined || value === '' ? undefined : value;\n}\n\n/** Read a Retry-After header (delta-seconds or an HTTP date) as non-negative milliseconds. */\nexport function readRetryAfter(response: HTTPResponse): number | undefined {\n const raw = readHeader(response, 'retry-after');\n if (raw === undefined) return undefined;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n const timestamp = Date.parse(raw);\n return Number.isNaN(timestamp) ? undefined : Math.max(0, timestamp - Date.now());\n}\n\n/** Read a non-negative integer block number header. */\nexport function readBlockNumberHeader(\n response: HTTPResponse,\n headerName = 'x-block-number',\n): number | undefined {\n const raw = readHeader(response, headerName);\n if (raw === undefined) return undefined;\n const blockNumber = Number(raw);\n return Number.isInteger(blockNumber) && blockNumber >= 0 ? blockNumber : undefined;\n}\n\nfunction hasHeaderGetter(\n headers: NonNullable<HTTPResponse['headers']>,\n): headers is { get(name: string): string | null } {\n return 'get' in headers && typeof headers.get === 'function';\n}\n"],"mappings":"A,kHASA,SAAgBA,EAAW,EAA6B,EAA+B,CACrF,GAAIC,IAAc,IAAU,UAAa,IAAA,GACzC,IAAMC,EAAQ,eAAiBC,EAAW,MAAM,EAAGF,CAAS,EAC5D,UAAa,aAAaC,CAAK,CACjC,CAOA,SAAgBE,EAAkB,EAAmB,EAAsB,CACzE,GAAIH,IAAc,KAAa,OAAO,SAASA,CAAS,GAAKA,EAAY,EAAI,OAAOA,EACpF,MAAM,IAAII,EAAa,kBAAmB,CAAE,MAAOC,EAAM,MAAOL,CAAU,CAAC,CAC7E,CAEA,MAAMM,EAAsB,6BAE5B,SAASC,EAAe,EAAsB,CAC5C,IAAIC,EAAM,GACV,IAAK,IAAMC,KAAQC,EACbD,IA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AAQ,OAAO,QAAQI,CAAO,CAAC,CAAC,MACnC,CAACL,KAASA,EAAI,YAAY,IAAMV,EAAK,YAAY,CACpD,CAAC,GAAG,GACJ,OAAOW,IAAU,IAAA,IAAaA,IAAU,GAAK,IAAA,GAAYA,CAC3D,CAGA,SAAgB0B,EAAe,EAA4C,CACzE,IAAMC,EAAMH,EAAWF,EAAU,aAAa,EAC9C,GAAIK,IAAQ,IAAA,GAAW,OACvB,IAAMC,EAAU,OAAOD,CAAG,EAC1B,GAAI,OAAO,SAASC,CAAO,GAAKA,GAAW,EAAG,OAAOA,EAAU,IAC/D,IAAMC,EAAY,KAAK,MAAMF,CAAG,EAChC,OAAO,OAAO,MAAME,CAAS,EAAI,IAAA,GAAY,KAAK,IAAI,EAAGA,EAAY,KAAK,IAAI,CAAC,CACjF,CAGA,SAAgBC,EACd,EACA,EAAa,iBACO,CACpB,IAAMH,EAAMH,EAAWF,EAAUS,CAAU,EAC3C,GAAIJ,IAAQ,IAAA,GAAW,OACvB,IAAMK,EAAc,OAAOL,CAAG,EAC9B,OAAO,OAAO,UAAUK,CAAW,GAAKA,GAAe,EAAIA,EAAc,IAAA,EAC3E,CAEA,SAASP,EACP,EACiD,CACjD,MAAO,QAASrB,GAAW,OAAOA,EAAQ,KAAQ,UACpD,C"}
|
|
1
|
+
{"version":3,"file":"transport.js","names":["armTimeout","timeoutMs","timer","controller","validateTimeoutMs","GalaSDKError","name","READABLE_QUERY_SAFE","encodeReadable","out","char","text","encodeScalar","buildQueryString","encoding","params","key","value","buildRequestHeaders","entries","put","headers","last","wire","parts","fetchRequestor","url","init","error","requestWithTimeout","disarm","externalSignal","options","abortFromCaller","read","kind","requestor","isGalaError","readResponseBody","response","parseJson","readHeader","hasHeaderGetter","readRetryAfter","raw","seconds","timestamp","readBlockNumberHeader","headerName","blockNumber"],"sources":["../../../src/utils/transport.ts"],"sourcesContent":["import type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { GalaSDKError, isGalaError, parseJson } from '../classes/gala_sdk_error.js';\nimport { GALA_CORE_SDK_VERSION } from '../version.js';\n\n/**\n * Arms the abort timer for a request. `Infinity` means \"never time out\": `setTimeout` would turn\n * it into 1 ms, so no timer is armed at all. Returns a function that disarms it.\n */\nexport function armTimeout(controller: AbortController, timeoutMs: number): () => void {\n if (timeoutMs === Infinity) return () => undefined;\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return () => clearTimeout(timer);\n}\n\n/**\n * Validates a request timeout in milliseconds: a positive finite number, or `Infinity` for none.\n *\n * @throws GalaSDKError `INVALID_TIMEOUT` (`params.field` = `name`) otherwise.\n */\nexport function validateTimeoutMs(timeoutMs: number, name: string): number {\n if (timeoutMs === Infinity || (Number.isFinite(timeoutMs) && timeoutMs > 0)) return timeoutMs;\n throw new GalaSDKError('INVALID_TIMEOUT', { field: name, value: timeoutMs });\n}\n\nconst READABLE_QUERY_SAFE = /[A-Za-z0-9\\-._~!'()*$|:,]/u;\n\nfunction encodeReadable(text: string): string {\n let out = '';\n for (const char of text) {\n if (char === ' ') out += '+';\n else if (READABLE_QUERY_SAFE.test(char)) out += char;\n else out += encodeScalar(char);\n }\n return out;\n}\n\n/** Percent-encodes one code point; a lone surrogate becomes U+FFFD, as `URLSearchParams` does. */\nfunction encodeScalar(char: string): string {\n try {\n return encodeURIComponent(char);\n } catch {\n return '%EF%BF%BD';\n }\n}\n\n/** Serializes GET parameters, in insertion order, in the encoding the wire options select. */\nexport function buildQueryString(\n params: Record<string, string>,\n encoding: WireOptions['queryEncoding'] = 'standard',\n): string {\n if (encoding === 'readable') {\n return Object.entries(params)\n .map(([key, value]) => `${encodeReadable(key)}=${encodeReadable(value)}`)\n .join('&');\n }\n return new URLSearchParams(params).toString();\n}\n\n/** What an SDK request adds to the headers the wire options describe. */\nexport interface RequestHeaderParts {\n /** The request carries a JSON body: `Content-Type: application/json` unless `wire.headers` sets one. */\n json?: boolean | undefined;\n /** Headers the SDK sends unless `wire.headers` replaces them (for example `Accept`). */\n defaults?: Record<string, string> | undefined;\n /**\n * Headers that carry the request's meaning (`X-Wallet-Address`, `X-Shadow`). They come last and\n * replace a same-named `wire.headers` entry, so an app's static headers can never re-attribute\n * or un-shadow a write.\n */\n fixed?: Record<string, string> | undefined;\n}\n\n/**\n * The request headers for ANY SDK request, GET or POST, from one place so the wire options reach\n * every request alike. Order, which is the order the requestor sees them in: `User-Agent`\n * (`wire.userAgent`, default `GalaChain-SDK/<version>`, `false` omits it), `parts.defaults`,\n * `wire.headers`, `Content-Type` (JSON bodies only), `parts.fixed`. A later entry replaces an\n * earlier one of the same name regardless of case, so a header is never sent twice.\n */\nexport function buildRequestHeaders(\n wire: WireOptions | undefined,\n parts: RequestHeaderParts = {},\n): Record<string, string> {\n const entries = new Map<string, [name: string, value: string]>();\n const put = (headers: Record<string, string> | undefined, last = false): void => {\n for (const [name, value] of Object.entries(headers ?? {})) {\n // A fixed header leaves any earlier same-named entry behind, so it also keeps its place at the end.\n if (last) entries.delete(name.toLowerCase());\n entries.set(name.toLowerCase(), [name, value]);\n }\n };\n if (wire?.userAgent !== false) {\n put({ 'User-Agent': wire?.userAgent ?? `GalaChain-SDK/${GALA_CORE_SDK_VERSION}` });\n }\n put(parts.defaults);\n put(wire?.headers);\n if (parts.json === true && !entries.has('content-type')) {\n put({ 'Content-Type': 'application/json' });\n }\n put(parts.fixed, true);\n return Object.fromEntries(entries.values());\n}\n\n/**\n * The default requestor: the global `fetch`, with a failure before any answer (offline, DNS,\n * CORS) coded as `TRANSPORT_ERROR` and the original error kept as `cause`. An aborted request is\n * left to {@link requestWithTimeout}, which knows whether the timeout or the caller aborted it.\n * A requestor the app supplies is not wrapped: its rejection reaches the caller unchanged.\n */\nexport const fetchRequestor: HttpRequestor = async (url, init) => {\n try {\n return await fetch(url, init);\n } catch (error: unknown) {\n if (init?.signal?.aborted === true) throw error;\n throw new GalaSDKError('TRANSPORT_ERROR', { url }, { url, cause: error });\n }\n};\n\n/** What a request is, for the failures the transport raises itself (see {@link requestWithTimeout}). */\nexport interface RequestKind {\n /** `false` for a read: nothing it sends is applied, so its failures say `write: false`. */\n write: boolean;\n}\n\n/**\n * Sends one request through `requestor`, aborting it after `timeoutMs` (`REQUEST_TIMEOUT`). The\n * caller's own abort passes through as it is. `kind: { write: false }` marks a read: its\n * `REQUEST_TIMEOUT`, and a `TRANSPORT_ERROR` of the default requestors (which cannot tell a read\n * from a write), then say `write: false`. Without it they are judged as a write's (fail-closed),\n * which is what a write's transport needs before it decides what an unanswered write means.\n */\nexport async function requestWithTimeout(\n requestor: HttpRequestor,\n url: string,\n options: RequestInit,\n timeoutMs: number,\n kind?: RequestKind,\n): Promise<HTTPResponse> {\n const controller = new AbortController();\n const disarm = armTimeout(controller, timeoutMs);\n const externalSignal = options.signal;\n const abortFromCaller = (): void => controller.abort();\n externalSignal?.addEventListener('abort', abortFromCaller, { once: true });\n const read = kind?.write === false;\n try {\n return await requestor(url, { ...options, signal: controller.signal });\n } catch (error: unknown) {\n // The caller's own abort is theirs: it passes through as the abort it is, never as a timeout.\n if (externalSignal?.aborted === true) throw error;\n if (controller.signal.aborted) {\n throw new GalaSDKError(\n 'REQUEST_TIMEOUT',\n { url, timeoutMs },\n { url, cause: error, ...(read ? { write: false } : {}) },\n );\n }\n if (read && isGalaError(error, 'TRANSPORT_ERROR') && error.write) {\n throw new GalaSDKError(\n 'TRANSPORT_ERROR',\n { url: error.url ?? url },\n { url: error.url ?? url, cause: error.cause, write: false },\n );\n }\n // Anything else is the requestor's own rejection (an app's axios interceptor error, say):\n // rethrown as it is, because the app's error handling produced it.\n throw error;\n } finally {\n disarm();\n externalSignal?.removeEventListener('abort', abortFromCaller);\n }\n}\n\nexport async function readResponseBody(response: HTTPResponse): Promise<unknown> {\n const text = await response.text();\n return parseJson(text) ?? text;\n}\n\n/** Read a case-insensitive response header from either supported header shape. */\nexport function readHeader(response: HTTPResponse, name: string): string | undefined {\n const headers = response.headers;\n if (headers === undefined) return undefined;\n if (hasHeaderGetter(headers)) {\n const value = headers.get(name);\n return value === null || value === '' ? undefined : value;\n }\n const value = Object.entries(headers).find(\n ([key]) => key.toLowerCase() === name.toLowerCase(),\n )?.[1];\n return value === undefined || value === '' ? undefined : value;\n}\n\n/** Read a Retry-After header (delta-seconds or an HTTP date) as non-negative milliseconds. */\nexport function readRetryAfter(response: HTTPResponse): number | undefined {\n const raw = readHeader(response, 'retry-after');\n if (raw === undefined) return undefined;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n const timestamp = Date.parse(raw);\n return Number.isNaN(timestamp) ? undefined : Math.max(0, timestamp - Date.now());\n}\n\n/** Read a non-negative integer block number header. */\nexport function readBlockNumberHeader(\n response: HTTPResponse,\n headerName = 'x-block-number',\n): number | undefined {\n const raw = readHeader(response, headerName);\n if (raw === undefined) return undefined;\n const blockNumber = Number(raw);\n return Number.isInteger(blockNumber) && blockNumber >= 0 ? blockNumber : undefined;\n}\n\nfunction hasHeaderGetter(\n headers: NonNullable<HTTPResponse['headers']>,\n): headers is { get(name: string): string | null } {\n return 'get' in headers && typeof headers.get === 'function';\n}\n"],"mappings":"A,kHASA,SAAgBA,EAAW,EAA6B,EAA+B,CACrF,GAAIC,IAAc,IAAU,UAAa,IAAA,GACzC,IAAMC,EAAQ,eAAiBC,EAAW,MAAM,EAAGF,CAAS,EAC5D,UAAa,aAAaC,CAAK,CACjC,CAOA,SAAgBE,EAAkB,EAAmB,EAAsB,CACzE,GAAIH,IAAc,KAAa,OAAO,SAASA,CAAS,GAAKA,EAAY,EAAI,OAAOA,EACpF,MAAM,IAAII,EAAa,kBAAmB,CAAE,MAAOC,EAAM,MAAOL,CAAU,CAAC,CAC7E,CAEA,MAAMM,EAAsB,6BAE5B,SAASC,EAAe,EAAsB,CAC5C,IAAIC,EAAM,GACV,IAAK,IAAMC,KAAQC,EACbD,IAAS,IAAK,GAAO,IAChBH,EAAoB,KAAKG,CAAI,EAAG,GAAOA,EAC3C,GA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,IAAMV,EAAK,YAAY,CACpD,CAAC,GAAG,GACJ,OAAOW,IAAU,IAAA,IAAaA,IAAU,GAAK,IAAA,GAAYA,CAC3D,CAGA,SAAgB0B,EAAe,EAA4C,CACzE,IAAMC,EAAMH,EAAWF,EAAU,aAAa,EAC9C,GAAIK,IAAQ,IAAA,GAAW,OACvB,IAAMC,EAAU,OAAOD,CAAG,EAC1B,GAAI,OAAO,SAASC,CAAO,GAAKA,GAAW,EAAG,OAAOA,EAAU,IAC/D,IAAMC,EAAY,KAAK,MAAMF,CAAG,EAChC,OAAO,OAAO,MAAME,CAAS,EAAI,IAAA,GAAY,KAAK,IAAI,EAAGA,EAAY,KAAK,IAAI,CAAC,CACjF,CAGA,SAAgBC,EACd,EACA,EAAa,iBACO,CACpB,IAAMH,EAAMH,EAAWF,EAAUS,CAAU,EAC3C,GAAIJ,IAAQ,IAAA,GAAW,OACvB,IAAMK,EAAc,OAAOL,CAAG,EAC9B,OAAO,OAAO,UAAUK,CAAW,GAAKA,GAAe,EAAIA,EAAc,IAAA,EAC3E,CAEA,SAASP,EACP,EACiD,CACjD,MAAO,QAASrB,GAAW,OAAOA,EAAQ,KAAQ,UACpD,C"}
|
package/dist/browser/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=`1.
|
|
1
|
+
const e=`1.3.0-rc.0`;export{e as GALA_CORE_SDK_VERSION};
|
|
2
2
|
//# sourceMappingURL=version.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","names":["GALA_CORE_SDK_VERSION"],"sources":["../../src/version.ts"],"sourcesContent":["declare const __GALA_CORE_SDK_VERSION__: string | undefined;\n\n/**\n * The `@gala-chain/gala-core-sdk` package version, embedded by the bundler, with a source-test\n * fallback. It is the version in the default `User-Agent` (`GalaChain-SDK/<version>`) of every SDK\n * request, whichever product SDK sends it.\n */\nexport const GALA_CORE_SDK_VERSION =\n typeof __GALA_CORE_SDK_VERSION__ === 'string' ? __GALA_CORE_SDK_VERSION__ : '1.
|
|
1
|
+
{"version":3,"file":"version.js","names":["GALA_CORE_SDK_VERSION"],"sources":["../../src/version.ts"],"sourcesContent":["declare const __GALA_CORE_SDK_VERSION__: string | undefined;\n\n/**\n * The `@gala-chain/gala-core-sdk` package version, embedded by the bundler, with a source-test\n * fallback. It is the version in the default `User-Agent` (`GalaChain-SDK/<version>`) of every SDK\n * request, whichever product SDK sends it.\n */\nexport const GALA_CORE_SDK_VERSION =\n typeof __GALA_CORE_SDK_VERSION__ === 'string' ? __GALA_CORE_SDK_VERSION__ : '1.3.0-rc.0';\n"],"mappings":"AAOA,MAAaA,EAAA,a"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{GalaSDKError as e}from"../classes/gala_sdk_error.js";function t(t,n=`dtoExpiresAt`){if(typeof t!=`number`||!Number.isSafeInteger(t))throw new e(`INVALID_DTO_EXPIRES_AT`,{field:n,reason:`not_a_safe_integer`});if(t<=0)throw new e(`INVALID_DTO_EXPIRES_AT`,{field:n,reason:`not_positive`});return t}export{t as checkDtoExpiresAt};
|
|
2
|
+
//# sourceMappingURL=dto_expiry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dto_expiry.js","names":["checkDtoExpiresAt","value","GalaSDKError"],"sources":["../../../src/writes/dto_expiry.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\n\n/**\n * A signed DTO's `dtoExpiresAt`, checked: a JS number that is a safe integer of epoch\n * MILLISECONDS, greater than zero. Returned unchanged, so the signed value is the one given.\n *\n * Chain semantics (`@GalaTransaction`, before authorization): the chain refuses the DTO with\n * `ExpiredError` when `dto.dtoExpiresAt && dto.dtoExpiresAt < Date.now()` (its own clock, strict\n * less-than: a DTO is still accepted in the millisecond it expires). A falsy value is no expiry at\n * all, so `0` is refused here rather than signed as one. A DTO without the field stays valid on\n * chain: the field is optional and additive.\n *\n * This checks the field only; it applies no window against a clock (the wallet builder in\n * `@gala-games/wallet-core` adds the 60 s quote window and refuses an expired deadline).\n *\n * @throws GalaSDKError `INVALID_DTO_EXPIRES_AT` (`reason` `not_a_safe_integer` or `not_positive`,\n * `field` = `field`).\n */\nexport function checkDtoExpiresAt(value: unknown, field = 'dtoExpiresAt'): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value)) {\n throw new GalaSDKError('INVALID_DTO_EXPIRES_AT', { field, reason: 'not_a_safe_integer' });\n }\n if (value <= 0) {\n throw new GalaSDKError('INVALID_DTO_EXPIRES_AT', { field, reason: 'not_positive' });\n }\n return value;\n}\n"],"mappings":"A,4DAkBA,SAAgBA,EAAkB,EAAgB,EAAQ,eAAwB,CAChF,GAAI,OAAOC,GAAU,UAAY,CAAC,OAAO,cAAcA,CAAK,EAC1D,MAAM,IAAIC,EAAa,yBAA0B,CAAE,QAAO,OAAQ,oBAAqB,CAAC,EAE1F,GAAID,GAAS,EACX,MAAM,IAAIC,EAAa,yBAA0B,CAAE,QAAO,OAAQ,cAAe,CAAC,EAEpF,OAAOD,CACT,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"../_virtual/_@oxc-project_runtime@0.154.0/helpers/esm/defineProperty.js";import{GalaSDKError as t}from"../classes/gala_sdk_error.js";import{galaChainUserRef as n}from"./identity.js";import{fetchRequestor as r,validateTimeoutMs as i}from"../utils/transport.js";import{assertUniqueKey as a,createUniqueKey as o,resolveUniqueKeyPrefix as s}from"../utils/unique_key.js";import{lockExpires as
|
|
1
|
+
import e from"../_virtual/_@oxc-project_runtime@0.154.0/helpers/esm/defineProperty.js";import{GalaSDKError as t}from"../classes/gala_sdk_error.js";import{galaChainUserRef as n}from"./identity.js";import{fetchRequestor as r,validateTimeoutMs as i}from"../utils/transport.js";import{assertUniqueKey as a,createUniqueKey as o,resolveUniqueKeyPrefix as s}from"../utils/unique_key.js";import{checkDtoExpiresAt as c}from"./dto_expiry.js";import{lockExpires as l,lockName as u,lockTokenDto as d,unlockTokenDto as f}from"./lock.js";import{claimNftCollectionDto as p,claimedCollection as m,createNftCollectionDto as h,createdTokenClass as g,mintNftDto as _,mintedInstances as v,nftAuthorities as y,nftCallerPublicKey as b,nftClassPart as x,nftMintQuantity as S,nftString as C,nftText as w,nftTokenClass as T,nftWholeNumber as E}from"./nft.js";import{submitWrite as D}from"./submit.js";import{quoteNftFee as O}from"./nft_fee.js";import{checkQuantity as k,resolveToken as A}from"./token_ref.js";import{GALA_TOKEN_CLASS_KEY as j,burnTokensDto as M,transferTokenDto as N}from"./transfer.js";import{GATEWAY_WRITE_BATCH_LIMITS as P}from"./types.js";var F=class{constructor(a){e(this,`walletAddress`,void 0),e(this,`transport`,void 0),e(this,`uniqueKeyPrefix`,void 0),e(this,`tokenNameResolver`,void 0);let{signer:o,gatewayBaseUrl:c,httpRequestor:l,tokenNameResolver:u}=a;if(typeof o!=`object`||!o||typeof o.signObject!=`function`)throw new t(`INVALID_WRITES_OPTION`,{option:`signer`});if(typeof c!=`string`)throw new t(`INVALID_WRITES_OPTION`,{option:`gatewayBaseUrl`});if(l!==void 0&&typeof l!=`function`)throw new t(`INVALID_WRITES_OPTION`,{option:`httpRequestor`});if(u!==void 0&&(typeof u!=`object`||!u||typeof u.resolveTokenClassKey!=`function`))throw new t(`INVALID_WRITES_OPTION`,{option:`tokenNameResolver`});this.walletAddress=n(a.walletAddress,`walletAddress`),this.uniqueKeyPrefix=s(a.uniqueKeyPrefix),this.tokenNameResolver=u,this.transport={gatewayBaseUrl:c.replace(/\/+$/u,``),signer:o,requestor:l??r,timeoutMs:i(a.requestTimeoutMs??3e4,`requestTimeoutMs`),wire:a.wire}}transferGala(e){return this.transferToken({to:e.to,quantity:e.quantity,tokenClassKey:j,uniqueKey:e.uniqueKey,dtoExpiresAt:e.dtoExpiresAt})}async transferToken(e){let t=n(e.to,`to`),r=k(e,``),i=e.dtoExpiresAt===void 0?void 0:c(e.dtoExpiresAt),a=this.uniqueKeyOf(e.uniqueKey),o=await this.resolveOne(r);return this.submit(`TransferToken`,N(this.walletAddress,t,o,a,i),a)}async burnTokens(e){let t=this.checkBatch(`BurnTokens`,e.tokens),n=this.uniqueKeyOf(e.uniqueKey),r=await this.resolveAll(t);return this.submit(`BurnTokens`,M(r,n),n)}async lockTokens(e){let t=e.lockAuthority===void 0?this.walletAddress:n(e.lockAuthority,`lockAuthority`),r=l(e.expires),i=u(e.name),a=this.checkBatch(`LockToken`,e.tokens),o=this.uniqueKeyOf(e.uniqueKey),s=await this.resolveAll(a);return this.submit(`LockToken`,d(t,this.walletAddress,s,o,r,i),o)}async unlockTokens(e){let t=u(e.name),n=this.checkBatch(`UnlockToken`,e.tokens),r=this.uniqueKeyOf(e.uniqueKey),i=await this.resolveAll(n);return this.submit(`UnlockToken`,f(this.walletAddress,i,r,t),r)}async claimNftCollection(e){let t=this.prepareClaim(e),n=await D(this.transport,`GrantNftCollectionAuthorization`,t.dto,t.uniqueKey);return m(n,t.collection)}async createNftCollection(e){let t=this.prepareCreate(e),n=await D(this.transport,`CreateNftCollection`,t.dto,t.uniqueKey);return g(n,t.tokenClass)}async mintNft(e){let t=this.prepareMint(e),n=await D(this.transport,t.method,t.dto,t.uniqueKey);return v(n,t.tokenClass,t.quantity)}async estimateNftFee(e,t){let n=b(t.callerPublicKey),r=this.prepareFeeRequest(e);return await O(this.transport,this.uniqueKeyPrefix,n,r.method,r.dto)}prepareFeeRequest(e){switch(e.write){case`claimNftCollection`:{let{dto:t}=this.prepareClaim(e);return{method:`GrantNftCollectionAuthorization`,dto:t}}case`createNftCollection`:{let{dto:t}=this.prepareCreate(e);return{method:`CreateNftCollection`,dto:t}}case`mintNft`:{let{method:t,dto:n}=this.prepareMint(e);return{method:t,dto:n}}}}prepareClaim(e){let t=x(e.collection,`collection`),r=e.authorizedUser===void 0?this.walletAddress:n(e.authorizedUser,`authorizedUser`),i=this.uniqueKeyOf(e.uniqueKey);return{collection:t,uniqueKey:i,dto:p(t,r,i)}}prepareCreate(e){let t=T(e),n={name:w(e.name,`name`),symbol:C(e.symbol,`symbol`),description:w(e.description,`description`),image:w(e.image,`image`),maxSupply:E(e.maxSupply,`maxSupply`),maxCapacity:e.maxCapacity===void 0?void 0:E(e.maxCapacity,`maxCapacity`),metadataAddress:e.metadataAddress===void 0?void 0:w(e.metadataAddress,`metadataAddress`),contractAddress:e.contractAddress===void 0?void 0:w(e.contractAddress,`contractAddress`),rarity:e.rarity===void 0?void 0:w(e.rarity,`rarity`),authorities:e.authorities===void 0?void 0:y(e.authorities)},r=this.uniqueKeyOf(e.uniqueKey);return{tokenClass:t,uniqueKey:r,dto:h(t,n,r)}}prepareMint(e){let t=T(e),r=S(e.quantity,`quantity`),i=e.owner===void 0?this.walletAddress:n(e.owner,`owner`),a=e.existingAllowance===!0?`MintToken`:`MintTokenWithAllowance`,o=this.uniqueKeyOf(e.uniqueKey);return{method:a,tokenClass:t,quantity:r,uniqueKey:o,dto:_(a,t,i,r,o)}}uniqueKeyOf(e){return e===void 0?o(this.uniqueKeyPrefix):(a(e),e)}checkBatch(e,n){let r=P[e],i=Array.isArray(n)?n.length:0;if(i<1||i>r)throw new t(`INVALID_TOKEN_BATCH`,{method:e,count:i,max:r});return n.map((e,t)=>k(e,`tokens[${t}].`))}async resolveOne(e){return{quantity:e.quantity,key:await A(e.token,this.tokenNameResolver)}}async resolveAll(e){let t=[];for(let n of e)t.push(await this.resolveOne(n));return t}submit(e,t,n){return D(this.transport,e,t,n)}};export{F as GatewayWrites};
|
|
2
2
|
//# sourceMappingURL=gateway_writes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gateway_writes.js","names":["_defineProperty","GatewayWrites","options","signer","GalaSDKError","gatewayBaseUrl","httpRequestor","tokenNameResolver","galaChainUserRef","resolveUniqueKeyPrefix","fetchRequestor","validateTimeoutMs","input","GALA_TOKEN_CLASS_KEY","to","checked","checkQuantity","uniqueKey","token","transferTokenDto","tokens","burnTokensDto","lockAuthority","expires","lockExpires","name","lockName","lockTokenDto","unlockTokenDto","prepared","receipt","submitWrite","claimedCollection","createdTokenClass","mintedInstances","callerPublicKey","nftCallerPublicKey","request","quoteNftFee","collection","nftClassPart","authorizedUser","claimNftCollectionDto","tokenClass","nftTokenClass","fields","nftText","nftString","nftWholeNumber","nftAuthorities","createNftCollectionDto","quantity","nftMintQuantity","owner","method","mintNftDto","given","createUniqueKey","assertUniqueKey","max","GATEWAY_WRITE_BATCH_LIMITS","count","index","resolveToken","resolved","entry","dto"],"sources":["../../../src/writes/gateway_writes.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { fetchRequestor, validateTimeoutMs } from '../utils/transport.js';\nimport { assertUniqueKey, createUniqueKey, resolveUniqueKeyPrefix } from '../utils/unique_key.js';\nimport { galaChainUserRef } from './identity.js';\nimport { lockExpires, lockName, lockTokenDto, unlockTokenDto } from './lock.js';\nimport {\n claimedCollection,\n claimNftCollectionDto,\n createdTokenClass,\n createNftCollectionDto,\n mintedInstances,\n mintNftDto,\n nftAuthorities,\n nftCallerPublicKey,\n nftClassPart,\n nftMintQuantity,\n nftString,\n nftText,\n nftTokenClass,\n nftWholeNumber,\n type ClaimNftCollectionInput,\n type ClaimNftCollectionReceipt,\n type CreateNftCollectionInput,\n type CreateNftCollectionReceipt,\n type MintNftInput,\n type MintNftReceipt,\n type NftWriteMethod,\n} from './nft.js';\nimport { quoteNftFee, type NftFeeQuote } from './nft_fee.js';\nimport { submitWrite, type WriteTransport } from './submit.js';\nimport { checkQuantity, resolveToken, type CheckedQuantity } from './token_ref.js';\nimport {\n burnTokensDto,\n GALA_TOKEN_CLASS_KEY,\n transferTokenDto,\n type ResolvedQuantity,\n} from './transfer.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport {\n GATEWAY_WRITE_BATCH_LIMITS,\n type BurnTokensInput,\n type GatewayWriteMethod,\n type GatewayWriteReceipt,\n type GatewayWritesOptions,\n type LockTokensInput,\n type TokenNameResolver,\n type TokenQuantityInput,\n type TransferGalaInput,\n type TransferTokenInput,\n type UnlockTokensInput,\n} from './types.js';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * What `estimateNftFee` prices: the input of one NFT write, named by the write's method. It takes the\n * same checks as the write.\n */\nexport type NftFeeRequest =\n | ({ write: 'claimNftCollection' } & ClaimNftCollectionInput)\n | ({ write: 'createNftCollection' } & CreateNftCollectionInput)\n | ({ write: 'mintNft' } & MintNftInput);\n\n/**\n * Signed GalaChain token-contract writes through the gateway: transfer GALA, transfer a token,\n * burn, lock and unlock. React Native safe (no Node builtins, no ethers, no `@gala-chain/api`).\n *\n * Every write is checked completely BEFORE it is signed (recipient and owner spellings, the token,\n * the quantity, the `uniqueKey`, the batch), so a refused input costs no signature and no request.\n * The DTO is plain JSON with exactly the chain's fields; the signer signs it as it is (nothing,\n * least of all a signer hint, is added) and the body sent is what the signer returned. Quantities\n * are whole tokens and are signed exactly as written.\n *\n * @example\n * ```ts\n * const writes = new GatewayWrites({\n * gatewayBaseUrl: 'https://gateway-mainnet.galachain.com',\n * signer: new PrivateKeySigner(privateKey),\n * walletAddress: 'eth|70997970C51812dc3A010C7d01b50e0d17dc79C8',\n * });\n * const { transactionId, blockNumber } = await writes.transferGala({ to: 'client|abc', quantity: '1.5' });\n * ```\n */\nexport class GatewayWrites {\n /** The identity every write is made as, in the spelling the gateway receives. */\n public readonly walletAddress: string;\n private readonly transport: WriteTransport;\n private readonly uniqueKeyPrefix: string;\n private readonly tokenNameResolver: TokenNameResolver | undefined;\n\n /**\n * @throws GalaSDKError `INVALID_WRITES_OPTION` (a missing signer or base URL, a requestor that is\n * not a function, a resolver without `resolveTokenClassKey`), `INVALID_WALLET_ADDRESS`,\n * `INVALID_TIMEOUT`, `INVALID_UNIQUE_KEY_PREFIX`.\n */\n constructor(options: GatewayWritesOptions) {\n const { signer, gatewayBaseUrl, httpRequestor, tokenNameResolver } = options;\n if (typeof signer !== 'object' || signer === null || typeof signer.signObject !== 'function') {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'signer' });\n }\n if (typeof gatewayBaseUrl !== 'string') {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'gatewayBaseUrl' });\n }\n if (httpRequestor !== undefined && typeof httpRequestor !== 'function') {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'httpRequestor' });\n }\n if (\n tokenNameResolver !== undefined &&\n (typeof tokenNameResolver !== 'object' ||\n tokenNameResolver === null ||\n typeof tokenNameResolver.resolveTokenClassKey !== 'function')\n ) {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'tokenNameResolver' });\n }\n this.walletAddress = galaChainUserRef(options.walletAddress, 'walletAddress');\n this.uniqueKeyPrefix = resolveUniqueKeyPrefix(options.uniqueKeyPrefix);\n this.tokenNameResolver = tokenNameResolver;\n this.transport = {\n gatewayBaseUrl: gatewayBaseUrl.replace(/\\/+$/u, ''),\n signer,\n requestor: httpRequestor ?? fetchRequestor,\n timeoutMs: validateTimeoutMs(\n options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n 'requestTimeoutMs',\n ),\n wire: options.wire,\n };\n }\n\n /**\n * Transfer GALA (`GALA|Unit|none|none`, instance `\"0\"`) to `to`.\n *\n * @throws GalaSDKError pre-send: `INVALID_WALLET_ADDRESS`, `INVALID_QUANTITY`,\n * `INVALID_UNIQUE_KEY`, `SIGNING_FAILED`; in flight: `GATEWAY_WRITE_OUTCOME_UNKNOWN` (check\n * `error.uniqueKey`; never resend under a fresh key);\n * post-send: `GATEWAY_WRITE_REJECTED`, `GATEWAY_HTTP_ERROR`, `GATEWAY_RESPONSE_INVALID`.\n */\n public transferGala(input: TransferGalaInput): Promise<GatewayWriteReceipt> {\n return this.transferToken({\n to: input.to,\n quantity: input.quantity,\n tokenClassKey: GALA_TOKEN_CLASS_KEY,\n uniqueKey: input.uniqueKey,\n });\n }\n\n /**\n * Transfer one token to `to`.\n *\n * @throws GalaSDKError as {@link transferGala}, plus `INVALID_TOKEN_REFERENCE`,\n * `NO_TOKEN_NAME_RESOLVER`, `TOKEN_NAME_RESOLUTION_FAILED`.\n */\n public async transferToken(input: TransferTokenInput): Promise<GatewayWriteReceipt> {\n const to = galaChainUserRef(input.to, 'to');\n const checked = checkQuantity(input, '');\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const token = await this.resolveOne(checked);\n return this.submit(\n 'TransferToken',\n transferTokenDto(this.walletAddress, to, token, uniqueKey),\n uniqueKey,\n );\n }\n\n /**\n * Burn 1 to 50 tokens of the writer's. IRREVERSIBLE: burned tokens are gone.\n *\n * @throws GalaSDKError as {@link transferToken}, plus `INVALID_TOKEN_BATCH`.\n */\n public async burnTokens(input: BurnTokensInput): Promise<GatewayWriteReceipt> {\n const checked = this.checkBatch('BurnTokens', input.tokens);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const tokens = await this.resolveAll(checked);\n return this.submit('BurnTokens', burnTokensDto(tokens, uniqueKey), uniqueKey);\n }\n\n /**\n * Lock 1 to 100 tokens of the writer's under one hold.\n *\n * @throws GalaSDKError as {@link burnTokens}, plus `INVALID_LOCK_EXPIRES`, `INVALID_LOCK_NAME`.\n */\n public async lockTokens(input: LockTokensInput): Promise<GatewayWriteReceipt> {\n const lockAuthority =\n input.lockAuthority === undefined\n ? this.walletAddress\n : galaChainUserRef(input.lockAuthority, 'lockAuthority');\n const expires = lockExpires(input.expires);\n const name = lockName(input.name);\n const checked = this.checkBatch('LockToken', input.tokens);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const tokens = await this.resolveAll(checked);\n return this.submit(\n 'LockToken',\n lockTokenDto(lockAuthority, this.walletAddress, tokens, uniqueKey, expires, name),\n uniqueKey,\n );\n }\n\n /**\n * Unlock 1 to 100 tokens of the writer's from their hold.\n *\n * @throws GalaSDKError as {@link burnTokens}, plus `INVALID_LOCK_NAME`.\n */\n public async unlockTokens(input: UnlockTokensInput): Promise<GatewayWriteReceipt> {\n const name = lockName(input.name);\n const checked = this.checkBatch('UnlockToken', input.tokens);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const tokens = await this.resolveAll(checked);\n return this.submit(\n 'UnlockToken',\n unlockTokenDto(this.walletAddress, tokens, uniqueKey, name),\n uniqueKey,\n );\n }\n\n /**\n * Claim an NFT collection name: authorize `authorizedUser` (default the writer) to create token\n * classes under it. The chain charges its claim fee (see {@link estimateNftFee}) and refuses a\n * name that is taken, whatever its casing.\n *\n * @throws GalaSDKError pre-send: `INVALID_NFT_INPUT`, `INVALID_WALLET_ADDRESS`,\n * `INVALID_UNIQUE_KEY`, `SIGNING_FAILED`; in flight: `GATEWAY_WRITE_OUTCOME_UNKNOWN` (check\n * `error.uniqueKey`; never resend under a fresh key); post-send: `GATEWAY_WRITE_REJECTED`,\n * `GATEWAY_HTTP_ERROR`, `GATEWAY_RESPONSE_INVALID` (also an answer for another collection).\n */\n public async claimNftCollection(\n input: ClaimNftCollectionInput,\n ): Promise<ClaimNftCollectionReceipt> {\n const prepared = this.prepareClaim(input);\n const receipt = await submitWrite(\n this.transport,\n 'GrantNftCollectionAuthorization',\n prepared.dto,\n prepared.uniqueKey,\n );\n return claimedCollection(receipt, prepared.collection);\n }\n\n /**\n * Create the token class of an NFT collection the writer is authorized for (`CreateNftCollection`).\n *\n * @throws GalaSDKError as {@link claimNftCollection}.\n */\n public async createNftCollection(\n input: CreateNftCollectionInput,\n ): Promise<CreateNftCollectionReceipt> {\n const prepared = this.prepareCreate(input);\n const receipt = await submitWrite(\n this.transport,\n 'CreateNftCollection',\n prepared.dto,\n prepared.uniqueKey,\n );\n return createdTokenClass(receipt, prepared.tokenClass);\n }\n\n /**\n * Mint 1 to 1000 NFTs of a token class the writer is a token authority of, to `owner` (default\n * the writer). The receipt lists the instances the chain created, as the chain answered them.\n *\n * @throws GalaSDKError as {@link claimNftCollection}.\n */\n public async mintNft(input: MintNftInput): Promise<MintNftReceipt> {\n const prepared = this.prepareMint(input);\n const receipt = await submitWrite(\n this.transport,\n prepared.method,\n prepared.dto,\n prepared.uniqueKey,\n );\n return mintedInstances(receipt, prepared.tokenClass, prepared.quantity);\n }\n\n /**\n * What GalaChain's DryRun says an NFT write would cost, for the same input the write takes,\n * checked the same way, and with nothing written to the chain. The fee is the network's own\n * figure for this environment (it differs between stage and mainnet), never a constant.\n *\n * `callerPublicKey` is the writer's secp256k1 public key (hex): the chain's DryRun needs a caller\n * and a signer is not asked for its key. A write the chain would refuse (no authorization, no\n * balance, no mint allowance) is `GATEWAY_READ_REJECTED`, never a fee.\n *\n * @throws GalaSDKError the input checks of the write; `INVALID_NFT_INPUT` for a bad key;\n * `SIGNING_FAILED`; `REQUEST_TIMEOUT` / `TRANSPORT_ERROR` (`write: false`); `GATEWAY_HTTP_ERROR`;\n * `GATEWAY_READ_REJECTED`; `GATEWAY_READ_RESPONSE_INVALID`.\n */\n public async estimateNftFee(\n request: NftFeeRequest,\n options: { readonly callerPublicKey: string },\n ): Promise<NftFeeQuote> {\n const callerPublicKey = nftCallerPublicKey(options.callerPublicKey);\n const prepared = this.prepareFeeRequest(request);\n return await quoteNftFee(\n this.transport,\n this.uniqueKeyPrefix,\n callerPublicKey,\n prepared.method,\n prepared.dto,\n );\n }\n\n private prepareFeeRequest(request: NftFeeRequest): {\n method: NftWriteMethod;\n dto: Record<string, unknown>;\n } {\n switch (request.write) {\n case 'claimNftCollection': {\n const { dto } = this.prepareClaim(request);\n return { method: 'GrantNftCollectionAuthorization', dto };\n }\n case 'createNftCollection': {\n const { dto } = this.prepareCreate(request);\n return { method: 'CreateNftCollection', dto };\n }\n case 'mintNft': {\n const { method, dto } = this.prepareMint(request);\n return { method, dto };\n }\n }\n }\n\n /** Everything a claim needs, every input checked before the key is spent. */\n private prepareClaim(input: ClaimNftCollectionInput): {\n collection: string;\n uniqueKey: string;\n dto: Record<string, unknown>;\n } {\n const collection = nftClassPart(input.collection, 'collection');\n const authorizedUser =\n input.authorizedUser === undefined\n ? this.walletAddress\n : galaChainUserRef(input.authorizedUser, 'authorizedUser');\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n return {\n collection,\n uniqueKey,\n dto: claimNftCollectionDto(collection, authorizedUser, uniqueKey),\n };\n }\n\n private prepareCreate(input: CreateNftCollectionInput): {\n tokenClass: GalaChainTokenClassKey;\n uniqueKey: string;\n dto: Record<string, unknown>;\n } {\n const tokenClass = nftTokenClass(input);\n const fields = {\n name: nftText(input.name, 'name'),\n symbol: nftString(input.symbol, 'symbol'),\n description: nftText(input.description, 'description'),\n image: nftText(input.image, 'image'),\n maxSupply: nftWholeNumber(input.maxSupply, 'maxSupply'),\n maxCapacity:\n input.maxCapacity === undefined\n ? undefined\n : nftWholeNumber(input.maxCapacity, 'maxCapacity'),\n metadataAddress:\n input.metadataAddress === undefined\n ? undefined\n : nftText(input.metadataAddress, 'metadataAddress'),\n contractAddress:\n input.contractAddress === undefined\n ? undefined\n : nftText(input.contractAddress, 'contractAddress'),\n rarity: input.rarity === undefined ? undefined : nftText(input.rarity, 'rarity'),\n authorities: input.authorities === undefined ? undefined : nftAuthorities(input.authorities),\n };\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n return { tokenClass, uniqueKey, dto: createNftCollectionDto(tokenClass, fields, uniqueKey) };\n }\n\n private prepareMint(input: MintNftInput): {\n method: 'MintTokenWithAllowance' | 'MintToken';\n tokenClass: GalaChainTokenClassKey;\n quantity: string;\n uniqueKey: string;\n dto: Record<string, unknown>;\n } {\n const tokenClass = nftTokenClass(input);\n const quantity = nftMintQuantity(input.quantity, 'quantity');\n const owner =\n input.owner === undefined ? this.walletAddress : galaChainUserRef(input.owner, 'owner');\n const method = input.existingAllowance === true ? 'MintToken' : 'MintTokenWithAllowance';\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n return {\n method,\n tokenClass,\n quantity,\n uniqueKey,\n dto: mintNftDto(method, tokenClass, owner, quantity, uniqueKey),\n };\n }\n\n /** The caller's key, checked, or a fresh one. */\n private uniqueKeyOf(given: string | undefined): string {\n if (given === undefined) return createUniqueKey(this.uniqueKeyPrefix);\n assertUniqueKey(given);\n return given;\n }\n\n /** Every token and quantity of a batch write, checked synchronously, in order. */\n private checkBatch(\n method: Exclude<GatewayWriteMethod, 'TransferToken'>,\n tokens: readonly TokenQuantityInput[],\n ): CheckedQuantity[] {\n const max = GATEWAY_WRITE_BATCH_LIMITS[method];\n const count = Array.isArray(tokens) ? tokens.length : 0;\n if (count < 1 || count > max) {\n throw new GalaSDKError('INVALID_TOKEN_BATCH', { method, count, max });\n }\n return tokens.map((input, index) => checkQuantity(input, `tokens[${index}].`));\n }\n\n private async resolveOne(checked: CheckedQuantity): Promise<ResolvedQuantity> {\n return {\n quantity: checked.quantity,\n key: await resolveToken(checked.token, this.tokenNameResolver),\n };\n }\n\n /** Resolves the checked tokens' names in order, one at a time (a resolver may be rate-limited). */\n private async resolveAll(checked: readonly CheckedQuantity[]): Promise<ResolvedQuantity[]> {\n const resolved: ResolvedQuantity[] = [];\n for (const entry of checked) resolved.push(await this.resolveOne(entry));\n return resolved;\n }\n\n private submit(\n method: GatewayWriteMethod,\n dto: Record<string, unknown>,\n uniqueKey: string,\n ): Promise<GatewayWriteReceipt> {\n return submitWrite(this.transport, method, dto, uniqueKey);\n }\n}\n"],"mappings":"A,0jCAmFA,IAAaC,EAAb,KAA2B,CAYzB,YAAY,EAA+B,CAV3BD,EAAA,KAAA,gBAAA,IAAA,EAAA,EACCA,EAAA,KAAA,YAAA,IAAA,EAAA,EACAA,EAAA,KAAA,kBAAA,IAAA,EAAA,EACAA,EAAA,KAAA,oBAAA,IAAA,EAAA,EAQf,GAAM,CAAE,SAAQ,iBAAgB,gBAAe,qBAAsBE,EACrE,GAAI,OAAOC,GAAW,WAAYA,GAAmB,OAAOA,EAAO,YAAe,WAChF,MAAM,IAAIC,EAAa,wBAAyB,CAAE,OAAQ,QAAS,CAAC,EAEtE,GAAI,OAAOC,GAAmB,SAC5B,MAAM,IAAID,EAAa,wBAAyB,CAAE,OAAQ,gBAAiB,CAAC,EAE9E,GAAIE,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AGA,MAAc,WAAW,EAAkE,CACzF,IAAMiD,EAA+B,CAAC,EACtC,IAAK,IAAMC,KAASlD,EAASiD,EAAS,KAAK,MAAM,KAAK,WAAWC,CAAK,CAAC,EACvE,OAAOD,CACT,CAEA,OACE,EACA,EACA,EAC8B,CAC9B,OAAOjC,EAAY,KAAK,UAAWuB,EAAQY,EAAKjD,CAAS,CAC3D,CACF,E"}
|
|
1
|
+
{"version":3,"file":"gateway_writes.js","names":["_defineProperty","GatewayWrites","options","signer","GalaSDKError","gatewayBaseUrl","httpRequestor","tokenNameResolver","galaChainUserRef","resolveUniqueKeyPrefix","fetchRequestor","validateTimeoutMs","input","GALA_TOKEN_CLASS_KEY","to","checked","checkQuantity","dtoExpiresAt","checkDtoExpiresAt","uniqueKey","token","transferTokenDto","tokens","burnTokensDto","lockAuthority","expires","lockExpires","name","lockName","lockTokenDto","unlockTokenDto","prepared","receipt","submitWrite","claimedCollection","createdTokenClass","mintedInstances","callerPublicKey","nftCallerPublicKey","request","quoteNftFee","collection","nftClassPart","authorizedUser","claimNftCollectionDto","tokenClass","nftTokenClass","fields","nftText","nftString","nftWholeNumber","nftAuthorities","createNftCollectionDto","quantity","nftMintQuantity","owner","method","mintNftDto","given","createUniqueKey","assertUniqueKey","max","GATEWAY_WRITE_BATCH_LIMITS","count","index","resolveToken","resolved","entry","dto"],"sources":["../../../src/writes/gateway_writes.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { fetchRequestor, validateTimeoutMs } from '../utils/transport.js';\nimport { assertUniqueKey, createUniqueKey, resolveUniqueKeyPrefix } from '../utils/unique_key.js';\nimport { checkDtoExpiresAt } from './dto_expiry.js';\nimport { galaChainUserRef } from './identity.js';\nimport { lockExpires, lockName, lockTokenDto, unlockTokenDto } from './lock.js';\nimport {\n claimedCollection,\n claimNftCollectionDto,\n createdTokenClass,\n createNftCollectionDto,\n mintedInstances,\n mintNftDto,\n nftAuthorities,\n nftCallerPublicKey,\n nftClassPart,\n nftMintQuantity,\n nftString,\n nftText,\n nftTokenClass,\n nftWholeNumber,\n type ClaimNftCollectionInput,\n type ClaimNftCollectionReceipt,\n type CreateNftCollectionInput,\n type CreateNftCollectionReceipt,\n type MintNftInput,\n type MintNftReceipt,\n type NftWriteMethod,\n} from './nft.js';\nimport { quoteNftFee, type NftFeeQuote } from './nft_fee.js';\nimport { submitWrite, type WriteTransport } from './submit.js';\nimport { checkQuantity, resolveToken, type CheckedQuantity } from './token_ref.js';\nimport {\n burnTokensDto,\n GALA_TOKEN_CLASS_KEY,\n transferTokenDto,\n type ResolvedQuantity,\n} from './transfer.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport {\n GATEWAY_WRITE_BATCH_LIMITS,\n type BurnTokensInput,\n type GatewayWriteMethod,\n type GatewayWriteReceipt,\n type GatewayWritesOptions,\n type LockTokensInput,\n type TokenNameResolver,\n type TokenQuantityInput,\n type TransferGalaInput,\n type TransferTokenInput,\n type UnlockTokensInput,\n} from './types.js';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * What `estimateNftFee` prices: the input of one NFT write, named by the write's method. It takes the\n * same checks as the write.\n */\nexport type NftFeeRequest =\n | ({ write: 'claimNftCollection' } & ClaimNftCollectionInput)\n | ({ write: 'createNftCollection' } & CreateNftCollectionInput)\n | ({ write: 'mintNft' } & MintNftInput);\n\n/**\n * Signed GalaChain token-contract writes through the gateway: transfer GALA, transfer a token,\n * burn, lock and unlock. React Native safe (no Node builtins, no ethers, no `@gala-chain/api`).\n *\n * Every write is checked completely BEFORE it is signed (recipient and owner spellings, the token,\n * the quantity, the `uniqueKey`, the batch), so a refused input costs no signature and no request.\n * The DTO is plain JSON with exactly the chain's fields; the signer signs it as it is (nothing,\n * least of all a signer hint, is added) and the body sent is what the signer returned. Quantities\n * are whole tokens, signed in the chain's canonical spelling (`writeQuantity`: `\"1.50\"` as `\"1.5\"`).\n *\n * @example\n * ```ts\n * const writes = new GatewayWrites({\n * gatewayBaseUrl: 'https://gateway-mainnet.galachain.com',\n * signer: new PrivateKeySigner(privateKey),\n * walletAddress: 'eth|70997970C51812dc3A010C7d01b50e0d17dc79C8',\n * });\n * const { transactionId, blockNumber } = await writes.transferGala({ to: 'client|abc', quantity: '1.5' });\n * ```\n */\nexport class GatewayWrites {\n /** The identity every write is made as, in the spelling the gateway receives. */\n public readonly walletAddress: string;\n private readonly transport: WriteTransport;\n private readonly uniqueKeyPrefix: string;\n private readonly tokenNameResolver: TokenNameResolver | undefined;\n\n /**\n * @throws GalaSDKError `INVALID_WRITES_OPTION` (a missing signer or base URL, a requestor that is\n * not a function, a resolver without `resolveTokenClassKey`), `INVALID_WALLET_ADDRESS`,\n * `INVALID_TIMEOUT`, `INVALID_UNIQUE_KEY_PREFIX`.\n */\n constructor(options: GatewayWritesOptions) {\n const { signer, gatewayBaseUrl, httpRequestor, tokenNameResolver } = options;\n if (typeof signer !== 'object' || signer === null || typeof signer.signObject !== 'function') {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'signer' });\n }\n if (typeof gatewayBaseUrl !== 'string') {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'gatewayBaseUrl' });\n }\n if (httpRequestor !== undefined && typeof httpRequestor !== 'function') {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'httpRequestor' });\n }\n if (\n tokenNameResolver !== undefined &&\n (typeof tokenNameResolver !== 'object' ||\n tokenNameResolver === null ||\n typeof tokenNameResolver.resolveTokenClassKey !== 'function')\n ) {\n throw new GalaSDKError('INVALID_WRITES_OPTION', { option: 'tokenNameResolver' });\n }\n this.walletAddress = galaChainUserRef(options.walletAddress, 'walletAddress');\n this.uniqueKeyPrefix = resolveUniqueKeyPrefix(options.uniqueKeyPrefix);\n this.tokenNameResolver = tokenNameResolver;\n this.transport = {\n gatewayBaseUrl: gatewayBaseUrl.replace(/\\/+$/u, ''),\n signer,\n requestor: httpRequestor ?? fetchRequestor,\n timeoutMs: validateTimeoutMs(\n options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n 'requestTimeoutMs',\n ),\n wire: options.wire,\n };\n }\n\n /**\n * Transfer GALA (`GALA|Unit|none|none`, instance `\"0\"`) to `to`.\n *\n * `input.dtoExpiresAt` (optional, epoch ms) is signed into the DTO when given; see\n * `DtoExpiresAtInput.dtoExpiresAt`.\n *\n * @throws GalaSDKError pre-send: `INVALID_WALLET_ADDRESS`, `INVALID_QUANTITY`,\n * `INVALID_DTO_EXPIRES_AT`, `INVALID_UNIQUE_KEY`, `SIGNING_FAILED`; in flight:\n * `GATEWAY_WRITE_OUTCOME_UNKNOWN` (check `error.uniqueKey`; never resend under a fresh key);\n * post-send: `GATEWAY_WRITE_REJECTED`, `GATEWAY_HTTP_ERROR`, `GATEWAY_RESPONSE_INVALID`.\n */\n public transferGala(input: TransferGalaInput): Promise<GatewayWriteReceipt> {\n return this.transferToken({\n to: input.to,\n quantity: input.quantity,\n tokenClassKey: GALA_TOKEN_CLASS_KEY,\n uniqueKey: input.uniqueKey,\n dtoExpiresAt: input.dtoExpiresAt,\n });\n }\n\n /**\n * Transfer one token to `to`.\n *\n * @throws GalaSDKError as {@link transferGala}, plus `INVALID_TOKEN_REFERENCE`,\n * `NO_TOKEN_NAME_RESOLVER`, `TOKEN_NAME_RESOLUTION_FAILED`.\n */\n public async transferToken(input: TransferTokenInput): Promise<GatewayWriteReceipt> {\n const to = galaChainUserRef(input.to, 'to');\n const checked = checkQuantity(input, '');\n const dtoExpiresAt =\n input.dtoExpiresAt === undefined ? undefined : checkDtoExpiresAt(input.dtoExpiresAt);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const token = await this.resolveOne(checked);\n return this.submit(\n 'TransferToken',\n transferTokenDto(this.walletAddress, to, token, uniqueKey, dtoExpiresAt),\n uniqueKey,\n );\n }\n\n /**\n * Burn 1 to 50 tokens of the writer's. IRREVERSIBLE: burned tokens are gone.\n *\n * @throws GalaSDKError as {@link transferToken}, plus `INVALID_TOKEN_BATCH`.\n */\n public async burnTokens(input: BurnTokensInput): Promise<GatewayWriteReceipt> {\n const checked = this.checkBatch('BurnTokens', input.tokens);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const tokens = await this.resolveAll(checked);\n return this.submit('BurnTokens', burnTokensDto(tokens, uniqueKey), uniqueKey);\n }\n\n /**\n * Lock 1 to 100 tokens of the writer's under one hold.\n *\n * @throws GalaSDKError as {@link burnTokens}, plus `INVALID_LOCK_EXPIRES`, `INVALID_LOCK_NAME`.\n */\n public async lockTokens(input: LockTokensInput): Promise<GatewayWriteReceipt> {\n const lockAuthority =\n input.lockAuthority === undefined\n ? this.walletAddress\n : galaChainUserRef(input.lockAuthority, 'lockAuthority');\n const expires = lockExpires(input.expires);\n const name = lockName(input.name);\n const checked = this.checkBatch('LockToken', input.tokens);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const tokens = await this.resolveAll(checked);\n return this.submit(\n 'LockToken',\n lockTokenDto(lockAuthority, this.walletAddress, tokens, uniqueKey, expires, name),\n uniqueKey,\n );\n }\n\n /**\n * Unlock 1 to 100 tokens of the writer's from their hold.\n *\n * @throws GalaSDKError as {@link burnTokens}, plus `INVALID_LOCK_NAME`.\n */\n public async unlockTokens(input: UnlockTokensInput): Promise<GatewayWriteReceipt> {\n const name = lockName(input.name);\n const checked = this.checkBatch('UnlockToken', input.tokens);\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n const tokens = await this.resolveAll(checked);\n return this.submit(\n 'UnlockToken',\n unlockTokenDto(this.walletAddress, tokens, uniqueKey, name),\n uniqueKey,\n );\n }\n\n /**\n * Claim an NFT collection name: authorize `authorizedUser` (default the writer) to create token\n * classes under it. The chain charges its claim fee (see {@link estimateNftFee}) and refuses a\n * name that is taken, whatever its casing.\n *\n * @throws GalaSDKError pre-send: `INVALID_NFT_INPUT`, `INVALID_WALLET_ADDRESS`,\n * `INVALID_UNIQUE_KEY`, `SIGNING_FAILED`; in flight: `GATEWAY_WRITE_OUTCOME_UNKNOWN` (check\n * `error.uniqueKey`; never resend under a fresh key); post-send: `GATEWAY_WRITE_REJECTED`,\n * `GATEWAY_HTTP_ERROR`, `GATEWAY_RESPONSE_INVALID` (also an answer for another collection).\n */\n public async claimNftCollection(\n input: ClaimNftCollectionInput,\n ): Promise<ClaimNftCollectionReceipt> {\n const prepared = this.prepareClaim(input);\n const receipt = await submitWrite(\n this.transport,\n 'GrantNftCollectionAuthorization',\n prepared.dto,\n prepared.uniqueKey,\n );\n return claimedCollection(receipt, prepared.collection);\n }\n\n /**\n * Create the token class of an NFT collection the writer is authorized for (`CreateNftCollection`).\n *\n * @throws GalaSDKError as {@link claimNftCollection}.\n */\n public async createNftCollection(\n input: CreateNftCollectionInput,\n ): Promise<CreateNftCollectionReceipt> {\n const prepared = this.prepareCreate(input);\n const receipt = await submitWrite(\n this.transport,\n 'CreateNftCollection',\n prepared.dto,\n prepared.uniqueKey,\n );\n return createdTokenClass(receipt, prepared.tokenClass);\n }\n\n /**\n * Mint 1 to 1000 NFTs of a token class the writer is a token authority of, to `owner` (default\n * the writer). The receipt lists the instances the chain created, as the chain answered them.\n *\n * @throws GalaSDKError as {@link claimNftCollection}.\n */\n public async mintNft(input: MintNftInput): Promise<MintNftReceipt> {\n const prepared = this.prepareMint(input);\n const receipt = await submitWrite(\n this.transport,\n prepared.method,\n prepared.dto,\n prepared.uniqueKey,\n );\n return mintedInstances(receipt, prepared.tokenClass, prepared.quantity);\n }\n\n /**\n * What GalaChain's DryRun says an NFT write would cost, for the same input the write takes,\n * checked the same way, and with nothing written to the chain. The fee is the network's own\n * figure for this environment (it differs between stage and mainnet), never a constant.\n *\n * `callerPublicKey` is the writer's secp256k1 public key (hex): the chain's DryRun needs a caller\n * and a signer is not asked for its key. A write the chain would refuse (no authorization, no\n * balance, no mint allowance) is `GATEWAY_READ_REJECTED`, never a fee.\n *\n * @throws GalaSDKError the input checks of the write; `INVALID_NFT_INPUT` for a bad key;\n * `SIGNING_FAILED`; `REQUEST_TIMEOUT` / `TRANSPORT_ERROR` (`write: false`); `GATEWAY_HTTP_ERROR`;\n * `GATEWAY_READ_REJECTED`; `GATEWAY_READ_RESPONSE_INVALID`.\n */\n public async estimateNftFee(\n request: NftFeeRequest,\n options: { readonly callerPublicKey: string },\n ): Promise<NftFeeQuote> {\n const callerPublicKey = nftCallerPublicKey(options.callerPublicKey);\n const prepared = this.prepareFeeRequest(request);\n return await quoteNftFee(\n this.transport,\n this.uniqueKeyPrefix,\n callerPublicKey,\n prepared.method,\n prepared.dto,\n );\n }\n\n private prepareFeeRequest(request: NftFeeRequest): {\n method: NftWriteMethod;\n dto: Record<string, unknown>;\n } {\n switch (request.write) {\n case 'claimNftCollection': {\n const { dto } = this.prepareClaim(request);\n return { method: 'GrantNftCollectionAuthorization', dto };\n }\n case 'createNftCollection': {\n const { dto } = this.prepareCreate(request);\n return { method: 'CreateNftCollection', dto };\n }\n case 'mintNft': {\n const { method, dto } = this.prepareMint(request);\n return { method, dto };\n }\n }\n }\n\n /** Everything a claim needs, every input checked before the key is spent. */\n private prepareClaim(input: ClaimNftCollectionInput): {\n collection: string;\n uniqueKey: string;\n dto: Record<string, unknown>;\n } {\n const collection = nftClassPart(input.collection, 'collection');\n const authorizedUser =\n input.authorizedUser === undefined\n ? this.walletAddress\n : galaChainUserRef(input.authorizedUser, 'authorizedUser');\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n return {\n collection,\n uniqueKey,\n dto: claimNftCollectionDto(collection, authorizedUser, uniqueKey),\n };\n }\n\n private prepareCreate(input: CreateNftCollectionInput): {\n tokenClass: GalaChainTokenClassKey;\n uniqueKey: string;\n dto: Record<string, unknown>;\n } {\n const tokenClass = nftTokenClass(input);\n const fields = {\n name: nftText(input.name, 'name'),\n symbol: nftString(input.symbol, 'symbol'),\n description: nftText(input.description, 'description'),\n image: nftText(input.image, 'image'),\n maxSupply: nftWholeNumber(input.maxSupply, 'maxSupply'),\n maxCapacity:\n input.maxCapacity === undefined\n ? undefined\n : nftWholeNumber(input.maxCapacity, 'maxCapacity'),\n metadataAddress:\n input.metadataAddress === undefined\n ? undefined\n : nftText(input.metadataAddress, 'metadataAddress'),\n contractAddress:\n input.contractAddress === undefined\n ? undefined\n : nftText(input.contractAddress, 'contractAddress'),\n rarity: input.rarity === undefined ? undefined : nftText(input.rarity, 'rarity'),\n authorities: input.authorities === undefined ? undefined : nftAuthorities(input.authorities),\n };\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n return { tokenClass, uniqueKey, dto: createNftCollectionDto(tokenClass, fields, uniqueKey) };\n }\n\n private prepareMint(input: MintNftInput): {\n method: 'MintTokenWithAllowance' | 'MintToken';\n tokenClass: GalaChainTokenClassKey;\n quantity: string;\n uniqueKey: string;\n dto: Record<string, unknown>;\n } {\n const tokenClass = nftTokenClass(input);\n const quantity = nftMintQuantity(input.quantity, 'quantity');\n const owner =\n input.owner === undefined ? this.walletAddress : galaChainUserRef(input.owner, 'owner');\n const method = input.existingAllowance === true ? 'MintToken' : 'MintTokenWithAllowance';\n const uniqueKey = this.uniqueKeyOf(input.uniqueKey);\n return {\n method,\n tokenClass,\n quantity,\n uniqueKey,\n dto: mintNftDto(method, tokenClass, owner, quantity, uniqueKey),\n };\n }\n\n /** The caller's key, checked, or a fresh one. */\n private uniqueKeyOf(given: string | undefined): string {\n if (given === undefined) return createUniqueKey(this.uniqueKeyPrefix);\n assertUniqueKey(given);\n return given;\n }\n\n /** Every token and quantity of a batch write, checked synchronously, in order. */\n private checkBatch(\n method: Exclude<GatewayWriteMethod, 'TransferToken'>,\n tokens: readonly TokenQuantityInput[],\n ): CheckedQuantity[] {\n const max = GATEWAY_WRITE_BATCH_LIMITS[method];\n const count = Array.isArray(tokens) ? tokens.length : 0;\n if (count < 1 || count > max) {\n throw new GalaSDKError('INVALID_TOKEN_BATCH', { method, count, max });\n }\n return tokens.map((input, index) => checkQuantity(input, `tokens[${index}].`));\n }\n\n private async resolveOne(checked: CheckedQuantity): Promise<ResolvedQuantity> {\n return {\n quantity: checked.quantity,\n key: await resolveToken(checked.token, this.tokenNameResolver),\n };\n }\n\n /** Resolves the checked tokens' names in order, one at a time (a resolver may be rate-limited). */\n private async resolveAll(checked: readonly CheckedQuantity[]): Promise<ResolvedQuantity[]> {\n const resolved: ResolvedQuantity[] = [];\n for (const entry of checked) resolved.push(await this.resolveOne(entry));\n return resolved;\n }\n\n private submit(\n method: GatewayWriteMethod,\n dto: Record<string, unknown>,\n uniqueKey: string,\n ): Promise<GatewayWriteReceipt> {\n return submitWrite(this.transport, method, dto, uniqueKey);\n }\n}\n"],"mappings":"A,8mCAoFA,IAAaC,EAAb,KAA2B,CAYzB,YAAY,EAA+B,CAV3BD,EAAA,KAAA,gBAAA,IAAA,EAAA,EACCA,EAAA,KAAA,YAAA,IAAA,EAAA,EACAA,EAAA,KAAA,kBAAA,IAAA,EAAA,EACAA,EAAA,KAAA,oBAAA,IAAA,EAAA,EAQf,GAAM,CAAE,SAAQ,iBAAgB,gBAAe,qBAAsBE,EACrE,GAAI,OAAOC,GAAW,WAAYA,GAAmB,OAAOA,EAAO,YAAe,WAChF,MAAM,IAAIC,EAAa,wBAAyB,CAAE,OAAQ,QAAS,CAAC,EAEtE,GAAI,OAAOC,GAAmB,SAC5B,MAAM,IAAID,EAAa,wBAAyB,CAAE,OAAQ,gBAAiB,CAAC,EAE9E,GAAIE,IAAkB,IAAA,IAAa,OAAOA,GAAkB,WAC1D,MAAM,IAAIF,EAAa,wBAAyB,CAAE,OAAQ,eAAgB,CAAC,EAE7E,GACEG,IAAsB,IAAA,KACrB,OAAOA,GAAsB,WAC5BA,GACA,OAAOA,EAAkB,sBAAyB,YAEpD,MAAM,IAAIH,EAAa,wBAAyB,CAAE,OAAQ,mBAAoB,CAAC,EAEjF,KAAK,cAAgBI,EAAiBN,EAAQ,cAAe,eAAe,EAC5E,KAAK,gBAAkBO,EAAuBP,EAAQ,eAAe,EACrE,KAAK,kBAAoBK,EACzB,KAAK,UAAY,C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@
|
|
|
1
|
-
import{GalaSDKError as e}from"../classes/gala_sdk_error.js";import{checksumEthereumAddress as t}from"../utils/eth_address.js";const n=/^(?:eth\||0x)?([0-9a-fA-F]{40})$/u,r=/^client\|[A-Za-z0-9_-]+$/u,i=/^eth\|0[xX](.*)$/su;function a(e){let t=e.indexOf(`|`);return t<0?e:`${e.slice(0,t).toLowerCase()}${e.slice(t)}`}function o(n,r){if(typeof n!=`string`)return;let o=i.exec(a(n))?.[1];if(o===void 0)return;let s=/^[0-9a-fA-F]{40}$/u.test(o)?t(o):void 0;throw new e(`INVALID_ETH_USER_REF_PREFIX`,{field:r,value:n,expected:s===void 0?`eth|<40 hex digits>`:`eth|${s.slice(2)}`})}function s(i,s){if(o(i,s),typeof i==`string`){let e=a(i);if(r.test(e))return e;let o=n.exec(e)?.[1],s=o===void 0?void 0:t(o);if(s!==void 0)return`eth|${s.slice(2)}`}throw new e(`INVALID_WALLET_ADDRESS`,{field:s,value
|
|
1
|
+
import{GalaSDKError as e}from"../classes/gala_sdk_error.js";import{checksumEthereumAddress as t}from"../utils/eth_address.js";const n=/^(?:eth\||0x)?([0-9a-fA-F]{40})$/u,r=/^client\|[A-Za-z0-9_-]+$/u,i=/^eth\|0[xX](.*)$/su;function a(e){let t=e.indexOf(`|`);return t<0?e:`${e.slice(0,t).toLowerCase()}${e.slice(t)}`}function o(n,r){if(typeof n!=`string`)return;let o=i.exec(a(n))?.[1];if(o===void 0)return;let s=/^[0-9a-fA-F]{40}$/u.test(o)?t(o):void 0;throw new e(`INVALID_ETH_USER_REF_PREFIX`,{field:r,value:n,expected:s===void 0?`eth|<40 hex digits>`:`eth|${s.slice(2)}`})}function s(i,s){if(o(i,s),typeof i==`string`){let e=a(i);if(r.test(e))return e;let o=n.exec(e)?.[1],s=o===void 0?void 0:t(o);if(s!==void 0)return`eth|${s.slice(2)}`}throw new e(`INVALID_WALLET_ADDRESS`,{field:s,value:`[redacted]`})}export{o as assertNoEthZeroXPrefix,s as galaChainUserRef};
|
|
2
2
|
//# sourceMappingURL=identity.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identity.js","names":["ACCOUNT","CLIENT_ALIAS","ETH_WITH_0X","lowerScheme","pipe","value","assertNoEthZeroXPrefix","rest","checksummed","checksumEthereumAddress","GalaSDKError","galaChainUserRef","field","spelled","digits","account"],"sources":["../../../src/writes/identity.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { checksumEthereumAddress } from '../utils/eth_address.js';\n\n/** `eth|`, `0x` or nothing, then the 40 hex digits of an Ethereum account. */\nconst ACCOUNT = /^(?:eth\\||0x)?([0-9a-fA-F]{40})$/u;\nconst CLIENT_ALIAS = /^client\\|[A-Za-z0-9_-]+$/u;\n/** `eth|0x...`: not a user reference. An `eth|` reference is followed by the digits alone. */\nconst ETH_WITH_0X = /^eth\\|0[xX](.*)$/su;\n\n/**\n * `value` with the part before its first `|` lower-cased and everything after it exactly as written (a value with no\n * `|` is returned as is): `Client|X` is the account `client|X`, `ETH|<hex>` is `eth|<hex>`. The scheme is\n * case-insensitive, an alias id is not (launchpad-sdk's `userRef` follows the same rule).\n */\nfunction lowerScheme(value: string): string {\n const pipe = value.indexOf('|');\n return pipe < 0 ? value : `${value.slice(0, pipe).toLowerCase()}${value.slice(pipe)}`;\n}\n\n/**\n * Refuses `eth|0x...` (any digits, any casing of the `0x`) with `INVALID_ETH_USER_REF_PREFIX`,\n * naming the correct spelling. `eth|0x...` is not an address form: GalaChain's `eth|` reference is\n * followed by the 40 hex digits only. A bare `0x<40 hex>` is a different, normal thing (an\n * Ethereum address) and is not touched. Every place core reads an account refuses it through this\n * one function, before anything is signed or sent.\n *\n * @throws GalaSDKError `INVALID_ETH_USER_REF_PREFIX` (`params.field` = `field`).\n */\nexport function assertNoEthZeroXPrefix(value: unknown, field: string): void {\n if (typeof value !== 'string') return;\n const rest = ETH_WITH_0X.exec(lowerScheme(value))?.[1];\n if (rest === undefined) return;\n const checksummed = /^[0-9a-fA-F]{40}$/u.test(rest) ? checksumEthereumAddress(rest) : undefined;\n throw new GalaSDKError('INVALID_ETH_USER_REF_PREFIX', {\n field,\n value,\n expected: checksummed === undefined ? 'eth|<40 hex digits>' : `eth|${checksummed.slice(2)}`,\n });\n}\n\n/**\n * The GalaChain user reference a read or write names (owner, sender, recipient, lock authority),\n * in the one spelling the gateway receives:\n *\n * - an Ethereum account, as `eth|<40 hex>`, `0x<40 hex>` or bare `<40 hex>`: sent as `eth|` plus\n * its EIP-55 checksummed digits (no `0x`). The gateway refuses every other casing of an `eth|`\n * reference (all lower case, all upper case) with HTTP 400 `DTO_VALIDATION_FAILED`\n * (`IsUserRefConstraint`; recorded in `tests/fixtures/gateway-reads-recorded.json`). A\n * mixed-case spelling whose casing is not the EIP-55 checksum is a typo (what EIP-55 exists to\n * catch) and is refused.\n * - `eth|0x<hex>` is NOT an address form: an `eth|` reference is followed by the digits alone.\n * It is refused before anything is signed or sent (see {@link assertNoEthZeroXPrefix}). A bare\n * `0x<40 hex>` is an ordinary Ethereum address and is converted to `eth|<EIP-55 digits>`.\n * - `client|<id>` (`A-Za-z0-9_-`): a GalaChain alias, kept exactly as written after the scheme.\n * - The scheme (before the first `|`) is accepted in any case and sent lower case (`Client|X` -> `client|X`,\n * `ETH|<hex>` -> `eth|<hex>`); everything after the `|` keeps its case.\n *\n * Anything else is refused before anything is signed or sent (fail closed): an unknown spelling\n * could name an account nobody holds.\n *\n * @throws GalaSDKError `INVALID_ETH_USER_REF_PREFIX` for `eth|0x...`, otherwise\n * `INVALID_WALLET_ADDRESS` (`params.field` = `field`).\n */\nexport function galaChainUserRef(value: unknown, field: string): string {\n assertNoEthZeroXPrefix(value, field);\n if (typeof value === 'string') {\n const spelled = lowerScheme(value);\n if (CLIENT_ALIAS.test(spelled)) return spelled;\n const digits = ACCOUNT.exec(spelled)?.[1];\n const account = digits === undefined ? undefined : checksumEthereumAddress(digits);\n if (account !== undefined) return `eth|${account.slice(2)}`;\n }\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field, value:
|
|
1
|
+
{"version":3,"file":"identity.js","names":["ACCOUNT","CLIENT_ALIAS","ETH_WITH_0X","lowerScheme","pipe","value","assertNoEthZeroXPrefix","rest","checksummed","checksumEthereumAddress","GalaSDKError","galaChainUserRef","field","spelled","digits","account"],"sources":["../../../src/writes/identity.ts"],"sourcesContent":["import { GalaSDKError } from '../classes/gala_sdk_error.js';\nimport { checksumEthereumAddress } from '../utils/eth_address.js';\n\n/** `eth|`, `0x` or nothing, then the 40 hex digits of an Ethereum account. */\nconst ACCOUNT = /^(?:eth\\||0x)?([0-9a-fA-F]{40})$/u;\nconst CLIENT_ALIAS = /^client\\|[A-Za-z0-9_-]+$/u;\n/** `eth|0x...`: not a user reference. An `eth|` reference is followed by the digits alone. */\nconst ETH_WITH_0X = /^eth\\|0[xX](.*)$/su;\n\n/**\n * `value` with the part before its first `|` lower-cased and everything after it exactly as written (a value with no\n * `|` is returned as is): `Client|X` is the account `client|X`, `ETH|<hex>` is `eth|<hex>`. The scheme is\n * case-insensitive, an alias id is not (launchpad-sdk's `userRef` follows the same rule).\n */\nfunction lowerScheme(value: string): string {\n const pipe = value.indexOf('|');\n return pipe < 0 ? value : `${value.slice(0, pipe).toLowerCase()}${value.slice(pipe)}`;\n}\n\n/**\n * Refuses `eth|0x...` (any digits, any casing of the `0x`) with `INVALID_ETH_USER_REF_PREFIX`,\n * naming the correct spelling. `eth|0x...` is not an address form: GalaChain's `eth|` reference is\n * followed by the 40 hex digits only. A bare `0x<40 hex>` is a different, normal thing (an\n * Ethereum address) and is not touched. Every place core reads an account refuses it through this\n * one function, before anything is signed or sent.\n *\n * @throws GalaSDKError `INVALID_ETH_USER_REF_PREFIX` (`params.field` = `field`).\n */\nexport function assertNoEthZeroXPrefix(value: unknown, field: string): void {\n if (typeof value !== 'string') return;\n const rest = ETH_WITH_0X.exec(lowerScheme(value))?.[1];\n if (rest === undefined) return;\n const checksummed = /^[0-9a-fA-F]{40}$/u.test(rest) ? checksumEthereumAddress(rest) : undefined;\n throw new GalaSDKError('INVALID_ETH_USER_REF_PREFIX', {\n field,\n value,\n expected: checksummed === undefined ? 'eth|<40 hex digits>' : `eth|${checksummed.slice(2)}`,\n });\n}\n\n/**\n * The GalaChain user reference a read or write names (owner, sender, recipient, lock authority),\n * in the one spelling the gateway receives:\n *\n * - an Ethereum account, as `eth|<40 hex>`, `0x<40 hex>` or bare `<40 hex>`: sent as `eth|` plus\n * its EIP-55 checksummed digits (no `0x`). The gateway refuses every other casing of an `eth|`\n * reference (all lower case, all upper case) with HTTP 400 `DTO_VALIDATION_FAILED`\n * (`IsUserRefConstraint`; recorded in `tests/fixtures/gateway-reads-recorded.json`). A\n * mixed-case spelling whose casing is not the EIP-55 checksum is a typo (what EIP-55 exists to\n * catch) and is refused.\n * - `eth|0x<hex>` is NOT an address form: an `eth|` reference is followed by the digits alone.\n * It is refused before anything is signed or sent (see {@link assertNoEthZeroXPrefix}). A bare\n * `0x<40 hex>` is an ordinary Ethereum address and is converted to `eth|<EIP-55 digits>`.\n * - `client|<id>` (`A-Za-z0-9_-`): a GalaChain alias, kept exactly as written after the scheme.\n * - The scheme (before the first `|`) is accepted in any case and sent lower case (`Client|X` -> `client|X`,\n * `ETH|<hex>` -> `eth|<hex>`); everything after the `|` keeps its case.\n *\n * Anything else is refused before anything is signed or sent (fail closed): an unknown spelling\n * could name an account nobody holds.\n *\n * @throws GalaSDKError `INVALID_ETH_USER_REF_PREFIX` for `eth|0x...`, otherwise\n * `INVALID_WALLET_ADDRESS` (`params.field` = `field`).\n */\nexport function galaChainUserRef(value: unknown, field: string): string {\n assertNoEthZeroXPrefix(value, field);\n if (typeof value === 'string') {\n const spelled = lowerScheme(value);\n if (CLIENT_ALIAS.test(spelled)) return spelled;\n const digits = ACCOUNT.exec(spelled)?.[1];\n const account = digits === undefined ? undefined : checksumEthereumAddress(digits);\n if (account !== undefined) return `eth|${account.slice(2)}`;\n }\n // The supplied value is never echoed (it may be anything a caller pasted into an address field).\n throw new GalaSDKError('INVALID_WALLET_ADDRESS', { field, value: '[redacted]' });\n}\n"],"mappings":"A,8HAIA,MAAMA,EAAU,oCACVC,EAAe,4BAEfC,EAAc,qBAOpB,SAASC,EAAY,EAAuB,CAC1C,IAAMC,EAAOC,EAAM,QAAQ,GAAG,EAC9B,OAAOD,EAAO,EAAIC,EAAQ,GAAGA,EAAM,MAAM,EAAGD,CAAI,CAAC,CAAC,YAAY,IAAIC,EAAM,MAAMD,CAAI,GACpF,CAWA,SAAgBE,EAAuB,EAAgB,EAAqB,CAC1E,GAAI,OAAOD,GAAU,SAAU,OAC/B,IAAME,EAAOL,EAAY,KAAKC,EAAYE,CAAK,CAAC,CAAC,GAAG,GACpD,GAAIE,IAAS,IAAA,GAAW,OACxB,IAAMC,EAAc,qBAAqB,KAAKD,CAAI,EAAIE,EAAwBF,CAAI,EAAI,IAAA,GACtF,MAAM,IAAIG,EAAa,8BAA+B,CACpD,QACA,QACA,SAAUF,IAAgB,IAAA,GAAY,sBAAwB,OAAOA,EAAY,MAAM,CAAC,GAC1F,CAAC,CACH,CAyBA,SAAgBG,EAAiB,EAAgB,EAAuB,CAEtE,GADAL,EAAuBD,EAAOO,CAAK,EAC/B,OAAOP,GAAU,SAAU,CAC7B,IAAMQ,EAAUV,EAAYE,CAAK,EACjC,GAAIJ,EAAa,KAAKY,CAAO,EAAG,OAAOA,EACvC,IAAMC,EAASd,EAAQ,KAAKa,CAAO,CAAC,GAAG,GACjCE,EAAUD,IAAW,IAAA,GAAY,IAAA,GAAYL,EAAwBK,CAAM,EACjF,GAAIC,IAAY,IAAA,GAAW,MAAO,OAAOA,EAAQ,MAAM,CAAC,GAC1D,CAEA,MAAM,IAAIL,EAAa,yBAA0B,CAAE,QAAO,MAAO,YAAa,CAAC,CACjF,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{GalaSDKError as e,isGalaError as t}from"../classes/gala_sdk_error.js";import{splitClassKey as n,tryParseTokenClassKey as r}from"../utils/class_key.js";import i from"bignumber.js";const a=/^[0-9]+(?:\.[0-9]+)?$/u,o=/^[0-9]
|
|
1
|
+
import{GalaSDKError as e,isGalaError as t}from"../classes/gala_sdk_error.js";import{splitClassKey as n,tryParseTokenClassKey as r}from"../utils/class_key.js";import i from"bignumber.js";const a=/^[0-9]+(?:\.[0-9]+)?$/u,o=/^(?:0|[1-9][0-9]*)$/u;function s(t,n){if(typeof t==`string`&&a.test(t)){let e=new i(t);if(e.isGreaterThan(0))return e.toFixed()}throw new e(`INVALID_QUANTITY`,{field:n,value:`[redacted]`})}function c(e){return typeof e==`string`?e.includes(`|`)?e.split(`|`).length===4?n(e,`|`):void 0:n(e,`$`):r(e)}function l(t,n){return new e(`INVALID_TOKEN_REFERENCE`,{field:t,reason:n})}function u(e,t){if(e===void 0)throw l(t,`missing`);let n=c(e);if(n===void 0)throw l(t,`bad_class_key`);return{collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey}}function d(e,t){return{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instance:t}}function f(e,t){return{quantity:s(e.quantity,`${t}quantity`),token:p(e,`${t}token`)}}function p(e,t){let{tokenClassKey:n,tokenName:r,instance:i}=e;if(r!==void 0){if(n!==void 0||i!==void 0)throw l(t,`ambiguous`);if(typeof r!=`string`||r===``)throw l(t,`missing`);return{kind:`name`,tokenName:r}}let a=u(n,t),s=i??`0`;if(typeof s!=`string`||!o.test(s))throw l(t,`bad_instance`);return{kind:`key`,key:d(a,s)}}async function m(n,i){if(n.kind===`key`)return n.key;let{tokenName:a}=n;if(i===void 0)throw new e(`NO_TOKEN_NAME_RESOLVER`,{tokenName:a});let s,c=!1;try{i.resolveTokenInstance===void 0?s=await i.resolveTokenClassKey(a):(c=!0,s=await i.resolveTokenInstance(a))}catch(n){throw t(n)?n:new e(`TOKEN_NAME_RESOLUTION_FAILED`,{tokenName:a},{cause:n})}let l=typeof s==`object`&&s?s:void 0,u=l===void 0?void 0:r(l),f=c?l?.instance:`0`;if(u===void 0||typeof f!=`string`||!o.test(f))throw new e(`TOKEN_NAME_RESOLUTION_FAILED`,{tokenName:a});return d(u,f)}export{f as checkQuantity,p as checkToken,m as resolveToken,u as tokenClassKeyOf,s as writeQuantity};
|
|
2
2
|
//# sourceMappingURL=token_ref.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token_ref.js","names":["BigNumber","DECIMAL","INSTANCE","writeQuantity","value","GalaSDKError","classKeyOf","splitClassKey","tryParseTokenClassKey","invalidReference","tokenClassKeyOf","field","key","instanceKey","checkQuantity","input","at","checkToken","tokenName","tokenClassKey","instance","chosen","resolveToken","token","resolver","resolved","byInstance","cause","isGalaError","record"],"sources":["../../../src/writes/token_ref.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { GalaSDKError, isGalaError } from '../classes/gala_sdk_error.js';\nimport { splitClassKey, tryParseTokenClassKey } from '../utils/class_key.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { GalaChainTokenInstanceKey, TokenNameResolver, TokenQuantityInput } from './types.js';\n\n/** A plain decimal: digits, optionally a fraction. No sign, exponent, hex, spaces or separators. */\nconst DECIMAL = /^[0-9]+(?:\\.[0-9]+)?$/u;\nconst INSTANCE = /^[0-9]+$/u;\n\n/**\n * The quantity of a write, exactly as the caller wrote it: whole tokens as a plain decimal string\n * greater than zero. It is returned unchanged (never scaled to base units, never re-formatted), so\n * the signed amount is the amount the caller passed. A JS number is refused: it may already have\n * lost digits (`0.1 + 0.2`), and the chain receives strings.\n *\n * @throws GalaSDKError `INVALID_QUANTITY`.\n */\nexport function writeQuantity(value: unknown, field: string): string {\n if (typeof value === 'string' && DECIMAL.test(value) && new BigNumber(value).isGreaterThan(0)) {\n return value;\n }\n throw new GalaSDKError('INVALID_QUANTITY', { field, value: String(value) });\n}\n\n/**\n * The class key a write input names, or `undefined` when it is not one. Stricter than\n * `tryParseTokenClassKey` for the pipe form: `a|b|c|d|e` is refused rather than read as collection\n * `a|b`, because a five-part pipe string is someone's `class key|instance`, and signing a transfer\n * of a different collection is the one outcome a write must never have.\n */\nfunction classKeyOf(value: unknown): GalaChainTokenClassKey | undefined {\n if (typeof value !== 'string') return tryParseTokenClassKey(value);\n if (!value.includes('|')) return splitClassKey(value, '$');\n const parts = value.split('|');\n return parts.length === 4 ? splitClassKey(value, '|') : undefined;\n}\n\nfunction invalidReference(\n field: string,\n reason: 'missing' | 'ambiguous' | 'bad_class_key' | 'bad_instance',\n): GalaSDKError<'INVALID_TOKEN_REFERENCE'> {\n return new GalaSDKError('INVALID_TOKEN_REFERENCE', { field, reason });\n}\n\n/**\n * The class key `value` names, in the forms a write accepts (see {@link classKeyOf}), as the four\n * parts and nothing else; the gateway reads take their keys this way too.\n *\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE` (`missing` for `undefined`, else `bad_class_key`).\n */\nexport function tokenClassKeyOf(value: unknown, field: string): GalaChainTokenClassKey {\n if (value === undefined) throw invalidReference(field, 'missing');\n const key = classKeyOf(value);\n if (key === undefined) throw invalidReference(field, 'bad_class_key');\n return {\n collection: key.collection,\n category: key.category,\n type: key.type,\n additionalKey: key.additionalKey,\n };\n}\n\n/** The fields of an instance key, and only those, in the order the chain DTOs carry them. */\nfunction instanceKey(key: GalaChainTokenClassKey, instance: string): GalaChainTokenInstanceKey {\n return {\n collection: key.collection,\n category: key.category,\n type: key.type,\n additionalKey: key.additionalKey,\n instance,\n };\n}\n\n/** A token named either way, checked synchronously; a name is resolved later (see {@link resolveToken}). */\nexport type CheckedToken =\n | { readonly kind: 'key'; readonly key: GalaChainTokenInstanceKey }\n | { readonly kind: 'name'; readonly tokenName: string };\n\n/** One checked token-and-quantity of a write. */\nexport interface CheckedQuantity {\n readonly quantity: string;\n readonly token: CheckedToken;\n}\n\n/**\n * Checks one token-and-quantity input: the quantity as `<at>quantity`, the token as `<at>token`\n * (`at` is `''` for a transfer, `tokens[2].` for a batch entry).\n *\n * @throws GalaSDKError `INVALID_QUANTITY`, `INVALID_TOKEN_REFERENCE`.\n */\nexport function checkQuantity(input: TokenQuantityInput, at: string): CheckedQuantity {\n return {\n quantity: writeQuantity(input.quantity, `${at}quantity`),\n token: checkToken(input, `${at}token`),\n };\n}\n\n/**\n * Checks how a write input names its token, without resolving a name (so invalid input never\n * costs a resolver round trip).\n *\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE`.\n */\nexport function checkToken(input: TokenQuantityInput, field: string): CheckedToken {\n const { tokenClassKey, tokenName, instance } = input;\n if (tokenName !== undefined) {\n if (tokenClassKey !== undefined || instance !== undefined) {\n throw invalidReference(field, 'ambiguous');\n }\n if (typeof tokenName !== 'string' || tokenName === '') throw invalidReference(field, 'missing');\n return { kind: 'name', tokenName };\n }\n const key = tokenClassKeyOf(tokenClassKey, field);\n const chosen: unknown = instance ?? '0';\n if (typeof chosen !== 'string' || !INSTANCE.test(chosen)) {\n throw invalidReference(field, 'bad_instance');\n }\n return { kind: 'key', key: instanceKey(key, chosen) };\n}\n\n/**\n * The instance key a checked token stands for. A name goes through the app's resolver at the\n * boundary of \"nothing was sent\": a rejection becomes `TOKEN_NAME_RESOLUTION_FAILED` (the\n * original as `cause`), an SDK error passes through, and an answer that is not a key is a failed\n * resolution too, so an unusable answer is never signed.\n *\n * @throws GalaSDKError `NO_TOKEN_NAME_RESOLVER`, `TOKEN_NAME_RESOLUTION_FAILED`.\n */\nexport async function resolveToken(\n token: CheckedToken,\n resolver: TokenNameResolver | undefined,\n): Promise<GalaChainTokenInstanceKey> {\n if (token.kind === 'key') return token.key;\n const { tokenName } = token;\n if (resolver === undefined) throw new GalaSDKError('NO_TOKEN_NAME_RESOLVER', { tokenName });\n let resolved: unknown;\n // Decided once, before the await: which answer shape is expected cannot change mid-call.\n let byInstance = false;\n try {\n if (resolver.resolveTokenInstance !== undefined) {\n byInstance = true;\n resolved = await resolver.resolveTokenInstance(tokenName);\n } else {\n resolved = await resolver.resolveTokenClassKey(tokenName);\n }\n } catch (cause: unknown) {\n if (isGalaError(cause)) throw cause;\n throw new GalaSDKError('TOKEN_NAME_RESOLUTION_FAILED', { tokenName }, { cause });\n }\n // Only the documented object answer is accepted: a resolver that answers with a string could\n // hand back a five-part `key|instance` that a lenient parse would read as another collection.\n const record = typeof resolved === 'object' && resolved !== null ? resolved : undefined;\n const key = record === undefined ? undefined : tryParseTokenClassKey(record);\n const instance = byInstance ? (record as { instance?: unknown } | undefined)?.instance : '0';\n if (key === undefined || typeof instance !== 'string' || !INSTANCE.test(instance)) {\n throw new GalaSDKError('TOKEN_NAME_RESOLUTION_FAILED', { tokenName });\n }\n return instanceKey(key, instance);\n}\n"],"mappings":"A,0LAOA,MAAMC,EAAU,yBACVC,EAAW,YAUjB,SAAgBC,EAAc,EAAgB,EAAuB,CACnE,GAAI,OAAOC,GAAU,UAAYH,EAAQ,KAAKG,CAAK,GAAK,IAAIJ,EAAUI,CAAK,CAAC,CAAC,cAAc,CAAC,EAC1F,OAAOA,EAET,MAAM,IAAIC,EAAa,mBAAoB,CAAE,QAAO,MAAO,OAAOD,CAAK,CAAE,CAAC,CAC5E,CAQA,SAASE,EAAW,EAAoD,CAItE,OAHI,OAAOF,GAAU,SAChBA,EAAM,SAAS,GAAG,EACTA,EAAM,MAAM,GACf,CAAC,CAAC,SAAW,EAAIG,EAAcH,EAAO,GAAG,EAAI,IAAA,GAFvBG,EAAcH,EAAO,GAAG,EADnBI,EAAsBJ,CAAK,CAInE,CAEA,SAASK,EACP,EACA,EACyC,CACzC,OAAO,IAAIJ,EAAa,0BAA2B,CAAE,QAAO,QAAO,CAAC,CACtE,CAQA,SAAgBK,EAAgB,EAAgB,EAAuC,CACrF,GAAIN,IAAU,IAAA,GAAW,MAAMK,EAAiBE,EAAO,SAAS,EAChE,IAAMC,EAAMN,EAAWF,CAAK,EAC5B,GAAIQ,IAAQ,IAAA,GAAW,MAAMH,EAAiBE,EAAO,eAAe,EACpE,MAAO,CACL,WAAYC,EAAI,WAChB,SAAUA,EAAI,SACd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vB,MADIC,EAAYD,CAAK,EAASA,EACxB,IAAItB,EAAa,+BAAgC,CAAE,WAAU,EAAG,CAAE,OAAM,CAAC,CACjF,CAGA,IAAMwB,EAAS,OAAOJ,GAAa,UAAYA,EAAoBA,EAAW,IAAA,GACxEb,EAAMiB,IAAW,IAAA,GAAY,IAAA,GAAYrB,EAAsBqB,CAAM,EACrET,EAAWM,EAAcG,GAA+C,SAAW,IACzF,GAAIjB,IAAQ,IAAA,IAAa,OAAOQ,GAAa,UAAY,CAAClB,EAAS,KAAKkB,CAAQ,EAC9E,MAAM,IAAIf,EAAa,+BAAgC,CAAE,WAAU,CAAC,EAEtE,OAAOQ,EAAYD,EAAKQ,CAAQ,CAClC,C"}
|
|
1
|
+
{"version":3,"file":"token_ref.js","names":["BigNumber","DECIMAL","INSTANCE","writeQuantity","value","amount","GalaSDKError","classKeyOf","splitClassKey","tryParseTokenClassKey","invalidReference","tokenClassKeyOf","field","key","instanceKey","checkQuantity","input","at","checkToken","tokenName","tokenClassKey","instance","chosen","resolveToken","token","resolver","resolved","byInstance","cause","isGalaError","record"],"sources":["../../../src/writes/token_ref.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { GalaSDKError, isGalaError } from '../classes/gala_sdk_error.js';\nimport { splitClassKey, tryParseTokenClassKey } from '../utils/class_key.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { GalaChainTokenInstanceKey, TokenNameResolver, TokenQuantityInput } from './types.js';\n\n/** A plain decimal: digits, optionally a fraction. No sign, exponent, hex, spaces or separators. */\nconst DECIMAL = /^[0-9]+(?:\\.[0-9]+)?$/u;\n/**\n * A token instance in the one spelling the chain's `TokenInstanceKey` (`@BigNumberProperty`)\n * accepts: a whole number with no leading zeros (`0`, `7`; never `007` or `00`). Not rewritten:\n * an instance names one token, so a spelling the chain would refuse is refused here.\n */\nconst INSTANCE = /^(?:0|[1-9][0-9]*)$/u;\n/** What the quantity error reports instead of the supplied value: errors never echo input. */\nconst REDACTED = '[redacted]';\n\n/**\n * The quantity of a write: whole tokens as a plain decimal string greater than zero (never scaled\n * to base units), returned in the chain's canonical spelling, `new BigNumber(value).toFixed()`.\n * The chain's DTO classes (`@BigNumberProperty` + `IsBigNumber`) refuse every other spelling of\n * the same number, so `\"1.50\"` is signed as `\"1.5\"`, `\"5.0\"` as `\"5\"` and `\"01\"` as `\"1\"`: the\n * amount the caller passed, in the bytes the chain can execute. A JS number is refused: it may\n * already have lost digits (`0.1 + 0.2`), and the chain receives strings.\n *\n * @throws GalaSDKError `INVALID_QUANTITY` (`params.value` is `[redacted]`: the input is never\n * echoed).\n */\nexport function writeQuantity(value: unknown, field: string): string {\n if (typeof value === 'string' && DECIMAL.test(value)) {\n const amount = new BigNumber(value);\n if (amount.isGreaterThan(0)) return amount.toFixed();\n }\n throw new GalaSDKError('INVALID_QUANTITY', { field, value: REDACTED });\n}\n\n/**\n * The class key a write input names, or `undefined` when it is not one. Stricter than\n * `tryParseTokenClassKey` for the pipe form: `a|b|c|d|e` is refused rather than read as collection\n * `a|b`, because a five-part pipe string is someone's `class key|instance`, and signing a transfer\n * of a different collection is the one outcome a write must never have.\n */\nfunction classKeyOf(value: unknown): GalaChainTokenClassKey | undefined {\n if (typeof value !== 'string') return tryParseTokenClassKey(value);\n if (!value.includes('|')) return splitClassKey(value, '$');\n const parts = value.split('|');\n return parts.length === 4 ? splitClassKey(value, '|') : undefined;\n}\n\nfunction invalidReference(\n field: string,\n reason: 'missing' | 'ambiguous' | 'bad_class_key' | 'bad_instance',\n): GalaSDKError<'INVALID_TOKEN_REFERENCE'> {\n return new GalaSDKError('INVALID_TOKEN_REFERENCE', { field, reason });\n}\n\n/**\n * The class key `value` names, in the forms a write accepts (see {@link classKeyOf}), as the four\n * parts and nothing else; the gateway reads take their keys this way too.\n *\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE` (`missing` for `undefined`, else `bad_class_key`).\n */\nexport function tokenClassKeyOf(value: unknown, field: string): GalaChainTokenClassKey {\n if (value === undefined) throw invalidReference(field, 'missing');\n const key = classKeyOf(value);\n if (key === undefined) throw invalidReference(field, 'bad_class_key');\n return {\n collection: key.collection,\n category: key.category,\n type: key.type,\n additionalKey: key.additionalKey,\n };\n}\n\n/** The fields of an instance key, and only those, in the order the chain DTOs carry them. */\nfunction instanceKey(key: GalaChainTokenClassKey, instance: string): GalaChainTokenInstanceKey {\n return {\n collection: key.collection,\n category: key.category,\n type: key.type,\n additionalKey: key.additionalKey,\n instance,\n };\n}\n\n/** A token named either way, checked synchronously; a name is resolved later (see {@link resolveToken}). */\nexport type CheckedToken =\n | { readonly kind: 'key'; readonly key: GalaChainTokenInstanceKey }\n | { readonly kind: 'name'; readonly tokenName: string };\n\n/** One checked token-and-quantity of a write. */\nexport interface CheckedQuantity {\n readonly quantity: string;\n readonly token: CheckedToken;\n}\n\n/**\n * Checks one token-and-quantity input: the quantity as `<at>quantity`, the token as `<at>token`\n * (`at` is `''` for a transfer, `tokens[2].` for a batch entry).\n *\n * @throws GalaSDKError `INVALID_QUANTITY`, `INVALID_TOKEN_REFERENCE`.\n */\nexport function checkQuantity(input: TokenQuantityInput, at: string): CheckedQuantity {\n return {\n quantity: writeQuantity(input.quantity, `${at}quantity`),\n token: checkToken(input, `${at}token`),\n };\n}\n\n/**\n * Checks how a write input names its token, without resolving a name (so invalid input never\n * costs a resolver round trip).\n *\n * @throws GalaSDKError `INVALID_TOKEN_REFERENCE`.\n */\nexport function checkToken(input: TokenQuantityInput, field: string): CheckedToken {\n const { tokenClassKey, tokenName, instance } = input;\n if (tokenName !== undefined) {\n if (tokenClassKey !== undefined || instance !== undefined) {\n throw invalidReference(field, 'ambiguous');\n }\n if (typeof tokenName !== 'string' || tokenName === '') throw invalidReference(field, 'missing');\n return { kind: 'name', tokenName };\n }\n const key = tokenClassKeyOf(tokenClassKey, field);\n const chosen: unknown = instance ?? '0';\n if (typeof chosen !== 'string' || !INSTANCE.test(chosen)) {\n throw invalidReference(field, 'bad_instance');\n }\n return { kind: 'key', key: instanceKey(key, chosen) };\n}\n\n/**\n * The instance key a checked token stands for. A name goes through the app's resolver at the\n * boundary of \"nothing was sent\": a rejection becomes `TOKEN_NAME_RESOLUTION_FAILED` (the\n * original as `cause`), an SDK error passes through, and an answer that is not a key is a failed\n * resolution too, so an unusable answer is never signed.\n *\n * @throws GalaSDKError `NO_TOKEN_NAME_RESOLVER`, `TOKEN_NAME_RESOLUTION_FAILED`.\n */\nexport async function resolveToken(\n token: CheckedToken,\n resolver: TokenNameResolver | undefined,\n): Promise<GalaChainTokenInstanceKey> {\n if (token.kind === 'key') return token.key;\n const { tokenName } = token;\n if (resolver === undefined) throw new GalaSDKError('NO_TOKEN_NAME_RESOLVER', { tokenName });\n let resolved: unknown;\n // Decided once, before the await: which answer shape is expected cannot change mid-call.\n let byInstance = false;\n try {\n if (resolver.resolveTokenInstance !== undefined) {\n byInstance = true;\n resolved = await resolver.resolveTokenInstance(tokenName);\n } else {\n resolved = await resolver.resolveTokenClassKey(tokenName);\n }\n } catch (cause: unknown) {\n if (isGalaError(cause)) throw cause;\n throw new GalaSDKError('TOKEN_NAME_RESOLUTION_FAILED', { tokenName }, { cause });\n }\n // Only the documented object answer is accepted: a resolver that answers with a string could\n // hand back a five-part `key|instance` that a lenient parse would read as another collection.\n const record = typeof resolved === 'object' && resolved !== null ? resolved : undefined;\n const key = record === undefined ? undefined : tryParseTokenClassKey(record);\n const instance = byInstance ? (record as { instance?: unknown } | undefined)?.instance : '0';\n if (key === undefined || typeof instance !== 'string' || !INSTANCE.test(instance)) {\n throw new GalaSDKError('TOKEN_NAME_RESOLUTION_FAILED', { tokenName });\n }\n return instanceKey(key, instance);\n}\n"],"mappings":"A,0LAOA,MAAMC,EAAU,yBAMVC,EAAW,uBAejB,SAAgBC,EAAc,EAAgB,EAAuB,CACnE,GAAI,OAAOC,GAAU,UAAYH,EAAQ,KAAKG,CAAK,EAAG,CACpD,IAAMC,EAAS,IAAIL,EAAUI,CAAK,EAClC,GAAIC,EAAO,cA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enInstance:n.key,uniqueKey:r}}function n(e,t){return{tokenInstances:e.map(e=>({quantity:e.quantity,tokenInstanceKey:e.key})),uniqueKey:t}}export{e as GALA_TOKEN_CLASS_KEY,n as burnTokensDto,t as transferTokenDto};
|
|
1
|
+
const e=Object.freeze({collection:`GALA`,category:`Unit`,type:`none`,additionalKey:`none`});function t(e,t,n,r,i){return{from:e,to:t,quantity:n.quantity,tokenInstance:n.key,uniqueKey:r,...i===void 0?{}:{dtoExpiresAt:i}}}function n(e,t){return{tokenInstances:e.map(e=>({quantity:e.quantity,tokenInstanceKey:e.key})),uniqueKey:t}}export{e as GALA_TOKEN_CLASS_KEY,n as burnTokensDto,t as transferTokenDto};
|
|
2
2
|
//# sourceMappingURL=transfer.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transfer.js","names":["GALA_TOKEN_CLASS_KEY","transferTokenDto","token","burnTokensDto","tokens"],"sources":["../../../src/writes/transfer.ts"],"sourcesContent":["import type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { GalaChainTokenInstanceKey } from './types.js';\n\n/** GALA's class key: what `transferGala` moves. */\nexport const GALA_TOKEN_CLASS_KEY: Readonly<GalaChainTokenClassKey> = Object.freeze({\n collection: 'GALA',\n category: 'Unit',\n type: 'none',\n additionalKey: 'none',\n});\n\n/** One token and the quantity of it a write moves, after checking and resolution. */\nexport interface ResolvedQuantity {\n readonly quantity: string;\n readonly key: GalaChainTokenInstanceKey;\n}\n\n/**\n * The unsigned `TransferToken` DTO: plain JSON, exactly the fields the chain signs, in the order\n * the gateway has always received them (`from, to, quantity, tokenInstance, uniqueKey`)
|
|
1
|
+
{"version":3,"file":"transfer.js","names":["GALA_TOKEN_CLASS_KEY","transferTokenDto","token","dtoExpiresAt","burnTokensDto","tokens"],"sources":["../../../src/writes/transfer.ts"],"sourcesContent":["import type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { GalaChainTokenInstanceKey } from './types.js';\n\n/** GALA's class key: what `transferGala` moves. */\nexport const GALA_TOKEN_CLASS_KEY: Readonly<GalaChainTokenClassKey> = Object.freeze({\n collection: 'GALA',\n category: 'Unit',\n type: 'none',\n additionalKey: 'none',\n});\n\n/** One token and the quantity of it a write moves, after checking and resolution. */\nexport interface ResolvedQuantity {\n readonly quantity: string;\n readonly key: GalaChainTokenInstanceKey;\n}\n\n/**\n * The unsigned `TransferToken` DTO: plain JSON, exactly the fields the chain signs, in the order\n * the gateway has always received them (`from, to, quantity, tokenInstance, uniqueKey`), then\n * `dtoExpiresAt` only when one is given (absent: the DTO, its bytes and its signature are exactly\n * what they were before the field existed). No signer field is ever added: the chain recovers the\n * signer from the signature.\n */\nexport function transferTokenDto(\n from: string,\n to: string,\n token: ResolvedQuantity,\n uniqueKey: string,\n dtoExpiresAt?: number,\n): Record<string, unknown> {\n return {\n from,\n to,\n quantity: token.quantity,\n tokenInstance: token.key,\n uniqueKey,\n ...(dtoExpiresAt === undefined ? {} : { dtoExpiresAt }),\n };\n}\n\n/** The unsigned `BurnTokens` DTO (`tokenInstances, uniqueKey`); burns are of the signer's own tokens. */\nexport function burnTokensDto(\n tokens: readonly ResolvedQuantity[],\n uniqueKey: string,\n): Record<string, unknown> {\n return {\n tokenInstances: tokens.map((token) => ({\n quantity: token.quantity,\n tokenInstanceKey: token.key,\n })),\n uniqueKey,\n };\n}\n"],"mappings":"AAIA,MAAaA,EAAyD,OAAO,OAAO,CAClF,WAAY,OACZ,SAAU,OACV,KAAM,OACN,cAAe,MACjB,CAAC,EAeD,SAAgBC,EACd,EACA,EACA,EACA,EACA,EACyB,CACzB,MAAO,CACL,OACA,KACA,SAAUC,EAAM,SAChB,cAAeA,EAAM,IACrB,YACA,GAAIC,IAAiB,IAAA,GAAY,CAAC,EAAI,CAAE,cAAa,CACvD,CACF,CAGA,SAAgBC,EACd,EACA,EACyB,CACzB,MAAO,CACL,eAAgBC,EAAO,IAAK,IAAW,CACrC,SAAUH,EAAM,SAChB,iBAAkBA,EAAM,GAC1B,EAAE,EACF,WACF,CACF,C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":["GATEWAY_WRITE_METHODS","GATEWAY_WRITE_BATCH_LIMITS"],"sources":["../../../src/writes/types.ts"],"sourcesContent":["import type { GalaChainSigner } from '../classes/signers.js';\nimport type { HttpRequestor } from '../types/http_requestor.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { WireOptions } from '../types/wire.js';\n\n/** The token-contract methods `GatewayWrites` signs and submits, as a closed set. */\nexport const GATEWAY_WRITE_METHODS = [\n 'TransferToken',\n 'BurnTokens',\n 'LockToken',\n 'UnlockToken',\n] as const;\n\n/** One member of {@link GATEWAY_WRITE_METHODS}. */\nexport type GatewayWriteMethod = (typeof GATEWAY_WRITE_METHODS)[number];\n\n/** The most tokens one write may carry (GalaChain batch limits; a burn is irreversible, so fewer). */\nexport const GATEWAY_WRITE_BATCH_LIMITS: Readonly<\n Record<Exclude<GatewayWriteMethod, 'TransferToken'>, number>\n> = Object.freeze({ BurnTokens: 50, LockToken: 100, UnlockToken: 100 });\n\n/** A token class key plus the instance of it a write moves (`\"0\"` for a fungible token). */\nexport interface GalaChainTokenInstanceKey extends GalaChainTokenClassKey {\n instance: string;\n}\n\n/**\n * A token class key as a write accepts it: `collection|category|type|additionalKey` (exactly four\n * parts), the `$`-joined composite key (split from the right, so a `$GMUSIC` collection stays\n * whole), or the four-part object. A bare symbol is never one, and none is derived from it.\n */\nexport type TokenClassKeyInput = string | GalaChainTokenClassKey;\n\n/**\n * Turns a product's token NAME (a launchpad token's name, say) into the chain key a write signs.\n * Optional: it is consulted only for inputs that name a token by `tokenName`; a `tokenClassKey`\n * never needs it. A rejection is `TOKEN_NAME_RESOLUTION_FAILED` (pre-send, the original error as\n * `cause`); an SDK error it throws passes through as it is.\n */\nexport interface TokenNameResolver {\n /** The class key `tokenName` stands for; the write moves its fungible instance `\"0\"`. */\n resolveTokenClassKey(tokenName: string): Promise<GalaChainTokenClassKey>;\n /**\n * The instance key `tokenName` stands for, when the product names a specific instance. When\n * present it is used instead of {@link resolveTokenClassKey}.\n */\n resolveTokenInstance?(tokenName: string): Promise<GalaChainTokenInstanceKey>;\n}\n\n/**\n * One token and amount of a write. Name the token with exactly one of `tokenClassKey` (plus an\n * optional `instance`) or `tokenName` (needs a `TokenNameResolver`).\n */\nexport interface TokenQuantityInput {\n /** The token's class key. */\n tokenClassKey?: TokenClassKeyInput | undefined;\n /** The instance of `tokenClassKey` to move, a decimal string; default `\"0\"` (fungible). */\n instance?: string | undefined;\n /** A product token name, resolved by the configured `TokenNameResolver`. */\n tokenName?: string | undefined;\n /**\n * The amount in WHOLE tokens, as the decimal string the chain is to receive (`\"1.5\"` is one and a\n * half tokens).
|
|
1
|
+
{"version":3,"file":"types.js","names":["GATEWAY_WRITE_METHODS","GATEWAY_WRITE_BATCH_LIMITS"],"sources":["../../../src/writes/types.ts"],"sourcesContent":["import type { GalaChainSigner } from '../classes/signers.js';\nimport type { HttpRequestor } from '../types/http_requestor.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport type { WireOptions } from '../types/wire.js';\n\n/** The token-contract methods `GatewayWrites` signs and submits, as a closed set. */\nexport const GATEWAY_WRITE_METHODS = [\n 'TransferToken',\n 'BurnTokens',\n 'LockToken',\n 'UnlockToken',\n] as const;\n\n/** One member of {@link GATEWAY_WRITE_METHODS}. */\nexport type GatewayWriteMethod = (typeof GATEWAY_WRITE_METHODS)[number];\n\n/** The most tokens one write may carry (GalaChain batch limits; a burn is irreversible, so fewer). */\nexport const GATEWAY_WRITE_BATCH_LIMITS: Readonly<\n Record<Exclude<GatewayWriteMethod, 'TransferToken'>, number>\n> = Object.freeze({ BurnTokens: 50, LockToken: 100, UnlockToken: 100 });\n\n/** A token class key plus the instance of it a write moves (`\"0\"` for a fungible token). */\nexport interface GalaChainTokenInstanceKey extends GalaChainTokenClassKey {\n instance: string;\n}\n\n/**\n * A token class key as a write accepts it: `collection|category|type|additionalKey` (exactly four\n * parts), the `$`-joined composite key (split from the right, so a `$GMUSIC` collection stays\n * whole), or the four-part object. A bare symbol is never one, and none is derived from it.\n */\nexport type TokenClassKeyInput = string | GalaChainTokenClassKey;\n\n/**\n * Turns a product's token NAME (a launchpad token's name, say) into the chain key a write signs.\n * Optional: it is consulted only for inputs that name a token by `tokenName`; a `tokenClassKey`\n * never needs it. A rejection is `TOKEN_NAME_RESOLUTION_FAILED` (pre-send, the original error as\n * `cause`); an SDK error it throws passes through as it is.\n */\nexport interface TokenNameResolver {\n /** The class key `tokenName` stands for; the write moves its fungible instance `\"0\"`. */\n resolveTokenClassKey(tokenName: string): Promise<GalaChainTokenClassKey>;\n /**\n * The instance key `tokenName` stands for, when the product names a specific instance. When\n * present it is used instead of {@link resolveTokenClassKey}.\n */\n resolveTokenInstance?(tokenName: string): Promise<GalaChainTokenInstanceKey>;\n}\n\n/**\n * One token and amount of a write. Name the token with exactly one of `tokenClassKey` (plus an\n * optional `instance`) or `tokenName` (needs a `TokenNameResolver`).\n */\nexport interface TokenQuantityInput {\n /** The token's class key. */\n tokenClassKey?: TokenClassKeyInput | undefined;\n /** The instance of `tokenClassKey` to move, a decimal string; default `\"0\"` (fungible). */\n instance?: string | undefined;\n /** A product token name, resolved by the configured `TokenNameResolver`. */\n tokenName?: string | undefined;\n /**\n * The amount in WHOLE tokens, as the decimal string the chain is to receive (`\"1.5\"` is one and a\n * half tokens). Never scaled to base units; signed in the chain's canonical spelling\n * (`BigNumber#toFixed()`: `\"1.50\"` is signed `\"1.5\"`), the only one the chain's DTO classes accept.\n */\n quantity: string;\n}\n\n/** Options every write takes. */\nexport interface WriteKeyInput {\n /**\n * The write's idempotency key: 1 to 128 characters of `A-Za-z0-9._:-`. Reuse a key only to retry\n * the SAME write. Omitted: a fresh `<uniqueKeyPrefix><uuid v4>` is minted (CSPRNG).\n */\n uniqueKey?: string | undefined;\n}\n\n/** The optional signed expiry of a transfer. */\nexport interface DtoExpiresAtInput {\n /**\n * When the chain stops accepting this signed DTO, in epoch MILLISECONDS: a safe integer above\n * zero (`INVALID_DTO_EXPIRES_AT` otherwise). It is part of the signed bytes, so it cannot be\n * removed or changed without invalidating the signature; the chain refuses the DTO once\n * `dtoExpiresAt < Date.now()` on its own clock. Omitted: no field, and the DTO is byte-for-byte\n * what it was before this option existed (the chain then applies no expiry). The SDK signs the\n * value as given and applies no window: a wallet derives it from its quote (`expiresAtMs`)\n * through `@gala-games/wallet-core`'s `buildTransferTokenDto`, which bounds it to 60 s.\n */\n dtoExpiresAt?: number | undefined;\n}\n\n/** `transferGala`: GALA (`GALA|Unit|none|none`, instance `\"0\"`) to a recipient. */\nexport interface TransferGalaInput extends WriteKeyInput, DtoExpiresAtInput {\n /**\n * The recipient: an Ethereum account (`eth|<40 hex>`, `0x<40 hex>` or `<40 hex>`, any casing\n * but a wrong EIP-55 checksum; always sent as `eth|<checksummed>`), or a `client|` alias (sent\n * as written). `eth|0x<40 hex>` is not an address form and is refused\n * (`INVALID_ETH_USER_REF_PREFIX`).\n */\n to: string;\n /** Whole GALA, as a decimal string (see {@link TokenQuantityInput.quantity}). */\n quantity: string;\n}\n\n/** `transferToken`: one token to a recipient. */\nexport interface TransferTokenInput extends TokenQuantityInput, WriteKeyInput, DtoExpiresAtInput {\n /** The recipient (see {@link TransferGalaInput.to}). */\n to: string;\n}\n\n/** `burnTokens`: 1 to 50 tokens, burned from the writer's own balance. IRREVERSIBLE. */\nexport interface BurnTokensInput extends WriteKeyInput {\n tokens: readonly TokenQuantityInput[];\n}\n\n/** `lockTokens`: 1 to 100 tokens of the writer's, held under one lock. */\nexport interface LockTokensInput extends WriteKeyInput {\n tokens: readonly TokenQuantityInput[];\n /** Who may unlock (see {@link TransferGalaInput.to} for the forms); default the writer itself. */\n lockAuthority?: string | undefined;\n /** When the hold expires, in epoch milliseconds; `0` (or omitted) means it never expires. */\n expires?: number | undefined;\n /** A name for the hold, so it can be unlocked by name. */\n name?: string | undefined;\n}\n\n/** `unlockTokens`: 1 to 100 tokens of the writer's, released from their hold. */\nexport interface UnlockTokensInput extends WriteKeyInput {\n tokens: readonly TokenQuantityInput[];\n /** The name of the hold to release. */\n name?: string | undefined;\n}\n\n/** How to reach and sign for the gateway. */\nexport interface GatewayWritesOptions {\n /**\n * The GalaChain gateway base URL; every write POSTs to\n * `<gatewayBaseUrl>/api/asset/token-contract/<Method>`. `''` sends the bare path, for an\n * `httpRequestor` that resolves paths against its own base (an HTTP client with a base URL).\n */\n gatewayBaseUrl: string;\n /** Signs every write. The DTO it is handed is exactly what is signed; nothing is added to it. */\n signer: GalaChainSigner;\n /**\n * The identity the writes are made AS: the sender of a transfer, the owner of what is burned,\n * locked or unlocked, and the default lock authority, in the forms of\n * {@link TransferGalaInput.to} (an Ethereum account is always sent as `eth|<checksummed>`).\n * It must be the account the signer's key acts as; the chain refuses a write whose sender is\n * not its signer.\n */\n walletAddress: string;\n /** The HTTP requestor; default the global `fetch`. Its own rejections reach the caller unchanged. */\n httpRequestor?: HttpRequestor | undefined;\n /** Timeout of every write request in milliseconds (default 30 000); `Infinity` arms no timer. */\n requestTimeoutMs?: number | undefined;\n /** Headers of every write request (`userAgent`, `headers`); see {@link WireOptions}. */\n wire?: WireOptions | undefined;\n /** Resolves `tokenName` inputs; only needed when a write names a token that way. */\n tokenNameResolver?: TokenNameResolver | undefined;\n /** Prefix of every minted `uniqueKey` (default `galaswap-operation-`); see `UniqueKeyOptions`. */\n uniqueKeyPrefix?: string | undefined;\n}\n\n/**\n * What a gateway write returns once GalaChain accepted it (`Status: 1`).\n */\nexport interface WriteReceipt<M extends string> {\n /** The method that was submitted. */\n readonly method: M;\n /** The `uniqueKey` that was signed (the minted one when the caller gave none). */\n readonly uniqueKey: string;\n /**\n * The chain transaction id: the gateway's `x-transaction-id` header, else a top-level\n * `transactionId` of the answer; `undefined` when it named none. Never guessed from the `Data`\n * items (a balance's `id` is not a transaction id).\n */\n readonly transactionId: string | undefined;\n /** The block the write landed in, from the gateway's `x-block-number` header, when it sent one. */\n readonly blockNumber: number | undefined;\n /** The chain's result: the answer's `Data` (balances, holds or burns), as GalaChain returned it. */\n readonly data: unknown;\n /** The whole parsed answer. */\n readonly body: unknown;\n}\n\n/** What a token write (transfer, burn, lock, unlock) returns once GalaChain accepted it. */\nexport type GatewayWriteReceipt = WriteReceipt<GatewayWriteMethod>;\n"],"mappings":"AAMA,MAAaA,EAAwB,CACnC,gBACA,aACA,YACA,aACF,EAMaC,EAET,OAAO,OAAO,CAAE,WAAY,GAAI,UAAW,IAAK,YAAa,GAAI,CAAC,E"}
|