@gala-chain/gala-core-sdk 1.1.0-beta.9 → 1.2.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -2
- 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/reads/gateway_reads.js +1 -1
- package/dist/browser/reads/nft_collections.js +2 -0
- package/dist/browser/reads/nft_collections.js.map +1 -0
- package/dist/browser/reads/nft_fees.js +2 -0
- package/dist/browser/reads/nft_fees.js.map +1 -0
- package/dist/browser/reads/request.js +1 -1
- package/dist/browser/reads/request.js.map +1 -1
- package/dist/browser/utils/transport.js +1 -1
- package/dist/browser/version.js +1 -1
- package/dist/browser/version.js.map +1 -1
- package/dist/browser/writes/gateway_writes.js +1 -1
- package/dist/browser/writes/gateway_writes.js.map +1 -1
- package/dist/browser/writes/nft.js +2 -0
- package/dist/browser/writes/nft.js.map +1 -0
- package/dist/browser/writes/nft_fee.js +2 -0
- package/dist/browser/writes/nft_fee.js.map +1 -0
- package/dist/browser/writes/submit.js +1 -1
- package/dist/browser/writes/submit.js.map +1 -1
- package/dist/browser/writes/types.js.map +1 -1
- package/dist/index.cjs +716 -134
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +255 -3
- package/dist/index.d.ts +255 -3
- package/dist/index.mjs +709 -135
- package/dist/index.mjs.map +1 -1
- package/package.json +32 -30
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.js","names":["CONTRACT_OF","ANSWERED_WITHOUT_STATUS","channelOf","collection","isRecord","value","stringField","record","key","chainErrorOf","body","nested","\"error\"","readGateway","url","transport","channel","method","response","requestWithTimeout","buildRequestHeaders","answer","readResponseBody","cause","GalaSDKError","dataOf","context","envelope","chainStatus","\"Status\"","chainError","statusAccepted","\"Data\"","invalidAnswer","data"],"sources":["../../../src/reads/request.ts"],"sourcesContent":["import { GalaSDKError, type GalaErrorContext } from '../classes/gala_sdk_error.js';\nimport type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { buildRequestHeaders, readResponseBody, requestWithTimeout } from '../utils/transport.js';\nimport type { GatewayReadMethod } from './types.js';\n\n/** What every read is sent with. */\nexport interface ReadTransport {\n readonly gatewayBaseUrl: string;\n readonly requestor: HttpRequestor;\n readonly timeoutMs: number;\n readonly wire: WireOptions | undefined;\n}\n\n/** The gateway channel a token lives on. */\nexport type GatewayChannel = 'asset' | 'music';\n\n/** The chaincode contract each read method belongs to (part of its URL). */\nconst CONTRACT_OF: Readonly<Record<GatewayReadMethod, 'token-contract' | 'public-key-contract'>> = {\n FetchBalances: 'token-contract',\n FetchTokenClasses: 'token-contract',\n FetchTokenClassesWithSupply: 'token-contract',\n FetchTokenClassesWithPagination: 'token-contract',\n FetchNftCollectionAuthorizationsWithPagination: 'token-contract',\n GetPublicKey: 'public-key-contract',\n};\n\n/**\n * Methods whose successful answer carries no `Status`: the connect-api GalaChain proxies answer\n * `GetPublicKey` with `{ Data: { publicKey } }` only (recorded 2026-10-14, prod and stage,\n * `tests/fixtures/public-key-recorded.json`). A `Status` they do send is still checked.\n */\nconst ANSWERED_WITHOUT_STATUS: ReadonlySet<
|
|
1
|
+
{"version":3,"file":"request.js","names":["CONTRACT_OF","ANSWERED_WITHOUT_STATUS","channelOf","collection","isRecord","value","stringField","record","key","chainErrorOf","body","nested","\"error\"","readGateway","url","transport","channel","method","response","requestWithTimeout","buildRequestHeaders","answer","readResponseBody","cause","GalaSDKError","dataOf","context","envelope","chainStatus","\"Status\"","chainError","statusAccepted","\"Data\"","invalidAnswer","data"],"sources":["../../../src/reads/request.ts"],"sourcesContent":["import { GalaSDKError, type GalaErrorContext } from '../classes/gala_sdk_error.js';\nimport type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { buildRequestHeaders, readResponseBody, requestWithTimeout } from '../utils/transport.js';\nimport type { GatewayReadMethod } from './types.js';\n\n/** What every read is sent with. */\nexport interface ReadTransport {\n readonly gatewayBaseUrl: string;\n readonly requestor: HttpRequestor;\n readonly timeoutMs: number;\n readonly wire: WireOptions | undefined;\n}\n\n/** The gateway channel a token lives on. */\nexport type GatewayChannel = 'asset' | 'music';\n\n/** The chaincode contract each read method belongs to (part of its URL). */\nconst CONTRACT_OF: Readonly<Record<GatewayReadMethod, 'token-contract' | 'public-key-contract'>> = {\n FetchBalances: 'token-contract',\n FetchTokenClasses: 'token-contract',\n FetchTokenClassesWithSupply: 'token-contract',\n FetchTokenClassesWithPagination: 'token-contract',\n FetchNftCollectionAuthorizationsWithPagination: 'token-contract',\n GetPublicKey: 'public-key-contract',\n};\n\n/**\n * Methods whose successful answer carries no `Status`: the connect-api GalaChain proxies answer\n * `GetPublicKey` with `{ Data: { publicKey } }` only (recorded 2026-10-14, prod and stage,\n * `tests/fixtures/public-key-recorded.json`). A `Status` they do send is still checked.\n */\nconst ANSWERED_WITHOUT_STATUS: ReadonlySet<string> = new Set<string>(['GetPublicKey']);\n\n/**\n * The channel of a collection: `$MUSIC` (and `MUSIC`, any case) lives on the gateway's `music`\n * channel, every other collection (`$GMUSIC` included) on `asset`.\n */\nexport function channelOf(collection: string | undefined): GatewayChannel {\n return collection !== undefined && /^\\$?music$/iu.test(collection) ? 'music' : 'asset';\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: Record<string, unknown> | undefined, key: string): string {\n const value = record?.[key];\n return typeof value === 'string' ? value : '';\n}\n\n/**\n * The chain's error object of a refused answer: GalaChain's gateway nests it as\n * `{ error: { Status: 0, ErrorKey, Message, ErrorPayload }, message }`; an older answer carries\n * `Status` / `ErrorKey` / `Message` at the top.\n */\nexport function chainErrorOf(body: unknown): Record<string, unknown> | undefined {\n if (!isRecord(body)) return undefined;\n const nested = body['error'];\n return isRecord(nested) ? nested : body;\n}\n\n/**\n * POSTs one read and returns the chain's `Data`. Reads change nothing, so every failure is a READ's\n * (`error.write === false`) and a retry is always safe:\n *\n * - no answer: `REQUEST_TIMEOUT` / `TRANSPORT_ERROR`, both `write: false` (an app requestor's\n * own rejection passes through unchanged: it is the app's error); a body that broke off is\n * `TRANSPORT_ERROR`;\n * - a numeric top-level `Status` other than 1, in any HTTP status: `GATEWAY_READ_REJECTED`;\n * - any other non-2xx: `GATEWAY_HTTP_ERROR` (`params.status`; the chain's refusal is `error.body`);\n * - a 2xx that is not `{ Status: 1, Data }` (for `GetPublicKey`, whose answer carries no\n * `Status`, not `{ Data }`): `GATEWAY_READ_RESPONSE_INVALID`.\n */\nexport async function readGateway(\n transport: ReadTransport,\n method: GatewayReadMethod,\n body: Record<string, unknown>,\n channel: GatewayChannel = 'asset',\n): Promise<unknown> {\n const url = `${transport.gatewayBaseUrl}/api/${channel}/${CONTRACT_OF[method]}/${method}`;\n const response = await requestWithTimeout(\n transport.requestor,\n url,\n {\n method: 'POST',\n headers: buildRequestHeaders(transport.wire, { json: true }),\n body: JSON.stringify(body),\n },\n transport.timeoutMs,\n { write: false },\n );\n let answer: unknown;\n try {\n answer = await readResponseBody(response);\n } catch (cause: unknown) {\n // The answer's headers arrived and its body broke off: nothing usable was read.\n throw new GalaSDKError('TRANSPORT_ERROR', { url }, { url, cause, write: false });\n }\n return dataOf(method, url, response, answer);\n}\n\n/**\n * The chain's `Data` of a read-like answer, or the error for one that is not (see\n * {@link readGateway} for the codes). Also the reading of a signed DryRun answer, which changes\n * nothing either, so it names its own `method` (a string, not a read method).\n */\nexport function dataOf(\n method: string,\n url: string,\n response: HTTPResponse,\n answer: unknown,\n): unknown {\n const context: GalaErrorContext = { status: response.status, body: answer, url, write: false };\n const envelope = isRecord(answer) ? answer : undefined;\n const chainStatus = envelope?.['Status'];\n if (typeof chainStatus === 'number' && chainStatus !== 1) {\n throw new GalaSDKError(\n 'GATEWAY_READ_REJECTED',\n {\n method,\n chainStatus,\n errorKey: stringField(envelope, 'ErrorKey'),\n serverMessage: stringField(envelope, 'Message'),\n },\n context,\n );\n }\n if (!response.ok) {\n const chainError = chainErrorOf(answer);\n throw new GalaSDKError(\n 'GATEWAY_HTTP_ERROR',\n {\n method,\n status: response.status,\n serverMessage: stringField(chainError, 'Message') || stringField(envelope, 'message'),\n },\n context,\n );\n }\n const statusAccepted =\n chainStatus === 1 || (chainStatus === undefined && ANSWERED_WITHOUT_STATUS.has(method));\n if (envelope === undefined || !statusAccepted || !('Data' in envelope)) {\n throw new GalaSDKError('GATEWAY_READ_RESPONSE_INVALID', { method }, context);\n }\n return envelope['Data'];\n}\n\n/** The error for a 2xx whose `Data` is not what `method` answers. */\nexport function invalidAnswer(\n method: GatewayReadMethod,\n data: unknown,\n): GalaSDKError<'GATEWAY_READ_RESPONSE_INVALID'> {\n return new GalaSDKError(\n 'GATEWAY_READ_RESPONSE_INVALID',\n { method },\n { body: data, write: false },\n );\n}\n"],"mappings":"A,sKAkBA,MAAMA,EAA6F,CACjG,cAAe,iBACf,kBAAmB,iBACnB,4BAA6B,iBAC7B,gCAAiC,iBACjC,+CAAgD,iBAChD,aAAc,qBAChB,EAOMC,kBAA+C,IAAI,IAAY,CAAC,cAAc,CAAC,EAMrF,SAAgBC,EAAU,EAAgD,CACxE,OAAOC,IAAe,IAAA,IAAa,eAAe,KAAKA,CAAU,EAAI,QAAU,OACjF,CAEA,SAASC,EAAS,EAAkD,CAClE,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,CAEA,SAASC,EAAY,EAA6C,EAAqB,CACrF,IAAMD,EAAQE,IAASC,GACvB,OAAO,OAAOH,GAAU,SAAWA,EAAQ,EAC7C,CAOA,SAAgBI,EAAa,EAAoD,CAC/E,GAAI,CAACL,EAASM,CAAI,EAAG,OACrB,IAAMC,EAASD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M,EACvF,GAAIU,IAAa,IAAA,IAAa,CAACI,GAAkB,EAAE,SAAUJ,GAC3D,MAAM,IAAIH,EAAa,gCAAiC,CAAE,QAAO,EAAGE,CAAO,EAE7E,OAAOC,EAASK,IAClB,CAGA,SAAgBC,EACd,EACA,EAC+C,CAC/C,OAAO,IAAIT,EACT,gCACA,CAAE,QAAO,EACT,CAAE,KAAMU,EAAM,MAAO,EAAM,CAC7B,CACF,C"}
|
|
@@ -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.2.0-beta.1`}),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
|
package/dist/browser/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=`1.
|
|
1
|
+
const e=`1.2.0-beta.1`;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.2.0-beta.1';\n"],"mappings":"AAOA,MAAaA,EAAA,e"}
|
|
@@ -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 c,lockName as l,lockTokenDto as u,unlockTokenDto as d}from"./lock.js";import{
|
|
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 c,lockName as l,lockTokenDto as u,unlockTokenDto as d}from"./lock.js";import{claimNftCollectionDto as f,claimedCollection as p,createNftCollectionDto as m,createdTokenClass as h,mintNftDto as g,mintedInstances as _,nftAuthorities as v,nftCallerPublicKey as y,nftClassPart as b,nftMintQuantity as x,nftString as S,nftText as C,nftTokenClass as w,nftWholeNumber as T}from"./nft.js";import{submitWrite as E}from"./submit.js";import{quoteNftFee as D}from"./nft_fee.js";import{checkQuantity as O,resolveToken as k}from"./token_ref.js";import{GALA_TOKEN_CLASS_KEY as A,burnTokensDto as j,transferTokenDto as M}from"./transfer.js";import{GATEWAY_WRITE_BATCH_LIMITS as N}from"./types.js";var P=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:A,uniqueKey:e.uniqueKey})}async transferToken(e){let t=n(e.to,`to`),r=O(e,``),i=this.uniqueKeyOf(e.uniqueKey),a=await this.resolveOne(r);return this.submit(`TransferToken`,M(this.walletAddress,t,a,i),i)}async burnTokens(e){let t=this.checkBatch(`BurnTokens`,e.tokens),n=this.uniqueKeyOf(e.uniqueKey),r=await this.resolveAll(t);return this.submit(`BurnTokens`,j(r,n),n)}async lockTokens(e){let t=e.lockAuthority===void 0?this.walletAddress:n(e.lockAuthority,`lockAuthority`),r=c(e.expires),i=l(e.name),a=this.checkBatch(`LockToken`,e.tokens),o=this.uniqueKeyOf(e.uniqueKey),s=await this.resolveAll(a);return this.submit(`LockToken`,u(t,this.walletAddress,s,o,r,i),o)}async unlockTokens(e){let t=l(e.name),n=this.checkBatch(`UnlockToken`,e.tokens),r=this.uniqueKeyOf(e.uniqueKey),i=await this.resolveAll(n);return this.submit(`UnlockToken`,d(this.walletAddress,i,r,t),r)}async claimNftCollection(e){let t=this.prepareClaim(e),n=await E(this.transport,`GrantNftCollectionAuthorization`,t.dto,t.uniqueKey);return p(n,t.collection)}async createNftCollection(e){let t=this.prepareCreate(e),n=await E(this.transport,`CreateNftCollection`,t.dto,t.uniqueKey);return h(n,t.tokenClass)}async mintNft(e){let t=this.prepareMint(e),n=await E(this.transport,t.method,t.dto,t.uniqueKey);return _(n,t.tokenClass,t.quantity)}async estimateNftFee(e,t){let n=y(t.callerPublicKey),r=this.prepareFeeRequest(e);return await D(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=b(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:f(t,r,i)}}prepareCreate(e){let t=w(e),n={name:C(e.name,`name`),symbol:S(e.symbol,`symbol`),description:C(e.description,`description`),image:C(e.image,`image`),maxSupply:T(e.maxSupply,`maxSupply`),maxCapacity:e.maxCapacity===void 0?void 0:T(e.maxCapacity,`maxCapacity`),metadataAddress:e.metadataAddress===void 0?void 0:C(e.metadataAddress,`metadataAddress`),contractAddress:e.contractAddress===void 0?void 0:C(e.contractAddress,`contractAddress`),rarity:e.rarity===void 0?void 0:C(e.rarity,`rarity`),authorities:e.authorities===void 0?void 0:v(e.authorities)},r=this.uniqueKeyOf(e.uniqueKey);return{tokenClass:t,uniqueKey:r,dto:m(t,n,r)}}prepareMint(e){let t=w(e),r=x(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:g(a,t,i,r,o)}}uniqueKeyOf(e){return e===void 0?o(this.uniqueKeyPrefix):(a(e),e)}checkBatch(e,n){let r=N[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)=>O(e,`tokens[${t}].`))}async resolveOne(e){return{quantity:e.quantity,key:await k(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 E(this.transport,e,t,n)}};export{P 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","given","createUniqueKey","assertUniqueKey","max","GATEWAY_WRITE_BATCH_LIMITS","method","count","index","resolveToken","resolved","entry","submitWrite","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 { 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 {\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 * 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 /** 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,ytBAiDA,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,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,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","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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,EAAQF,EACvB,MAAM,IAAIvD,EAAa,sBAAuB,CAAE,SAAQ,QAAO,KAAI,CAAC,EAEtE,OAAOgB,EAAO,KAAK,EAAO,IAAUJ,EAAcJ,EAAO,UAAUkD,EAAM,GAAG,CAAC,CAC/E,CAEA,MAAc,WAAW,EAAqD,CAC5E,MAAO,CACL,SAAU/C,EAAQ,SAClB,IAAK,MAAMgD,EAAahD,EAAQ,MAAO,KAAK,iBAAiB,CAC/D,CACF,CAGA,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"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{GalaSDKError as e}from"../classes/gala_sdk_error.js";import{galaChainUserRef as t}from"./identity.js";import n from"bignumber.js";const r=[`GrantNftCollectionAuthorization`,`CreateNftCollection`,`MintTokenWithAllowance`,`MintToken`],i=1e3,a=`none`;function o(t,n){return new e(`INVALID_NFT_INPUT`,{field:t,reason:n})}function s(e){for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<=31||n>=127&&n<=159)return!0}return!1}function c(e,t){if(typeof e!=`string`)throw o(t,`not_a_string`);if(e.trim()===``)throw o(t,`empty`);if(e.trim()!==e||e.includes(`|`)||s(e))throw o(t,`bad_characters`);return e}function l(e,t){if(typeof e!=`string`)throw o(t,`not_a_string`);if(e.trim()===``)throw o(t,`empty`);return e}function u(e,t){if(typeof e!=`string`)throw o(t,`not_a_string`);return e}const d=/^[1-9][0-9]{0,37}$/u;function f(e,t){if(typeof e!=`string`||!d.test(e))throw o(t,`not_a_positive_whole_number`);return e}function p(e,t){let r=f(e,t);if(new n(r).isGreaterThan(1e3))throw o(t,`above_mint_limit`);return r}function m(e){return{collection:c(e.collection,`collection`),category:c(e.category,`category`),type:c(e.type,`type`),additionalKey:c(e.additionalKey??`none`,`additionalKey`)}}function h(e){if(!Array.isArray(e)||e.length===0)throw o(`authorities`,`bad_authorities`);return e.map((e,n)=>t(e,`authorities[${n}]`))}const g=/^(?:0x)?(?:(?:02|03)[0-9a-fA-F]{64}|04[0-9a-fA-F]{128})$/u;function _(e){if(typeof e!=`string`||!g.test(e))throw o(`callerPublicKey`,`bad_public_key`);return e}function v(e,t,n){return{collection:e,authorizedUser:t,uniqueKey:n}}function y(e,t,n){return{...e,name:t.name,symbol:t.symbol,description:t.description,image:t.image,maxSupply:t.maxSupply,...t.maxCapacity===void 0?{}:{maxCapacity:t.maxCapacity},...t.metadataAddress===void 0?{}:{metadataAddress:t.metadataAddress},...t.contractAddress===void 0?{}:{contractAddress:t.contractAddress},...t.rarity===void 0?{}:{rarity:t.rarity},...t.authorities===void 0?{}:{authorities:[...t.authorities]},uniqueKey:n}}function b(e,t,n,r,i){return{tokenClass:t,owner:n,...e===`MintTokenWithAllowance`?{tokenInstance:`0`}:{},quantity:r,uniqueKey:i}}function x(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function S(t,n,r){return new e(`GATEWAY_RESPONSE_INVALID`,{method:t},{body:r,uniqueKey:n})}function C(e,t){return e.collection===t.collection&&e.category===t.category&&e.type===t.type&&e.additionalKey===t.additionalKey}function w(e,t){let n=e.data,r=x(n)?n.authorizedUsers:void 0;if(!x(n)||n.collection!==t||!Array.isArray(r)||r.length===0||!r.every(e=>typeof e==`string`))throw S(e.method,e.uniqueKey,e.body);return{...e,collection:t,authorizedUsers:r}}function T(e,t){let n=e.data;if(!x(n)||!C(n,t))throw S(e.method,e.uniqueKey,e.body);return{...e,tokenClass:{...t}}}const E=/^[0-9]+$/u;function D(e,t,n){let r=e.data,i=[];if(Array.isArray(r))for(let e of r){let n=x(e)?e.instance:void 0;if(!x(e)||!C(e,t)||typeof n!=`string`||!E.test(n))break;i.push({...t,instance:n})}if(!Array.isArray(r)||i.length!==r.length||i.length!==Number(n)||new Set(i.map(e=>e.instance)).size!==i.length)throw S(e.method,e.uniqueKey,e.body);return{...e,tokenInstances:i}}export{a as NFT_DEFAULT_ADDITIONAL_KEY,i as NFT_MINT_LIMIT,r as NFT_WRITE_METHODS,v as claimNftCollectionDto,w as claimedCollection,y as createNftCollectionDto,T as createdTokenClass,b as mintNftDto,D as mintedInstances,h as nftAuthorities,_ as nftCallerPublicKey,c as nftClassPart,p as nftMintQuantity,u as nftString,l as nftText,m as nftTokenClass,f as nftWholeNumber};
|
|
2
|
+
//# sourceMappingURL=nft.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nft.js","names":["BigNumber","NFT_WRITE_METHODS","NFT_MINT_LIMIT","NFT_DEFAULT_ADDITIONAL_KEY","refuse","GalaSDKError","hasControlCharacter","index","value","code","nftClassPart","field","nftText","nftString","WHOLE_NUMBER","nftWholeNumber","nftMintQuantity","quantity","nftTokenClass","input","nftAuthorities","galaChainUserRef","authority","PUBLIC_KEY","nftCallerPublicKey","claimNftCollectionDto","createNftCollectionDto","tokenClass","fields","mintNftDto","method","isRecord","unreadable","sameClass","\"collection\"","\"category\"","\"type\"","\"additionalKey\"","claimedCollection","data","receipt","users","\"authorizedUsers\"","collection","user","createdTokenClass","INSTANCE_ID","mintedInstances","instances","item","instance","\"instance\"","key"],"sources":["../../../src/writes/nft.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { GalaSDKError, type GalaErrorContext } from '../classes/gala_sdk_error.js';\nimport type { InvalidNftInputReason } from '../classes/error_catalog.js';\nimport type { GalaChainTokenClassKey } from '../types/token.js';\nimport { galaChainUserRef } from './identity.js';\nimport type { GalaChainTokenInstanceKey, WriteKeyInput, WriteReceipt } from './types.js';\n\n/**\n * The NFT methods of GalaChain's token contract that `GatewayWrites` signs and submits, as a closed\n * set: claim a collection name (`GrantNftCollectionAuthorization`), create the NFT collection's\n * token class (`CreateNftCollection`), mint NFTs, granting the minter its own mint allowance in\n * the same transaction (`MintTokenWithAllowance`) or against an allowance it already holds\n * (`MintToken`).\n */\nexport const NFT_WRITE_METHODS = [\n 'GrantNftCollectionAuthorization',\n 'CreateNftCollection',\n 'MintTokenWithAllowance',\n 'MintToken',\n] as const;\n\n/** One member of {@link NFT_WRITE_METHODS}. */\nexport type NftWriteMethod = (typeof NFT_WRITE_METHODS)[number];\n\n/** The most NFTs one mint may create (the chain's `MintTokenDto.MAX_NFT_MINT_SIZE`). */\nexport const NFT_MINT_LIMIT = 1000;\n\n/** The `additionalKey` an NFT token class carries when its creator names none (GalaChain's `none`). */\nexport const NFT_DEFAULT_ADDITIONAL_KEY = 'none';\n\n/** The four parts of the NFT token class a write names; `additionalKey` defaults to `none`. */\nexport interface NftTokenClassInput {\n /** The NFT collection name (the one claimed with `claimNftCollection`). */\n collection: string;\n /** The category of the token class. */\n category: string;\n /** The type of the token class. */\n type: string;\n /** The additional key of the token class; default `none`. */\n additionalKey?: string | undefined;\n}\n\n/** `claimNftCollection`: authorize a user to create token classes under a collection name. */\nexport interface ClaimNftCollectionInput extends WriteKeyInput {\n /** The collection name to claim. The chain refuses a name that is taken (case-insensitively). */\n collection: string;\n /**\n * Who is authorized to create the collection: a user reference in any of the forms of\n * `TransferGalaInput.to`; default the writer. The chain stores the authorization under the\n * account the reference names (an `eth|` reference becomes that account's `client|` alias).\n */\n authorizedUser?: string | undefined;\n}\n\n/** `createNftCollection`: create the token class of an NFT collection the writer is authorized for. */\nexport interface CreateNftCollectionInput extends NftTokenClassInput, WriteKeyInput {\n /** The token class's name. */\n name: string;\n /** The token class's symbol (a string; it may be empty). */\n symbol: string;\n /** The token class's description. */\n description: string;\n /** The token class's image URL. */\n image: string;\n /**\n * The most NFTs that may ever exist, a positive whole number as a decimal string. Required: the\n * chain refuses an NFT class whose supply is unbounded (\"maxSupply must be finite\").\n */\n maxSupply: string;\n /** The most NFTs that may be held at once, a positive whole number as a decimal string. */\n maxCapacity?: string | undefined;\n /** An optional metadata address. */\n metadataAddress?: string | undefined;\n /** An optional contract address. */\n contractAddress?: string | undefined;\n /** An optional rarity label. */\n rarity?: string | undefined;\n /**\n * The token authorities, as user references. Default (when omitted): the writer. They are the\n * accounts that may mint; naming others without the writer makes the writer unable to mint.\n */\n authorities?: readonly string[] | undefined;\n}\n\n/** `mintNft`: mint NFTs of a token class the writer is a token authority of. */\nexport interface MintNftInput extends NftTokenClassInput, WriteKeyInput {\n /** How many NFTs to mint, a whole number from 1 to {@link NFT_MINT_LIMIT} as a decimal string. */\n quantity: string;\n /** Who receives them: a user reference; default the writer. */\n owner?: string | undefined;\n /**\n * `false` (default): `MintTokenWithAllowance`, which grants the writer its own mint allowance in\n * the same transaction. `true`: `MintToken`, which spends a mint allowance the writer already\n * holds and is refused (`INSUFFICIENT_MINT_ALLOWANCE`) without one.\n */\n existingAllowance?: boolean | undefined;\n}\n\n/** What a claim returned: the collection and every account now authorized for it. */\nexport type ClaimNftCollectionReceipt = WriteReceipt<'GrantNftCollectionAuthorization'> & {\n readonly collection: string;\n readonly authorizedUsers: readonly string[];\n};\n\n/** What a create returned: the token class it created. */\nexport type CreateNftCollectionReceipt = WriteReceipt<'CreateNftCollection'> & {\n readonly tokenClass: Readonly<GalaChainTokenClassKey>;\n};\n\n/** What a mint returned: the NFT instances it created, in the chain's order. */\nexport type MintNftReceipt = WriteReceipt<'MintTokenWithAllowance' | 'MintToken'> & {\n readonly tokenInstances: readonly GalaChainTokenInstanceKey[];\n};\n\nfunction refuse(field: string, reason: InvalidNftInputReason): GalaSDKError {\n return new GalaSDKError('INVALID_NFT_INPUT', { field, reason });\n}\n\n/** True when `value` holds an ASCII or C1 control character (the NUL of chain composite keys among them). */\nfunction hasControlCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) return true;\n }\n return false;\n}\n\n/**\n * One part of a token class key (collection, category, type, additionalKey): a non-empty string\n * with no control character (the chain's composite keys are NUL-separated), no `|` (the key's own\n * separator) and no surrounding whitespace. Returned exactly as written, never trimmed.\n *\n * @throws GalaSDKError `INVALID_NFT_INPUT`.\n */\nexport function nftClassPart(value: unknown, field: string): string {\n if (typeof value !== 'string') throw refuse(field, 'not_a_string');\n if (value.trim() === '') throw refuse(field, 'empty');\n if (value.trim() !== value || value.includes('|') || hasControlCharacter(value)) {\n throw refuse(field, 'bad_characters');\n }\n return value;\n}\n\n/** A non-empty free-text field (name, description, image, ...), exactly as written. */\nexport function nftText(value: unknown, field: string): string {\n if (typeof value !== 'string') throw refuse(field, 'not_a_string');\n if (value.trim() === '') throw refuse(field, 'empty');\n return value;\n}\n\n/** A string that may be empty (the symbol). */\nexport function nftString(value: unknown, field: string): string {\n if (typeof value !== 'string') throw refuse(field, 'not_a_string');\n return value;\n}\n\nconst WHOLE_NUMBER = /^[1-9][0-9]{0,37}$/u;\n\n/**\n * A positive whole number written as a decimal string (no sign, fraction, exponent, separators or\n * leading zero), returned as written. A JS number is refused: the chain receives strings.\n */\nexport function nftWholeNumber(value: unknown, field: string): string {\n if (typeof value !== 'string' || !WHOLE_NUMBER.test(value)) {\n throw refuse(field, 'not_a_positive_whole_number');\n }\n return value;\n}\n\n/** The quantity of a mint: a positive whole number of at most {@link NFT_MINT_LIMIT}. */\nexport function nftMintQuantity(value: unknown, field: string): string {\n const quantity = nftWholeNumber(value, field);\n if (new BigNumber(quantity).isGreaterThan(NFT_MINT_LIMIT)) {\n throw refuse(field, 'above_mint_limit');\n }\n return quantity;\n}\n\n/** The token class a write names, every part checked; `additionalKey` defaults to `none`. */\nexport function nftTokenClass(input: NftTokenClassInput): GalaChainTokenClassKey {\n return {\n collection: nftClassPart(input.collection, 'collection'),\n category: nftClassPart(input.category, 'category'),\n type: nftClassPart(input.type, 'type'),\n additionalKey: nftClassPart(input.additionalKey ?? NFT_DEFAULT_ADDITIONAL_KEY, 'additionalKey'),\n };\n}\n\n/** The authorities of a create: one or more user references, each in its one gateway spelling. */\nexport function nftAuthorities(value: unknown): string[] {\n if (!Array.isArray(value) || value.length === 0) throw refuse('authorities', 'bad_authorities');\n return (value as unknown[]).map((authority, index) =>\n galaChainUserRef(authority, `authorities[${index}]`),\n );\n}\n\nconst PUBLIC_KEY = /^(?:0x)?(?:(?:02|03)[0-9a-fA-F]{64}|04[0-9a-fA-F]{128})$/u;\n\n/**\n * The public key a DryRun simulates the caller as: a secp256k1 key in hex, compressed (33 bytes) or\n * uncompressed (65 bytes), with or without `0x`. The chain refuses a DryRun that names no caller.\n */\nexport function nftCallerPublicKey(value: unknown): string {\n if (typeof value !== 'string' || !PUBLIC_KEY.test(value)) {\n throw refuse('callerPublicKey', 'bad_public_key');\n }\n return value;\n}\n\n/** The unsigned `GrantNftCollectionAuthorization` DTO. */\nexport function claimNftCollectionDto(\n collection: string,\n authorizedUser: string,\n uniqueKey: string,\n): Record<string, unknown> {\n return { collection, authorizedUser, uniqueKey };\n}\n\n/** The checked fields of a create. */\nexport interface CreateNftCollectionFields {\n readonly name: string;\n readonly symbol: string;\n readonly description: string;\n readonly image: string;\n readonly maxSupply: string;\n readonly maxCapacity: string | undefined;\n readonly metadataAddress: string | undefined;\n readonly contractAddress: string | undefined;\n readonly rarity: string | undefined;\n readonly authorities: readonly string[] | undefined;\n}\n\n/** The unsigned `CreateNftCollection` DTO: the fields the caller gave, none the caller left out. */\nexport function createNftCollectionDto(\n tokenClass: GalaChainTokenClassKey,\n fields: CreateNftCollectionFields,\n uniqueKey: string,\n): Record<string, unknown> {\n return {\n ...tokenClass,\n name: fields.name,\n symbol: fields.symbol,\n description: fields.description,\n image: fields.image,\n maxSupply: fields.maxSupply,\n ...(fields.maxCapacity === undefined ? {} : { maxCapacity: fields.maxCapacity }),\n ...(fields.metadataAddress === undefined ? {} : { metadataAddress: fields.metadataAddress }),\n ...(fields.contractAddress === undefined ? {} : { contractAddress: fields.contractAddress }),\n ...(fields.rarity === undefined ? {} : { rarity: fields.rarity }),\n ...(fields.authorities === undefined ? {} : { authorities: [...fields.authorities] }),\n uniqueKey,\n };\n}\n\n/**\n * The unsigned mint DTO. `MintTokenWithAllowance` names instance `\"0\"` (the allowance it grants\n * itself covers the class's mint, not one NFT); `MintToken` carries no instance.\n */\nexport function mintNftDto(\n method: 'MintTokenWithAllowance' | 'MintToken',\n tokenClass: GalaChainTokenClassKey,\n owner: string,\n quantity: string,\n uniqueKey: string,\n): Record<string, unknown> {\n return {\n tokenClass,\n owner,\n ...(method === 'MintTokenWithAllowance' ? { tokenInstance: '0' } : {}),\n quantity,\n uniqueKey,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** The error for a write GalaChain accepted whose answer does not say what the write did. */\nfunction unreadable(\n method: NftWriteMethod,\n uniqueKey: string,\n body: unknown,\n): GalaSDKError<'GATEWAY_RESPONSE_INVALID'> {\n const context: GalaErrorContext = { body, uniqueKey };\n return new GalaSDKError('GATEWAY_RESPONSE_INVALID', { method }, context);\n}\n\nfunction sameClass(value: Record<string, unknown>, tokenClass: GalaChainTokenClassKey): boolean {\n return (\n value['collection'] === tokenClass.collection &&\n value['category'] === tokenClass.category &&\n value['type'] === tokenClass.type &&\n value['additionalKey'] === tokenClass.additionalKey\n );\n}\n\n/**\n * The collection and authorized users a claim answered. Fails closed: an answer for another\n * collection, or one that authorizes nobody, is not the claim that was sent.\n */\nexport function claimedCollection(\n receipt: WriteReceipt<'GrantNftCollectionAuthorization'>,\n collection: string,\n): ClaimNftCollectionReceipt {\n const data = receipt.data;\n const users = isRecord(data) ? data['authorizedUsers'] : undefined;\n if (\n !isRecord(data) ||\n data['collection'] !== collection ||\n !Array.isArray(users) ||\n users.length === 0 ||\n !users.every((user): user is string => typeof user === 'string')\n ) {\n throw unreadable(receipt.method, receipt.uniqueKey, receipt.body);\n }\n return { ...receipt, collection, authorizedUsers: users };\n}\n\n/** The token class a create answered; an answer naming another class is not the create that was sent. */\nexport function createdTokenClass(\n receipt: WriteReceipt<'CreateNftCollection'>,\n tokenClass: GalaChainTokenClassKey,\n): CreateNftCollectionReceipt {\n const data = receipt.data;\n if (!isRecord(data) || !sameClass(data, tokenClass)) {\n throw unreadable(receipt.method, receipt.uniqueKey, receipt.body);\n }\n return { ...receipt, tokenClass: { ...tokenClass } };\n}\n\nconst INSTANCE_ID = /^[0-9]+$/u;\n\n/**\n * The NFT instances a mint answered, never synthesized: as many as were asked for, each of the\n * class that was named, each with a whole-number instance, none twice.\n */\nexport function mintedInstances(\n receipt: WriteReceipt<'MintTokenWithAllowance' | 'MintToken'>,\n tokenClass: GalaChainTokenClassKey,\n quantity: string,\n): MintNftReceipt {\n const data = receipt.data;\n const instances: GalaChainTokenInstanceKey[] = [];\n if (Array.isArray(data)) {\n for (const item of data as unknown[]) {\n const instance = isRecord(item) ? item['instance'] : undefined;\n if (!isRecord(item) || !sameClass(item, tokenClass) || typeof instance !== 'string') break;\n if (!INSTANCE_ID.test(instance)) break;\n instances.push({ ...tokenClass, instance });\n }\n }\n if (\n !Array.isArray(data) ||\n instances.length !== data.length ||\n instances.length !== Number(quantity) ||\n new Set(instances.map((key) => key.instance)).size !== instances.length\n ) {\n throw unreadable(receipt.method, receipt.uniqueKey, receipt.body);\n }\n return { ...receipt, tokenInstances: instances };\n}\n"],"mappings":"A,yIAcA,MAAaC,EAAoB,CAC/B,kCACA,sBACA,yBACA,WACF,EAMaC,EAAiB,IAGjBC,EAA6B,OAsF1C,SAASC,EAAO,EAAe,EAA6C,CAC1E,OAAO,IAAIC,EAAa,oBAAqB,CAAE,QAAO,QAAO,CAAC,CAChE,CAGA,SAASC,EAAoB,EAAwB,CACnD,IAAK,IAAIC,EAAQ,EAAGA,EAAQC,EAAM,OAAQ,GAAS,EAAG,CACpD,IAAMC,EAAOD,EAAM,WAAWD,CAAK,EACnC,GAAIE,GAAQ,IAASA,GAAQ,KAAQA,GAAQ,IAAO,MAAO,EAC7D,CACA,MAAO,EACT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Aa,UACvE,CAACJ,EAAY,KAAKI,CAAQ,EAAG,MACjCF,EAAU,KAAK,CAAE,GAAGrB,EAAY,UAAS,CAAC,CAC5C,CAEF,GACE,CAAC,MAAM,QAAQY,CAAI,GACnBS,EAAU,SAAWT,EAAK,QAC1BS,EAAU,SAAW,OAAO/B,CAAQ,GACpC,IAAI,IAAI+B,EAAU,IAAK,GAAQI,EAAI,QAAQ,CAAC,CAAC,CAAC,OAASJ,EAAU,OAEjE,MAAMhB,EAAWQ,EAAQ,OAAQA,EAAQ,UAAWA,EAAQ,IAAI,EAElE,MAAO,CAAE,GAAGA,EAAS,eAAgBQ,CAAU,CACjD,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{GalaSDKError as e}from"../classes/gala_sdk_error.js";import{buildRequestHeaders as t,readResponseBody as n,requestWithTimeout as r}from"../utils/transport.js";import{createUniqueKey as i}from"../utils/unique_key.js";import{dataOf as a}from"../reads/request.js";import{signedPayload as o}from"./submit.js";import s from"bignumber.js";function c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function l(e,t){let n=e[t];return typeof n==`string`?n:``}function u(t,n,r){let i=()=>new e(`GATEWAY_READ_RESPONSE_INVALID`,{method:`DryRun`},{...r,body:n});if(!c(n)||!c(n.response)||!c(n.writes))throw i();let a=n.response;if(a.Status!==1)throw new e(`GATEWAY_READ_REJECTED`,{method:`DryRun`,chainStatus:typeof a.Status==`number`?a.Status:0,errorKey:l(a,`ErrorKey`),serverMessage:l(a,`Message`)},{...r,body:a});let o=[],u=[];for(let[e,t]of Object.entries(n.writes)){let n=e.startsWith(`\0GCUR\0`)?o:e.startsWith(`\0GCFR\0`)?u:void 0;if(n===void 0)continue;let r;try{r=typeof t==`string`?JSON.parse(t):void 0}catch{throw i()}let a=c(r)?r.quantity:void 0,l=c(r)?r.feeCode:void 0;if(typeof a!=`string`||typeof l!=`string`)throw i();let d=new s(a);if(!d.isFinite()||d.isNegative())throw i();n.push({feeCode:l,quantity:a})}let d=o.length>0?o:u;return{method:t,fee:d.reduce((e,t)=>e.plus(t.quantity),new s(0)).toFixed(),feeToken:`GALA`,receipts:d}}async function d(s,c,l,d,f){let p=await o(s.signer,`DryRun`,{callerPublicKey:l,method:d,dto:f,uniqueKey:i(c)}),m=`${s.gatewayBaseUrl}/api/asset/token-contract/DryRun`,h=await r(s.requestor,m,{method:`POST`,headers:t(s.wire,{json:!0}),body:p},s.timeoutMs,{write:!1}),g;try{g=await n(h)}catch(t){throw new e(`TRANSPORT_ERROR`,{url:m},{url:m,cause:t,write:!1})}return u(d,a(`DryRun`,m,h,g),{status:h.status,url:m,write:!1})}export{u as feeQuoteOf,d as quoteNftFee};
|
|
2
|
+
//# sourceMappingURL=nft_fee.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nft_fee.js","names":["BigNumber","isRecord","value","stringField","record","key","feeQuoteOf","invalid","GalaSDKError","context","data","\"response\"","\"writes\"","response","\"Status\"","user","channel","target","receipt","quantity","\"quantity\"","feeCode","\"feeCode\"","amount","receipts","sum","quoteNftFee","payload","signedPayload","transport","createUniqueKey","uniqueKeyPrefix","url","requestWithTimeout","buildRequestHeaders","answer","readResponseBody","cause","method","dataOf"],"sources":["../../../src/writes/nft_fee.ts"],"sourcesContent":["import BigNumber from 'bignumber.js';\nimport { GalaSDKError, type GalaErrorContext } from '../classes/gala_sdk_error.js';\nimport { dataOf } from '../reads/request.js';\nimport { buildRequestHeaders, readResponseBody, requestWithTimeout } from '../utils/transport.js';\nimport { createUniqueKey } from '../utils/unique_key.js';\nimport type { NftWriteMethod } from './nft.js';\nimport { signedPayload, type WriteTransport } from './submit.js';\n\n/** The contract every NFT write, and the DryRun that prices it, is sent to. */\nconst TOKEN_CONTRACT = 'asset/token-contract';\n\n/** The key prefix of the chain's fee receipts: the channel's (`GCFR`) and the paying user's (`GCUR`). */\nconst CHANNEL_RECEIPT = '\\u0000GCFR\\u0000';\nconst USER_RECEIPT = '\\u0000GCUR\\u0000';\n\n/** One fee the simulated write would pay. */\nexport interface NftFeeReceipt {\n /** The chain's fee code (`NftCollectionAuthorization`, `CreateNftCollection`, ...). */\n readonly feeCode: string;\n /** The fee in whole GALA, a decimal string. */\n readonly quantity: string;\n}\n\n/** What GalaChain's DryRun says a write would cost. */\nexport interface NftFeeQuote {\n /** The method that was simulated. */\n readonly method: NftWriteMethod;\n /** The network fee in GALA, a decimal string; `\"0\"` only when the chain wrote no fee receipt. */\n readonly fee: string;\n /** The fee token: always GALA. */\n readonly feeToken: 'GALA';\n /** The fees the fee is the sum of, as the chain simulated them. */\n readonly receipts: readonly NftFeeReceipt[];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: Record<string, unknown>, key: string): string {\n const value = record[key];\n return typeof value === 'string' ? value : '';\n}\n\n/**\n * Reads a simulated write's fee from its DryRun `Data`. The simulated write must have SUCCEEDED\n * (`response.Status` 1): a write the chain would refuse still writes its fee receipt in the\n * simulation, and quoting that as the price of a write that will not happen would be a lie, so a\n * refusal (`PAYMENT_REQUIRED`, `INSUFFICIENT_MINT_ALLOWANCE`, ...) is `GATEWAY_READ_REJECTED`.\n *\n * The fee is what the paying user's receipts (`GCUR`) add up to; the channel receipt (`GCFR`) the\n * chain writes beside each is the same payment seen from the channel, so it is counted only when\n * no user receipt exists. No receipt at all is a fee of `\"0\"`: the write is free.\n *\n * @throws GalaSDKError `GATEWAY_READ_REJECTED` (the simulated write failed), `GATEWAY_READ_RESPONSE_INVALID`\n * (an answer that is not a DryRun result, or a receipt with no readable quantity).\n */\nexport function feeQuoteOf(\n method: NftWriteMethod,\n data: unknown,\n context: GalaErrorContext,\n): NftFeeQuote {\n const invalid = (): GalaSDKError<'GATEWAY_READ_RESPONSE_INVALID'> =>\n new GalaSDKError(\n 'GATEWAY_READ_RESPONSE_INVALID',\n { method: 'DryRun' },\n { ...context, body: data },\n );\n if (!isRecord(data) || !isRecord(data['response']) || !isRecord(data['writes'])) throw invalid();\n const response = data['response'];\n if (response['Status'] !== 1) {\n throw new GalaSDKError(\n 'GATEWAY_READ_REJECTED',\n {\n method: 'DryRun',\n chainStatus: typeof response['Status'] === 'number' ? response['Status'] : 0,\n errorKey: stringField(response, 'ErrorKey'),\n serverMessage: stringField(response, 'Message'),\n },\n { ...context, body: response },\n );\n }\n const user: NftFeeReceipt[] = [];\n const channel: NftFeeReceipt[] = [];\n for (const [key, value] of Object.entries(data['writes'])) {\n const target = key.startsWith(USER_RECEIPT)\n ? user\n : key.startsWith(CHANNEL_RECEIPT)\n ? channel\n : undefined;\n if (target === undefined) continue;\n let receipt: unknown;\n try {\n receipt = typeof value === 'string' ? (JSON.parse(value) as unknown) : undefined;\n } catch {\n throw invalid();\n }\n const quantity = isRecord(receipt) ? receipt['quantity'] : undefined;\n const feeCode = isRecord(receipt) ? receipt['feeCode'] : undefined;\n if (typeof quantity !== 'string' || typeof feeCode !== 'string') throw invalid();\n const amount = new BigNumber(quantity);\n if (!amount.isFinite() || amount.isNegative()) throw invalid();\n target.push({ feeCode, quantity });\n }\n const receipts = user.length > 0 ? user : channel;\n const fee = receipts.reduce((sum, receipt) => sum.plus(receipt.quantity), new BigNumber(0));\n return { method, fee: fee.toFixed(), feeToken: 'GALA', receipts };\n}\n\n/**\n * Prices `dto` as `method` with the gateway's DryRun: a signed wrapper\n * `{ callerPublicKey, method, dto, uniqueKey }` (the inner DTO travels unsigned, as an object, with\n * no `dtoOperation`: a DryRun runs it inside the wrapper, which is what is signed for `DryRun`)\n * and nothing is written to the chain. A DryRun changes nothing, so every failure of it is a\n * READ's (`write: false`) and a retry is safe.\n *\n * @throws GalaSDKError the signer's pre-send `SIGNING_FAILED`; `REQUEST_TIMEOUT` / `TRANSPORT_ERROR`\n * (`write: false`); `GATEWAY_HTTP_ERROR`; `GATEWAY_READ_REJECTED`; `GATEWAY_READ_RESPONSE_INVALID`.\n */\nexport async function quoteNftFee(\n transport: WriteTransport,\n uniqueKeyPrefix: string,\n callerPublicKey: string,\n method: NftWriteMethod,\n dto: Record<string, unknown>,\n): Promise<NftFeeQuote> {\n const payload = await signedPayload(transport.signer, 'DryRun', {\n callerPublicKey,\n method,\n dto,\n uniqueKey: createUniqueKey(uniqueKeyPrefix),\n });\n const url = `${transport.gatewayBaseUrl}/api/${TOKEN_CONTRACT}/DryRun`;\n const response = await requestWithTimeout(\n transport.requestor,\n url,\n {\n method: 'POST',\n headers: buildRequestHeaders(transport.wire, { json: true }),\n body: payload,\n },\n transport.timeoutMs,\n { write: false },\n );\n let answer: unknown;\n try {\n answer = await readResponseBody(response);\n } catch (cause: unknown) {\n throw new GalaSDKError('TRANSPORT_ERROR', { url }, { url, cause, write: false });\n }\n const data = dataOf('DryRun', url, response, answer);\n return feeQuoteOf(method, data, { status: response.status, url, write: false });\n}\n"],"mappings":"A,oVAmCA,SAASC,EAAS,EAAkD,CAClE,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,CAEA,SAASC,EAAY,EAAiC,EAAqB,CACzE,IAAMD,EAAQE,EAAOC,GACrB,OAAO,OAAOH,GAAU,SAAWA,EAAQ,EAC7C,CAeA,SAAgBI,EACd,EACA,EACA,EACa,CACb,IAAMC,MACJ,IAAIC,EACF,gCACA,CAAE,OAAQ,QAAS,EACnB,CAAE,GAAGC,EAAS,KAAMC,CAAK,CAC3B,EACF,GAAI,CAACT,EAASS,CAAI,GAAK,CAACT,EAASS,EAAKC,QAAW,GAAK,CAACV,EAASS,EAAKE,MAAS,EAAG,MAAML,EAAQ,EAC/F,IAAMM,EAAWH,EAAKC,SACtB,GAAIE,EAASC,SAAc,EACzB,MAAM,IAAIN,EACR,wBACA,CACE,OAAQ,SACR,YAAa,OAAOK,EAASC,QAAc,SAAWD,EAASC,OAAY,EAC3E,SAAUX,EAAYU,EAAU,UAAU,EAC1C,cAAeV,EAAYU,EAAU,SAAS,CAChD,EACA,CAAE,GAAGJ,EAAS,KAAM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AAM,EAAK,CAAC,EAC3D,KAAMF,CACR,EACAE,EAAU,UACV,CAAE,MAAO,EAAM,CACjB,EACIM,EACJ,GAAI,CACF,EAAS,MAAMC,EAAiBvB,CAAQ,CAC1C,OAASwB,EAAgB,CACvB,MAAM,IAAI7B,EAAa,kBAAmB,CAAE,KAAI,EAAG,CAAE,MAAK,QAAO,MAAO,EAAM,CAAC,CACjF,CAEA,OAAOF,EAAWgC,EADLC,EAAO,SAAUP,EAAKnB,EAAUsB,CAChB,EAAG,CAAE,OAAQtB,EAAS,OAAQ,MAAK,MAAO,EAAM,CAAC,CAChF,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{GalaSDKError as e,isGalaError as t}from"../classes/gala_sdk_error.js";import{serialize as n}from"../utils/signing.js";import{withDtoOperation as r}from"../utils/dto_operation.js";import{signPreSendFor as i}from"../utils/pre_send.js";import{buildRequestHeaders as a,readBlockNumberHeader as o,readHeader as s,readResponseBody as c,requestWithTimeout as l}from"../utils/transport.js";const
|
|
1
|
+
import{GalaSDKError as e,isGalaError as t}from"../classes/gala_sdk_error.js";import{serialize as n}from"../utils/signing.js";import{withDtoOperation as r}from"../utils/dto_operation.js";import{signPreSendFor as i}from"../utils/pre_send.js";import{buildRequestHeaders as a,readBlockNumberHeader as o,readHeader as s,readResponseBody as c,requestWithTimeout as l}from"../utils/transport.js";import{chainErrorOf as u}from"../reads/request.js";const d=`asset/token-contract`,f=/* @__PURE__ */ new Set([`signature`,`prefix`,`types`,`domain`]);function p(e,t){if(typeof t.signature!=`string`)return!1;let r=Object.fromEntries(Object.entries(t).filter(([e])=>!f.has(e)));return n(r)===e}async function m(t,a,o){let s=r(d,a,o),c=n(s),l=await i(t,d,a,s),u;try{u=p(c,l)?JSON.stringify(l):void 0}catch(t){throw new e(`SIGNING_FAILED`,{method:a,reason:`failed`},{cause:t})}if(u===void 0)throw new e(`SIGNING_FAILED`,{method:a,reason:`failed`});return u}async function h(n,r,i,o,s){let u=(t,n)=>new e(`GATEWAY_WRITE_OUTCOME_UNKNOWN`,{method:r,reason:t},{url:i,uniqueKey:s,cause:n}),d;try{d=await l(n.requestor,i,{method:`POST`,headers:a(n.wire,{json:!0}),body:o},n.timeoutMs)}catch(e){throw t(e,`REQUEST_TIMEOUT`)?u(`timeout`,e):t(e,`TRANSPORT_ERROR`)?u(`transport`,e):e}try{return{response:d,body:await c(d)}}catch(e){throw u(`transport`,e)}}function g(e){if(typeof e!=`string`)return;let t=e.trim();return t===``?void 0:t}function _(e,t){let n=e?.[t];return typeof n==`string`?n:``}function v(t,n,r,i,a){let c={status:i.status,body:a,url:r,uniqueKey:n},l=typeof a==`object`&&a&&!Array.isArray(a)?a:void 0,d=l?.Status,f=u(a),p=f?.Status;if(typeof p==`number`&&p!==1)throw new e(`GATEWAY_WRITE_REJECTED`,{method:t,chainStatus:p,errorKey:_(f,`ErrorKey`),serverMessage:_(f,`Message`)},c);if(!i.ok)throw new e(`GATEWAY_HTTP_ERROR`,{method:t,status:i.status,serverMessage:_(l,`Message`)||_(l,`message`)},c);let m=g(s(i,`x-transaction-id`))??g(l?.transactionId);if(l===void 0||!(d===1||d===void 0&&m!==void 0))throw new e(`GATEWAY_RESPONSE_INVALID`,{method:t},c);return{method:t,uniqueKey:n,transactionId:m,blockNumber:o(i),data:l.Data,body:a}}async function y(e,t,n,r){let i=await m(e.signer,t,n),a=`${e.gatewayBaseUrl}/api/${d}/${t}`,{response:o,body:s}=await h(e,t,a,i,r);return v(t,r,a,o,s)}export{m as signedPayload,y as submitWrite};
|
|
2
2
|
//# sourceMappingURL=submit.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"submit.js","names":["TOKEN_CONTRACT","SIGNATURE_ENVELOPE","carriesExactlyTheDto","signed","\"signature\"","withoutEnvelope","key","serialize","builtDto","signedPayload","operated","withDtoOperation","method","dto","signPreSendFor","signer","payload","cause","GalaSDKError","post","outcomeUnknown","response","requestWithTimeout","transport","url","buildRequestHeaders","error","isGalaError","readResponseBody","nonEmptyString","value","trimmed","stringField","record","receiptOf","context","envelope","body","chainStatus","\"Status\"","transactionId","readHeader","\"transactionId\"","readBlockNumberHeader","\"Data\"","submitWrite","uniqueKey"],"sources":["../../../src/writes/submit.ts"],"sourcesContent":["import { GalaSDKError, isGalaError, type GalaErrorContext } from '../classes/gala_sdk_error.js';\nimport type { GalaChainSigner } from '../classes/signers.js';\nimport type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { withDtoOperation } from '../utils/dto_operation.js';\nimport { signPreSendFor } from '../utils/pre_send.js';\nimport { serialize } from '../utils/signing.js';\nimport {\n buildRequestHeaders,\n readBlockNumberHeader,\n readHeader,\n readResponseBody,\n requestWithTimeout,\n} from '../utils/transport.js';\nimport type { GatewayWriteMethod, GatewayWriteReceipt } from './types.js';\n\n/** The contract every write of this module is sent to (its URL path and its `dtoOperation`). */\nconst TOKEN_CONTRACT = 'asset/token-contract';\n\n/** What every write is sent with. */\nexport interface WriteTransport {\n readonly gatewayBaseUrl: string;\n readonly signer: GalaChainSigner;\n readonly requestor: HttpRequestor;\n readonly timeoutMs: number;\n readonly wire: WireOptions | undefined;\n}\n\n/**\n * The fields a signer may add next to the DTO: the signature and, for the wallet schemes, the\n * personal-sign `prefix` and the EIP-712 `types` / `domain`. Nothing else: a signer that inserts a\n * signer hint (`signerAddress`, `signerPublicKey`) would make the chain attribute the write to\n * whoever that names (the phantom-signer class), so such a body is never sent.\n */\nconst SIGNATURE_ENVELOPE = new Set(['signature', 'prefix', 'types', 'domain']);\n\n/**\n * True when `signed` is the DTO the SDK built plus signature-envelope fields only: without the\n * envelope it serializes (the chain's own serialization) exactly as the DTO did BEFORE it was\n * handed to the signer, so a field the signer added, dropped or changed (also by mutating the\n * object it was handed) is caught; and its signature is a string.\n */\nfunction carriesExactlyTheDto(builtDto: string, signed: Record<string, unknown>): boolean {\n if (typeof signed['signature'] !== 'string') return false;\n const withoutEnvelope = Object.fromEntries(\n Object.entries(signed).filter(([key]) => !SIGNATURE_ENVELOPE.has(key)),\n );\n return serialize(withoutEnvelope) === builtDto;\n}\n\n/**\n * Signs `dto` and serializes the body to send, all before anything leaves: a signer failure, a\n * signer that changed the DTO or added a field to it, and a body that cannot be serialized are all\n * `SIGNING_FAILED` (pre-send: nothing was transmitted, a retry is safe).\n */\nasync function signedPayload(\n signer: GalaChainSigner,\n method: GatewayWriteMethod,\n dto: Record<string, unknown>,\n): Promise<string> {\n // Taken before the signer sees the DTO: what it hands back is compared with this, not with an\n // object it could have mutated.\n const operated = withDtoOperation(TOKEN_CONTRACT, method, dto);\n const builtDto = serialize(operated);\n const signed = await signPreSendFor(signer, TOKEN_CONTRACT, method, operated);\n let payload: string | undefined;\n try {\n payload = carriesExactlyTheDto(builtDto, signed) ? JSON.stringify(signed) : undefined;\n } catch (cause: unknown) {\n // A value JSON cannot carry (a BigInt, a cycle) in what the signer returned.\n throw new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' }, { cause });\n }\n if (payload === undefined) {\n throw new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' });\n }\n return payload;\n}\n\n/**\n * POSTs the signed body. Neither a timeout nor a transport failure proves the write was not\n * applied, so both are `GATEWAY_WRITE_OUTCOME_UNKNOWN` carrying the write's `uniqueKey` (the only\n * handle to check it with), never a retryable read failure. Any other rejection is the app's\n * requestor's own and reaches the caller unchanged.\n */\nasync function post(\n transport: WriteTransport,\n method: GatewayWriteMethod,\n url: string,\n payload: string,\n uniqueKey: string,\n): Promise<{ response: HTTPResponse; body: unknown }> {\n const outcomeUnknown = (\n reason: 'timeout' | 'transport',\n cause: unknown,\n ): GalaSDKError<'GATEWAY_WRITE_OUTCOME_UNKNOWN'> =>\n new GalaSDKError(\n 'GATEWAY_WRITE_OUTCOME_UNKNOWN',\n { method, reason },\n { url, uniqueKey, cause },\n );\n let response: HTTPResponse;\n try {\n response = await requestWithTimeout(\n transport.requestor,\n url,\n {\n method: 'POST',\n headers: buildRequestHeaders(transport.wire, { json: true }),\n body: payload,\n },\n transport.timeoutMs,\n );\n } catch (error: unknown) {\n if (isGalaError(error, 'REQUEST_TIMEOUT')) throw outcomeUnknown('timeout', error);\n if (isGalaError(error, 'TRANSPORT_ERROR')) throw outcomeUnknown('transport', error);\n throw error;\n }\n try {\n return { response, body: await readResponseBody(response) };\n } catch (cause: unknown) {\n // The answer's headers arrived and its body broke off: what the gateway did is unknown.\n throw outcomeUnknown('transport', cause);\n }\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const trimmed = value.trim();\n return trimmed === '' ? undefined : trimmed;\n}\n\nfunction stringField(record: Record<string, unknown> | undefined, key: string): string {\n const value = record?.[key];\n return typeof value === 'string' ? value : '';\n}\n\n/**\n * Reads the gateway's answer to a write. GalaChain's `Status` is checked BEFORE any transaction id\n * is trusted (a proxy can set `x-transaction-id` whatever the chain did):\n *\n * - a numeric `Status` other than 1, in any HTTP status: `GATEWAY_WRITE_REJECTED` (the chain refused);\n * - any other non-2xx: `GATEWAY_HTTP_ERROR`;\n * - a 2xx that is not a JSON object, has a non-numeric `Status`, or has no `Status` AND names no\n * transaction id: `GATEWAY_RESPONSE_INVALID` (it proves nothing; the write may have been applied);\n * - `Status: 1`, or no `Status` with a transaction id: the receipt.\n *\n * Every error carries the HTTP status, the body, the URL and the write's `uniqueKey`.\n */\nfunction receiptOf(\n method: GatewayWriteMethod,\n uniqueKey: string,\n url: string,\n response: HTTPResponse,\n body: unknown,\n): GatewayWriteReceipt {\n const context: GalaErrorContext = { status: response.status, body, url, uniqueKey };\n const envelope =\n typeof body === 'object' && body !== null && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : undefined;\n const chainStatus = envelope?.['Status'];\n if (typeof chainStatus === 'number' && chainStatus !== 1) {\n throw new GalaSDKError(\n 'GATEWAY_WRITE_REJECTED',\n {\n method,\n chainStatus,\n errorKey: stringField(envelope, 'ErrorKey'),\n serverMessage: stringField(envelope, 'Message'),\n },\n context,\n );\n }\n if (!response.ok) {\n throw new GalaSDKError(\n 'GATEWAY_HTTP_ERROR',\n {\n method,\n status: response.status,\n serverMessage: stringField(envelope, 'Message') || stringField(envelope, 'message'),\n },\n context,\n );\n }\n const transactionId =\n nonEmptyString(readHeader(response, 'x-transaction-id')) ??\n nonEmptyString(envelope?.['transactionId']);\n const accepted = chainStatus === 1 || (chainStatus === undefined && transactionId !== undefined);\n if (envelope === undefined || !accepted) {\n throw new GalaSDKError('GATEWAY_RESPONSE_INVALID', { method }, context);\n }\n return {\n method,\n uniqueKey,\n transactionId,\n blockNumber: readBlockNumberHeader(response),\n data: envelope['Data'],\n body,\n };\n}\n\n/**\n * Signs `dto` for `method`, POSTs it to `<gatewayBaseUrl>/api/asset/token-contract/<method>` and\n * reads the answer (see {@link receiptOf}). The body sent is exactly what the signer returned: the\n * DTO plus its signature (and, for a wallet scheme, `prefix` / `types` / `domain`).\n */\nexport async function submitWrite(\n transport: WriteTransport,\n method: GatewayWriteMethod,\n dto: Record<string, unknown>,\n uniqueKey: string,\n): Promise<GatewayWriteReceipt> {\n const payload = await signedPayload(transport.signer, method, dto);\n const url = `${transport.gatewayBaseUrl}/api/${TOKEN_CONTRACT}/${method}`;\n const { response, body } = await post(transport, method, url, payload, uniqueKey);\n return receiptOf(method, uniqueKey, url, response, body);\n}\n"],"mappings":"A,qYAiBA,MAAMA,EAAiB,uBAiBjBC,kBAAqB,IAAI,IAAI,CAAC,YAAa,SAAU,QAAS,QAAQ,CAAC,EAQ7E,SAASC,EAAqB,EAAkB,EAA0C,CACxF,GAAI,OAAOC,EAAOC,WAAiB,SAAU,MAAO,GACpD,IAAMC,EAAkB,OAAO,YAC7B,OAAO,QAAQF,CAAM,CAAC,CAAC,QAAQ,CAACG,KAAS,CAACL,EAAmB,IAAIK,CAAG,CAAC,CACvE,EACA,OAAOC,EAAUF,CAAe,IAAMG,CACxC,CAOA,eAAeC,EACb,EACA,EACA,EACiB,CAGjB,IAAMC,E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"file":"submit.js","names":["TOKEN_CONTRACT","SIGNATURE_ENVELOPE","carriesExactlyTheDto","signed","\"signature\"","withoutEnvelope","key","serialize","builtDto","signedPayload","operated","withDtoOperation","method","dto","signPreSendFor","signer","payload","cause","GalaSDKError","post","outcomeUnknown","response","requestWithTimeout","transport","url","buildRequestHeaders","error","isGalaError","readResponseBody","nonEmptyString","value","trimmed","stringField","record","receiptOf","context","envelope","body","chainStatus","\"Status\"","refusal","chainErrorOf","refusalStatus","transactionId","readHeader","\"transactionId\"","readBlockNumberHeader","\"Data\"","submitWrite","uniqueKey"],"sources":["../../../src/writes/submit.ts"],"sourcesContent":["import { GalaSDKError, isGalaError, type GalaErrorContext } from '../classes/gala_sdk_error.js';\nimport type { GalaChainSigner } from '../classes/signers.js';\nimport type { HTTPResponse, HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport { chainErrorOf } from '../reads/request.js';\nimport { withDtoOperation } from '../utils/dto_operation.js';\nimport { signPreSendFor } from '../utils/pre_send.js';\nimport { serialize } from '../utils/signing.js';\nimport {\n buildRequestHeaders,\n readBlockNumberHeader,\n readHeader,\n readResponseBody,\n requestWithTimeout,\n} from '../utils/transport.js';\nimport type { WriteReceipt } from './types.js';\n\n/** The contract every write of this module is sent to (its URL path and its `dtoOperation`). */\nconst TOKEN_CONTRACT = 'asset/token-contract';\n\n/** What every write is sent with. */\nexport interface WriteTransport {\n readonly gatewayBaseUrl: string;\n readonly signer: GalaChainSigner;\n readonly requestor: HttpRequestor;\n readonly timeoutMs: number;\n readonly wire: WireOptions | undefined;\n}\n\n/**\n * The fields a signer may add next to the DTO: the signature and, for the wallet schemes, the\n * personal-sign `prefix` and the EIP-712 `types` / `domain`. Nothing else: a signer that inserts a\n * signer hint (`signerAddress`, `signerPublicKey`) would make the chain attribute the write to\n * whoever that names (the phantom-signer class), so such a body is never sent.\n */\nconst SIGNATURE_ENVELOPE = new Set(['signature', 'prefix', 'types', 'domain']);\n\n/**\n * True when `signed` is the DTO the SDK built plus signature-envelope fields only: without the\n * envelope it serializes (the chain's own serialization) exactly as the DTO did BEFORE it was\n * handed to the signer, so a field the signer added, dropped or changed (also by mutating the\n * object it was handed) is caught; and its signature is a string.\n */\nfunction carriesExactlyTheDto(builtDto: string, signed: Record<string, unknown>): boolean {\n if (typeof signed['signature'] !== 'string') return false;\n const withoutEnvelope = Object.fromEntries(\n Object.entries(signed).filter(([key]) => !SIGNATURE_ENVELOPE.has(key)),\n );\n return serialize(withoutEnvelope) === builtDto;\n}\n\n/**\n * Signs `dto` and serializes the body to send, all before anything leaves: a signer failure, a\n * signer that changed the DTO or added a field to it, and a body that cannot be serialized are all\n * `SIGNING_FAILED` (pre-send: nothing was transmitted, a retry is safe).\n */\nexport async function signedPayload(\n signer: GalaChainSigner,\n method: string,\n dto: Record<string, unknown>,\n): Promise<string> {\n // Taken before the signer sees the DTO: what it hands back is compared with this, not with an\n // object it could have mutated.\n const operated = withDtoOperation(TOKEN_CONTRACT, method, dto);\n const builtDto = serialize(operated);\n const signed = await signPreSendFor(signer, TOKEN_CONTRACT, method, operated);\n let payload: string | undefined;\n try {\n payload = carriesExactlyTheDto(builtDto, signed) ? JSON.stringify(signed) : undefined;\n } catch (cause: unknown) {\n // A value JSON cannot carry (a BigInt, a cycle) in what the signer returned.\n throw new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' }, { cause });\n }\n if (payload === undefined) {\n throw new GalaSDKError('SIGNING_FAILED', { method, reason: 'failed' });\n }\n return payload;\n}\n\n/**\n * POSTs the signed body. Neither a timeout nor a transport failure proves the write was not\n * applied, so both are `GATEWAY_WRITE_OUTCOME_UNKNOWN` carrying the write's `uniqueKey` (the only\n * handle to check it with), never a retryable read failure. Any other rejection is the app's\n * requestor's own and reaches the caller unchanged.\n */\nasync function post(\n transport: WriteTransport,\n method: string,\n url: string,\n payload: string,\n uniqueKey: string,\n): Promise<{ response: HTTPResponse; body: unknown }> {\n const outcomeUnknown = (\n reason: 'timeout' | 'transport',\n cause: unknown,\n ): GalaSDKError<'GATEWAY_WRITE_OUTCOME_UNKNOWN'> =>\n new GalaSDKError(\n 'GATEWAY_WRITE_OUTCOME_UNKNOWN',\n { method, reason },\n { url, uniqueKey, cause },\n );\n let response: HTTPResponse;\n try {\n response = await requestWithTimeout(\n transport.requestor,\n url,\n {\n method: 'POST',\n headers: buildRequestHeaders(transport.wire, { json: true }),\n body: payload,\n },\n transport.timeoutMs,\n );\n } catch (error: unknown) {\n if (isGalaError(error, 'REQUEST_TIMEOUT')) throw outcomeUnknown('timeout', error);\n if (isGalaError(error, 'TRANSPORT_ERROR')) throw outcomeUnknown('transport', error);\n throw error;\n }\n try {\n return { response, body: await readResponseBody(response) };\n } catch (cause: unknown) {\n // The answer's headers arrived and its body broke off: what the gateway did is unknown.\n throw outcomeUnknown('transport', cause);\n }\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const trimmed = value.trim();\n return trimmed === '' ? undefined : trimmed;\n}\n\nfunction stringField(record: Record<string, unknown> | undefined, key: string): string {\n const value = record?.[key];\n return typeof value === 'string' ? value : '';\n}\n\n/**\n * Reads the gateway's answer to a write. GalaChain's `Status` is checked BEFORE any transaction id\n * is trusted (a proxy can set `x-transaction-id` whatever the chain did):\n *\n * - a numeric `Status` other than 1, in any HTTP status: `GATEWAY_WRITE_REJECTED` (the chain refused);\n * - any other non-2xx: `GATEWAY_HTTP_ERROR`;\n * - a 2xx that is not a JSON object, has a non-numeric `Status`, or has no `Status` AND names no\n * transaction id: `GATEWAY_RESPONSE_INVALID` (it proves nothing; the write may have been applied);\n * - `Status: 1`, or no `Status` with a transaction id: the receipt.\n *\n * Every error carries the HTTP status, the body, the URL and the write's `uniqueKey`.\n */\nfunction receiptOf<M extends string>(\n method: M,\n uniqueKey: string,\n url: string,\n response: HTTPResponse,\n body: unknown,\n): WriteReceipt<M> {\n const context: GalaErrorContext = { status: response.status, body, url, uniqueKey };\n const envelope =\n typeof body === 'object' && body !== null && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : undefined;\n const chainStatus = envelope?.['Status'];\n // The chain's refusal: at the top of the answer, or nested under `error` (the gateway answers a\n // refused write HTTP 4xx as `{ error: { Status: 0, ErrorKey, Message, ... } }`, recorded on stage).\n const refusal = chainErrorOf(body);\n const refusalStatus = refusal?.['Status'];\n if (typeof refusalStatus === 'number' && refusalStatus !== 1) {\n throw new GalaSDKError(\n 'GATEWAY_WRITE_REJECTED',\n {\n method,\n chainStatus: refusalStatus,\n errorKey: stringField(refusal, 'ErrorKey'),\n serverMessage: stringField(refusal, 'Message'),\n },\n context,\n );\n }\n if (!response.ok) {\n throw new GalaSDKError(\n 'GATEWAY_HTTP_ERROR',\n {\n method,\n status: response.status,\n serverMessage: stringField(envelope, 'Message') || stringField(envelope, 'message'),\n },\n context,\n );\n }\n const transactionId =\n nonEmptyString(readHeader(response, 'x-transaction-id')) ??\n nonEmptyString(envelope?.['transactionId']);\n const accepted = chainStatus === 1 || (chainStatus === undefined && transactionId !== undefined);\n if (envelope === undefined || !accepted) {\n throw new GalaSDKError('GATEWAY_RESPONSE_INVALID', { method }, context);\n }\n return {\n method,\n uniqueKey,\n transactionId,\n blockNumber: readBlockNumberHeader(response),\n data: envelope['Data'],\n body,\n };\n}\n\n/**\n * Signs `dto` for `method`, POSTs it to `<gatewayBaseUrl>/api/asset/token-contract/<method>` and\n * reads the answer (see {@link receiptOf}). The body sent is exactly what the signer returned: the\n * DTO plus its signature (and, for a wallet scheme, `prefix` / `types` / `domain`).\n */\nexport async function submitWrite<M extends string>(\n transport: WriteTransport,\n method: M,\n dto: Record<string, unknown>,\n uniqueKey: string,\n): Promise<WriteReceipt<M>> {\n const payload = await signedPayload(transport.signer, method, dto);\n const url = `${transport.gatewayBaseUrl}/api/${TOKEN_CONTRACT}/${method}`;\n const { response, body } = await post(transport, method, url, payload, uniqueKey);\n return receiptOf(method, uniqueKey, url, response, body);\n}\n"],"mappings":"A,wbAkBA,MAAMA,E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GiB,CAAO,EAExE,MAAO,CACL,SACA,YACA,gBACA,YAAaW,EAAsBzB,CAAQ,EAC3C,KAAMe,EAASW,KACf,MACF,CACF,CAOA,eAAsBC,EACpB,EACA,EACA,EACA,EAC0B,CAC1B,IAAMhC,EAAU,MAAMP,EAAcc,EAAU,OAAQX,EAAQC,CAAG,EAC3DW,EAAM,GAAGD,EAAU,eAAe,OAAOvB,EAAe,GAAGY,IAC3D,CAAE,WAAU,QAAS,MAAMO,EAAKI,EAAWX,EAAQY,EAAKR,EAASiC,CAAS,EAChF,OAAOf,EAAUtB,EAAQqC,EAAWzB,EAAKH,EAAUgB,CAAI,CACzD,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). It is signed exactly as written: never scaled to base units, never re-formatted\n * (`\"1.50\"` stays `\"1.50\"`).\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/** `transferGala`: GALA (`GALA|Unit|none|none`, instance `\"0\"`) to a recipient. */\nexport interface TransferGalaInput extends WriteKeyInput {\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 {\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
|
|
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). It is signed exactly as written: never scaled to base units, never re-formatted\n * (`\"1.50\"` stays `\"1.50\"`).\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/** `transferGala`: GALA (`GALA|Unit|none|none`, instance `\"0\"`) to a recipient. */\nexport interface TransferGalaInput extends WriteKeyInput {\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 {\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"}
|