@mysten/payment-kit 0.1.10 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { normalizeSuiAddress } from "@mysten/sui/utils";
1
+ import { normalizeStructTag, normalizeSuiAddress } from "@mysten/sui/utils";
2
2
  import { BcsEnum, BcsStruct, BcsTuple, TypeTagSerializer, bcs } from "@mysten/sui/bcs";
3
3
  import { isArgument } from "@mysten/sui/transactions";
4
4
 
@@ -84,7 +84,73 @@ function normalizeMoveArguments(args, argTypes, parameterNames) {
84
84
  }
85
85
  return normalizedArgs;
86
86
  }
87
+ const HAS_PHANTOM_REGEX = /phantom [A-Za-z_$][A-Za-z0-9_$]*/;
88
+ function splitTopLevelTypeArgs(inner) {
89
+ const parts = [];
90
+ let depth = 0;
91
+ let current = "";
92
+ for (const char of inner) {
93
+ if (char === "," && depth === 0) {
94
+ parts.push(current.trim());
95
+ current = "";
96
+ continue;
97
+ }
98
+ if (char === "<") depth++;
99
+ if (char === ">") depth--;
100
+ current += char;
101
+ }
102
+ if (current) parts.push(current.trim());
103
+ return parts;
104
+ }
105
+ function buildTypeTag(name, options) {
106
+ const lt = name.indexOf("<");
107
+ const base = lt === -1 ? name : name.slice(0, lt);
108
+ if (base.split("::").length !== 3) throw new Error(`${name} is not a top-level Move type`);
109
+ let result = name;
110
+ if (options?.typeArguments) {
111
+ const baked = lt === -1 ? [] : splitTopLevelTypeArgs(name.slice(lt + 1, -1));
112
+ const supplied = options.typeArguments.map((arg) => {
113
+ if (typeof arg === "string") return arg;
114
+ if (arg && typeof arg.serialize === "function" && typeof arg.name === "string") return arg.name;
115
+ throw new Error(`Invalid type argument ${stringify(arg)}`);
116
+ });
117
+ if (supplied.length !== baked.length) throw new Error(`Expected ${baked.length} type arguments for ${base}, got ${supplied.length}`);
118
+ result = supplied.length === 0 ? base : `${base}<${supplied.join(", ")}>`;
119
+ }
120
+ if (HAS_PHANTOM_REGEX.test(result)) throw new Error(options?.typeArguments ? `A type argument contains an unfilled phantom parameter in ${result}` : `Missing type arguments for ${result}`);
121
+ if (options?.package) {
122
+ const [, ...rest] = result.split("::");
123
+ result = [options.package, ...rest].join("::");
124
+ }
125
+ if (!HAS_PHANTOM_REGEX.test(result) && !/[@/]/.test(result)) TypeTagSerializer.parseFromStr(result);
126
+ return result;
127
+ }
128
+ async function resolveBuiltTypeTag(name, options) {
129
+ const { client, ...rest } = options;
130
+ const { type } = await client.core.mvr.resolveType({ type: buildTypeTag(name, rest) });
131
+ return normalizeStructTag(type);
132
+ }
87
133
  var MoveStruct = class extends BcsStruct {
134
+ /**
135
+ * Build the type tag for this struct.
136
+ *
137
+ * `typeArguments` is the full positional list, in Move declaration order, and
138
+ * is required when the struct has unfilled phantom parameters. The result may
139
+ * contain MVR names: those are valid in transaction `typeArguments`, but for
140
+ * queries or comparisons against on-chain data use `resolveTypeTag` instead.
141
+ */
142
+ typeTag(...args) {
143
+ return buildTypeTag(this.name, args[0]);
144
+ }
145
+ /**
146
+ * Build the type tag for this struct, then resolve any MVR names through the
147
+ * client (using its configured overrides and the MVR API) and return the
148
+ * normalized, address-only form suitable for queries and comparisons against
149
+ * on-chain data.
150
+ */
151
+ async resolveTypeTag(options) {
152
+ return resolveBuiltTypeTag(this.name, options);
153
+ }
88
154
  async get({ objectId, ...options }) {
89
155
  const [res] = await this.getMany({
90
156
  ...options,
@@ -109,10 +175,28 @@ var MoveStruct = class extends BcsStruct {
109
175
  });
110
176
  }
111
177
  };
112
- var MoveEnum = class extends BcsEnum {};
113
- var MoveTuple = class extends BcsTuple {};
178
+ var MoveEnum = class extends BcsEnum {
179
+ /** Build the type tag for this enum. See `MoveStruct.typeTag` for semantics. */
180
+ typeTag(...args) {
181
+ return buildTypeTag(this.name, args[0]);
182
+ }
183
+ /** Build and resolve the type tag for this enum. See `MoveStruct.resolveTypeTag`. */
184
+ async resolveTypeTag(options) {
185
+ return resolveBuiltTypeTag(this.name, options);
186
+ }
187
+ };
188
+ var MoveTuple = class extends BcsTuple {
189
+ /** Build the type tag for this struct. See `MoveStruct.typeTag` for semantics. */
190
+ typeTag(...args) {
191
+ return buildTypeTag(this.name, args[0]);
192
+ }
193
+ /** Build and resolve the type tag for this struct. See `MoveStruct.resolveTypeTag`. */
194
+ async resolveTypeTag(options) {
195
+ return resolveBuiltTypeTag(this.name, options);
196
+ }
197
+ };
114
198
  function stringify(val) {
115
- if (typeof val === "object") return JSON.stringify(val, (val$1) => val$1);
199
+ if (typeof val === "object") return JSON.stringify(val, (_key, value) => typeof value === "bigint" ? value.toString() : value);
116
200
  if (typeof val === "bigint") return val.toString();
117
201
  return val;
118
202
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["val"],"sources":["../../../src/contracts/utils/index.ts"],"sourcesContent":["import {\n\tbcs,\n\ttype BcsType,\n\ttype TypeTag,\n\tTypeTagSerializer,\n\tBcsStruct,\n\tBcsEnum,\n\tBcsTuple,\n} from '@mysten/sui/bcs';\nimport { normalizeSuiAddress } from '@mysten/sui/utils';\nimport { type TransactionArgument, isArgument } from '@mysten/sui/transactions';\nimport { type ClientWithCoreApi, type SuiClientTypes } from '@mysten/sui/client';\n\nconst MOVE_STDLIB_ADDRESS = normalizeSuiAddress('0x1');\nconst SUI_FRAMEWORK_ADDRESS = normalizeSuiAddress('0x2');\n\nexport type RawTransactionArgument<T> = T | TransactionArgument;\n\nexport type GetOptions<Include extends Omit<SuiClientTypes.ObjectInclude, 'content'> = {}> =\n\tSuiClientTypes.GetObjectOptions<Include> & { client: ClientWithCoreApi };\n\nexport type GetManyOptions<Include extends Omit<SuiClientTypes.ObjectInclude, 'content'> = {}> =\n\tSuiClientTypes.GetObjectsOptions<Include> & { client: ClientWithCoreApi };\n\nexport function getPureBcsSchema(typeTag: string | TypeTag): BcsType<any> | null {\n\tconst parsedTag = typeof typeTag === 'string' ? TypeTagSerializer.parseFromStr(typeTag) : typeTag;\n\n\tif ('u8' in parsedTag) {\n\t\treturn bcs.U8;\n\t} else if ('u16' in parsedTag) {\n\t\treturn bcs.U16;\n\t} else if ('u32' in parsedTag) {\n\t\treturn bcs.U32;\n\t} else if ('u64' in parsedTag) {\n\t\treturn bcs.U64;\n\t} else if ('u128' in parsedTag) {\n\t\treturn bcs.U128;\n\t} else if ('u256' in parsedTag) {\n\t\treturn bcs.U256;\n\t} else if ('address' in parsedTag) {\n\t\treturn bcs.Address;\n\t} else if ('bool' in parsedTag) {\n\t\treturn bcs.Bool;\n\t} else if ('vector' in parsedTag) {\n\t\tconst type = getPureBcsSchema(parsedTag.vector);\n\t\treturn type ? bcs.vector(type) : null;\n\t} else if ('struct' in parsedTag) {\n\t\tconst structTag = parsedTag.struct;\n\t\tconst pkg = normalizeSuiAddress(structTag.address);\n\n\t\tif (pkg === MOVE_STDLIB_ADDRESS) {\n\t\t\tif (\n\t\t\t\t(structTag.module === 'ascii' || structTag.module === 'string') &&\n\t\t\t\tstructTag.name === 'String'\n\t\t\t) {\n\t\t\t\treturn bcs.String;\n\t\t\t}\n\n\t\t\tif (structTag.module === 'option' && structTag.name === 'Option') {\n\t\t\t\tconst inner = structTag.typeParams[0];\n\t\t\t\tconst type = inner ? getPureBcsSchema(inner) : null;\n\t\t\t\treturn type ? bcs.option(type) : null;\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\tpkg === SUI_FRAMEWORK_ADDRESS &&\n\t\t\tstructTag.module === 'object' &&\n\t\t\t(structTag.name === 'ID' || structTag.name === 'UID')\n\t\t) {\n\t\t\treturn bcs.Address;\n\t\t}\n\t}\n\n\treturn null;\n}\n\nexport function normalizeMoveArguments(\n\targs: unknown[] | object,\n\targTypes: readonly (string | null)[],\n\tparameterNames?: string[],\n) {\n\tconst argLen = Array.isArray(args) ? args.length : Object.keys(args).length;\n\tif (parameterNames && argLen !== parameterNames.length) {\n\t\tthrow new Error(\n\t\t\t`Invalid number of arguments, expected ${parameterNames.length}, got ${argLen}`,\n\t\t);\n\t}\n\n\tconst normalizedArgs: TransactionArgument[] = [];\n\n\tlet index = 0;\n\tfor (const argType of argTypes) {\n\t\tif (argType === '0x2::clock::Clock') {\n\t\t\tnormalizedArgs.push((tx) => tx.object.clock());\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (argType === '0x2::random::Random') {\n\t\t\tnormalizedArgs.push((tx) => tx.object.random());\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (argType === '0x2::deny_list::DenyList') {\n\t\t\tnormalizedArgs.push((tx) => tx.object.denyList());\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (argType === '0x3::sui_system::SuiSystemState') {\n\t\t\tnormalizedArgs.push((tx) => tx.object.system());\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet arg;\n\t\tif (Array.isArray(args)) {\n\t\t\tif (index >= args.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid number of arguments, expected at least ${index + 1}, got ${args.length}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\targ = args[index];\n\t\t} else {\n\t\t\tif (!parameterNames) {\n\t\t\t\tthrow new Error(`Expected arguments to be passed as an array`);\n\t\t\t}\n\t\t\tconst name = parameterNames[index];\n\t\t\targ = args[name as keyof typeof args];\n\n\t\t\tif (arg === undefined) {\n\t\t\t\tthrow new Error(`Parameter ${name} is required`);\n\t\t\t}\n\t\t}\n\n\t\tindex += 1;\n\n\t\tif (typeof arg === 'function' || isArgument(arg)) {\n\t\t\tnormalizedArgs.push(arg as TransactionArgument);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst bcsType = argType === null ? null : getPureBcsSchema(argType);\n\n\t\tif (bcsType) {\n\t\t\tconst bytes = bcsType.serialize(arg as never);\n\t\t\tnormalizedArgs.push((tx) => tx.pure(bytes));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (typeof arg === 'string') {\n\t\t\tnormalizedArgs.push((tx) => tx.object(arg));\n\t\t\tcontinue;\n\t\t}\n\n\t\tthrow new Error(`Invalid argument ${stringify(arg)} for type ${argType}`);\n\t}\n\n\treturn normalizedArgs;\n}\n\nexport class MoveStruct<\n\tT extends Record<string, BcsType<any>>,\n\tconst Name extends string = string,\n> extends BcsStruct<T, Name> {\n\tasync get<Include extends Omit<SuiClientTypes.ObjectInclude, 'content' | 'json'> = {}>({\n\t\tobjectId,\n\t\t...options\n\t}: GetOptions<Include>): Promise<\n\t\tSuiClientTypes.Object<Include & { content: true; json: true }> & {\n\t\t\tjson: BcsStruct<T>['$inferType'];\n\t\t}\n\t> {\n\t\tconst [res] = await this.getMany<Include>({\n\t\t\t...options,\n\t\t\tobjectIds: [objectId],\n\t\t});\n\n\t\tif (!res) {\n\t\t\tthrow new Error(`No object found for id ${objectId}`);\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tasync getMany<Include extends Omit<SuiClientTypes.ObjectInclude, 'content' | 'json'> = {}>({\n\t\tclient,\n\t\t...options\n\t}: GetManyOptions<Include>): Promise<\n\t\tArray<\n\t\t\tSuiClientTypes.Object<Include & { content: true; json: true }> & {\n\t\t\t\tjson: BcsStruct<T>['$inferType'];\n\t\t\t}\n\t\t>\n\t> {\n\t\tconst response = (await client.core.getObjects({\n\t\t\t...options,\n\t\t\tinclude: {\n\t\t\t\t...options.include,\n\t\t\t\tcontent: true,\n\t\t\t},\n\t\t})) as SuiClientTypes.GetObjectsResponse<Include & { content: true }>;\n\n\t\treturn response.objects.map((obj) => {\n\t\t\tif (obj instanceof Error) {\n\t\t\t\tthrow obj;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\t...obj,\n\t\t\t\tjson: this.parse(obj.content),\n\t\t\t};\n\t\t});\n\t}\n}\n\nexport class MoveEnum<\n\tT extends Record<string, BcsType<any> | null>,\n\tconst Name extends string,\n> extends BcsEnum<T, Name> {}\n\nexport class MoveTuple<\n\tconst T extends readonly BcsType<any>[],\n\tconst Name extends string,\n> extends BcsTuple<T, Name> {}\n\nfunction stringify(val: unknown) {\n\tif (typeof val === 'object') {\n\t\treturn JSON.stringify(val, (val: unknown) => val);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,IAAiF,EACtF,UACA,GAAG,WAKF;EACD,MAAM,CAAC,OAAO,MAAM,KAAK,QAAiB;GACzC,GAAG;GACH,WAAW,CAAC,SAAS;GACrB,CAAC;AAEF,MAAI,CAAC,IACJ,OAAM,IAAI,MAAM,0BAA0B,WAAW;AAGtD,SAAO;;CAGR,MAAM,QAAqF,EAC1F,QACA,GAAG,WAOF;AASD,UARkB,MAAM,OAAO,KAAK,WAAW;GAC9C,GAAG;GACH,SAAS;IACR,GAAG,QAAQ;IACX,SAAS;IACT;GACD,CAAC,EAEc,QAAQ,KAAK,QAAQ;AACpC,OAAI,eAAe,MAClB,OAAM;AAGP,UAAO;IACN,GAAG;IACH,MAAM,KAAK,MAAM,IAAI,QAAQ;IAC7B;IACA;;;AAIJ,IAAa,WAAb,cAGU,QAAiB;AAE3B,IAAa,YAAb,cAGU,SAAkB;AAE5B,SAAS,UAAU,KAAc;AAChC,KAAI,OAAO,QAAQ,SAClB,QAAO,KAAK,UAAU,MAAM,UAAiBA,MAAI;AAElD,KAAI,OAAO,QAAQ,SAClB,QAAO,IAAI,UAAU;AAGtB,QAAO"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/contracts/utils/index.ts"],"sourcesContent":["import {\n\tbcs,\n\ttype BcsType,\n\ttype TypeTag,\n\tTypeTagSerializer,\n\tBcsStruct,\n\tBcsEnum,\n\tBcsTuple,\n} from '@mysten/sui/bcs';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui/utils';\nimport { type TransactionArgument, isArgument } from '@mysten/sui/transactions';\nimport { type ClientWithCoreApi, type SuiClientTypes } from '@mysten/sui/client';\n\nconst MOVE_STDLIB_ADDRESS = normalizeSuiAddress('0x1');\nconst SUI_FRAMEWORK_ADDRESS = normalizeSuiAddress('0x2');\n\nexport type RawTransactionArgument<T> = T | TransactionArgument;\n\nexport type GetOptions<Include extends Omit<SuiClientTypes.ObjectInclude, 'content'> = {}> =\n\tSuiClientTypes.GetObjectOptions<Include> & { client: ClientWithCoreApi };\n\nexport type GetManyOptions<Include extends Omit<SuiClientTypes.ObjectInclude, 'content'> = {}> =\n\tSuiClientTypes.GetObjectsOptions<Include> & { client: ClientWithCoreApi };\n\nexport function getPureBcsSchema(typeTag: string | TypeTag): BcsType<any> | null {\n\tconst parsedTag = typeof typeTag === 'string' ? TypeTagSerializer.parseFromStr(typeTag) : typeTag;\n\n\tif ('u8' in parsedTag) {\n\t\treturn bcs.U8;\n\t} else if ('u16' in parsedTag) {\n\t\treturn bcs.U16;\n\t} else if ('u32' in parsedTag) {\n\t\treturn bcs.U32;\n\t} else if ('u64' in parsedTag) {\n\t\treturn bcs.U64;\n\t} else if ('u128' in parsedTag) {\n\t\treturn bcs.U128;\n\t} else if ('u256' in parsedTag) {\n\t\treturn bcs.U256;\n\t} else if ('address' in parsedTag) {\n\t\treturn bcs.Address;\n\t} else if ('bool' in parsedTag) {\n\t\treturn bcs.Bool;\n\t} else if ('vector' in parsedTag) {\n\t\tconst type = getPureBcsSchema(parsedTag.vector);\n\t\treturn type ? bcs.vector(type) : null;\n\t} else if ('struct' in parsedTag) {\n\t\tconst structTag = parsedTag.struct;\n\t\tconst pkg = normalizeSuiAddress(structTag.address);\n\n\t\tif (pkg === MOVE_STDLIB_ADDRESS) {\n\t\t\tif (\n\t\t\t\t(structTag.module === 'ascii' || structTag.module === 'string') &&\n\t\t\t\tstructTag.name === 'String'\n\t\t\t) {\n\t\t\t\treturn bcs.String;\n\t\t\t}\n\n\t\t\tif (structTag.module === 'option' && structTag.name === 'Option') {\n\t\t\t\tconst inner = structTag.typeParams[0];\n\t\t\t\tconst type = inner ? getPureBcsSchema(inner) : null;\n\t\t\t\treturn type ? bcs.option(type) : null;\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\tpkg === SUI_FRAMEWORK_ADDRESS &&\n\t\t\tstructTag.module === 'object' &&\n\t\t\t(structTag.name === 'ID' || structTag.name === 'UID')\n\t\t) {\n\t\t\treturn bcs.Address;\n\t\t}\n\t}\n\n\treturn null;\n}\n\nexport function normalizeMoveArguments(\n\targs: unknown[] | object,\n\targTypes: readonly (string | null)[],\n\tparameterNames?: string[],\n) {\n\tconst argLen = Array.isArray(args) ? args.length : Object.keys(args).length;\n\tif (parameterNames && argLen !== parameterNames.length) {\n\t\tthrow new Error(\n\t\t\t`Invalid number of arguments, expected ${parameterNames.length}, got ${argLen}`,\n\t\t);\n\t}\n\n\tconst normalizedArgs: TransactionArgument[] = [];\n\n\tlet index = 0;\n\tfor (const argType of argTypes) {\n\t\tif (argType === '0x2::clock::Clock') {\n\t\t\tnormalizedArgs.push((tx) => tx.object.clock());\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (argType === '0x2::random::Random') {\n\t\t\tnormalizedArgs.push((tx) => tx.object.random());\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (argType === '0x2::deny_list::DenyList') {\n\t\t\tnormalizedArgs.push((tx) => tx.object.denyList());\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (argType === '0x3::sui_system::SuiSystemState') {\n\t\t\tnormalizedArgs.push((tx) => tx.object.system());\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet arg;\n\t\tif (Array.isArray(args)) {\n\t\t\tif (index >= args.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid number of arguments, expected at least ${index + 1}, got ${args.length}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\targ = args[index];\n\t\t} else {\n\t\t\tif (!parameterNames) {\n\t\t\t\tthrow new Error(`Expected arguments to be passed as an array`);\n\t\t\t}\n\t\t\tconst name = parameterNames[index];\n\t\t\targ = args[name as keyof typeof args];\n\n\t\t\tif (arg === undefined) {\n\t\t\t\tthrow new Error(`Parameter ${name} is required`);\n\t\t\t}\n\t\t}\n\n\t\tindex += 1;\n\n\t\tif (typeof arg === 'function' || isArgument(arg)) {\n\t\t\tnormalizedArgs.push(arg as TransactionArgument);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst bcsType = argType === null ? null : getPureBcsSchema(argType);\n\n\t\tif (bcsType) {\n\t\t\tconst bytes = bcsType.serialize(arg as never);\n\t\t\tnormalizedArgs.push((tx) => tx.pure(bytes));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (typeof arg === 'string') {\n\t\t\tnormalizedArgs.push((tx) => tx.object(arg));\n\t\t\tcontinue;\n\t\t}\n\n\t\tthrow new Error(`Invalid argument ${stringify(arg)} for type ${argType}`);\n\t}\n\n\treturn normalizedArgs;\n}\n\n/* -------------------------- Move type tags -------------------------- */\n\n/** A type argument: a type tag string, or a BCS type whose name is a Move type. */\nexport type TypeArgument = string | BcsType<any>;\n\nexport interface TypeTagOptions {\n\tpackage?: string;\n\ttypeArguments?: readonly TypeArgument[];\n}\n\n/**\n * `typeArguments` is required when the type's name contains unfilled\n * `phantom X` parameters (at any depth). Everything else — argument arity,\n * position contents, and tag validity — is validated at runtime.\n */\ntype TypeTagParams<Name extends string> = Name extends `${string}phantom ${string}`\n\t? [options: TypeTagOptions & { typeArguments: readonly TypeArgument[] }]\n\t: [options?: TypeTagOptions];\n\ntype ResolveTypeTagOptions<Name extends string> = {\n\tclient: ClientWithCoreApi;\n} & (Name extends `${string}phantom ${string}`\n\t? TypeTagOptions & { typeArguments: readonly TypeArgument[] }\n\t: TypeTagOptions);\n\nconst HAS_PHANTOM_REGEX = /phantom [A-Za-z_$][A-Za-z0-9_$]*/;\n\nfunction splitTopLevelTypeArgs(inner: string): string[] {\n\tconst parts: string[] = [];\n\tlet depth = 0;\n\tlet current = '';\n\tfor (const char of inner) {\n\t\tif (char === ',' && depth === 0) {\n\t\t\tparts.push(current.trim());\n\t\t\tcurrent = '';\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '<') depth++;\n\t\tif (char === '>') depth--;\n\t\tcurrent += char;\n\t}\n\tif (current) parts.push(current.trim());\n\treturn parts;\n}\n\nfunction buildTypeTag(name: string, options: TypeTagOptions | undefined): string {\n\tconst lt = name.indexOf('<');\n\tconst base = lt === -1 ? name : name.slice(0, lt);\n\n\tif (base.split('::').length !== 3) {\n\t\tthrow new Error(`${name} is not a top-level Move type`);\n\t}\n\n\tlet result = name;\n\n\tif (options?.typeArguments) {\n\t\tconst baked = lt === -1 ? [] : splitTopLevelTypeArgs(name.slice(lt + 1, -1));\n\t\tconst supplied = options.typeArguments.map((arg) => {\n\t\t\tif (typeof arg === 'string') {\n\t\t\t\treturn arg;\n\t\t\t}\n\t\t\tif (arg && typeof arg.serialize === 'function' && typeof arg.name === 'string') {\n\t\t\t\treturn arg.name;\n\t\t\t}\n\t\t\tthrow new Error(`Invalid type argument ${stringify(arg)}`);\n\t\t});\n\n\t\tif (supplied.length !== baked.length) {\n\t\t\tthrow new Error(\n\t\t\t\t`Expected ${baked.length} type arguments for ${base}, got ${supplied.length}`,\n\t\t\t);\n\t\t}\n\n\t\tresult = supplied.length === 0 ? base : `${base}<${supplied.join(', ')}>`;\n\t}\n\n\tif (HAS_PHANTOM_REGEX.test(result)) {\n\t\tthrow new Error(\n\t\t\toptions?.typeArguments\n\t\t\t\t? `A type argument contains an unfilled phantom parameter in ${result}`\n\t\t\t\t: `Missing type arguments for ${result}`,\n\t\t);\n\t}\n\n\tif (options?.package) {\n\t\tconst [, ...rest] = result.split('::');\n\t\tresult = [options.package, ...rest].join('::');\n\t}\n\n\t// fully validate address-only tags (MVR names can't be parsed as type tags)\n\tif (!HAS_PHANTOM_REGEX.test(result) && !/[@/]/.test(result)) {\n\t\tTypeTagSerializer.parseFromStr(result);\n\t}\n\n\treturn result;\n}\n\nasync function resolveBuiltTypeTag(\n\tname: string,\n\toptions: { client: ClientWithCoreApi } & TypeTagOptions,\n): Promise<string> {\n\tconst { client, ...rest } = options;\n\tconst { type } = await client.core.mvr.resolveType({\n\t\ttype: buildTypeTag(name, rest),\n\t});\n\treturn normalizeStructTag(type);\n}\n\nexport class MoveStruct<\n\tT extends Record<string, BcsType<any>>,\n\tconst Name extends string = string,\n> extends BcsStruct<T, Name> {\n\t/**\n\t * Build the type tag for this struct.\n\t *\n\t * `typeArguments` is the full positional list, in Move declaration order, and\n\t * is required when the struct has unfilled phantom parameters. The result may\n\t * contain MVR names: those are valid in transaction `typeArguments`, but for\n\t * queries or comparisons against on-chain data use `resolveTypeTag` instead.\n\t */\n\ttypeTag(...args: TypeTagParams<Name>): string {\n\t\treturn buildTypeTag(this.name, args[0] as TypeTagOptions | undefined);\n\t}\n\n\t/**\n\t * Build the type tag for this struct, then resolve any MVR names through the\n\t * client (using its configured overrides and the MVR API) and return the\n\t * normalized, address-only form suitable for queries and comparisons against\n\t * on-chain data.\n\t */\n\tasync resolveTypeTag(options: ResolveTypeTagOptions<Name>): Promise<string> {\n\t\treturn resolveBuiltTypeTag(\n\t\t\tthis.name,\n\t\t\toptions as { client: ClientWithCoreApi } & TypeTagOptions,\n\t\t);\n\t}\n\n\tasync get<Include extends Omit<SuiClientTypes.ObjectInclude, 'content' | 'json'> = {}>({\n\t\tobjectId,\n\t\t...options\n\t}: GetOptions<Include>): Promise<\n\t\tSuiClientTypes.Object<Include & { content: true; json: true }> & {\n\t\t\tjson: BcsStruct<T>['$inferType'];\n\t\t}\n\t> {\n\t\tconst [res] = await this.getMany<Include>({\n\t\t\t...options,\n\t\t\tobjectIds: [objectId],\n\t\t});\n\n\t\tif (!res) {\n\t\t\tthrow new Error(`No object found for id ${objectId}`);\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tasync getMany<Include extends Omit<SuiClientTypes.ObjectInclude, 'content' | 'json'> = {}>({\n\t\tclient,\n\t\t...options\n\t}: GetManyOptions<Include>): Promise<\n\t\tArray<\n\t\t\tSuiClientTypes.Object<Include & { content: true; json: true }> & {\n\t\t\t\tjson: BcsStruct<T>['$inferType'];\n\t\t\t}\n\t\t>\n\t> {\n\t\tconst response = (await client.core.getObjects({\n\t\t\t...options,\n\t\t\tinclude: {\n\t\t\t\t...options.include,\n\t\t\t\tcontent: true,\n\t\t\t},\n\t\t})) as SuiClientTypes.GetObjectsResponse<Include & { content: true }>;\n\n\t\treturn response.objects.map((obj) => {\n\t\t\tif (obj instanceof Error) {\n\t\t\t\tthrow obj;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\t...obj,\n\t\t\t\tjson: this.parse(obj.content),\n\t\t\t};\n\t\t});\n\t}\n}\n\nexport class MoveEnum<\n\tT extends Record<string, BcsType<any> | null>,\n\tconst Name extends string,\n> extends BcsEnum<T, Name> {\n\t/** Build the type tag for this enum. See `MoveStruct.typeTag` for semantics. */\n\ttypeTag(...args: TypeTagParams<Name>): string {\n\t\treturn buildTypeTag(this.name, args[0] as TypeTagOptions | undefined);\n\t}\n\n\t/** Build and resolve the type tag for this enum. See `MoveStruct.resolveTypeTag`. */\n\tasync resolveTypeTag(options: ResolveTypeTagOptions<Name>): Promise<string> {\n\t\treturn resolveBuiltTypeTag(\n\t\t\tthis.name,\n\t\t\toptions as { client: ClientWithCoreApi } & TypeTagOptions,\n\t\t);\n\t}\n}\n\nexport class MoveTuple<\n\tconst T extends readonly BcsType<any>[],\n\tconst Name extends string,\n> extends BcsTuple<T, Name> {\n\t/** Build the type tag for this struct. See `MoveStruct.typeTag` for semantics. */\n\ttypeTag(...args: TypeTagParams<Name>): string {\n\t\treturn buildTypeTag(this.name, args[0] as TypeTagOptions | undefined);\n\t}\n\n\t/** Build and resolve the type tag for this struct. See `MoveStruct.resolveTypeTag`. */\n\tasync resolveTypeTag(options: ResolveTypeTagOptions<Name>): Promise<string> {\n\t\treturn resolveBuiltTypeTag(\n\t\t\tthis.name,\n\t\t\toptions as { client: ClientWithCoreApi } & TypeTagOptions,\n\t\t);\n\t}\n}\n\nfunction stringify(val: unknown) {\n\tif (typeof val === 'object') {\n\t\treturn JSON.stringify(val, (_key, value) =>\n\t\t\ttypeof value === 'bigint' ? value.toString() : value,\n\t\t);\n\t}\n\tif (typeof val === 'bigint') {\n\t\treturn val.toString();\n\t}\n\n\treturn val;\n}\n"],"mappings":";;;;;AAaA,MAAM,sBAAsB,oBAAoB,MAAM;AACtD,MAAM,wBAAw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K,MACL,QACA;;;AAIH,SAAS,UAAU,KAAc;AAChC,KAAI,OAAO,QAAQ,SAClB,QAAO,KAAK,UAAU,MAAM,MAAM,UACjC,OAAO,UAAU,WAAW,MAAM,UAAU,GAAG,MAC/C;AAEF,KAAI,OAAO,QAAQ,SAClB,QAAO,IAAI,UAAU;AAGtB,QAAO"}
@@ -0,0 +1,256 @@
1
+ # Getting Started
2
+
3
+ > Install and set up Payment Kit for your Sui application.
4
+
5
+ > **Note:** This package is in active development and should be used with caution. APIs are experimental and
6
+ > subject to breaking changes without notice. We recommend thoroughly testing any implementation
7
+ > before using in production environments.
8
+
9
+ This guide will help you set up and start using the Payment Kit SDK in your Sui application.
10
+
11
+ ## Prerequisites
12
+
13
+ Before you begin, ensure you have:
14
+
15
+ - A Sui wallet with Testnet or Mainnet SUI tokens
16
+ - Basic understanding of TypeScript and the Sui blockchain
17
+
18
+ ## Installation
19
+
20
+ Install the Payment Kit SDK and the Sui TypeScript SDK:
21
+
22
+ ```bash npm2yarn
23
+ npm install --save @mysten/payment-kit @mysten/sui
24
+ ```
25
+
26
+ ## Setting up the client
27
+
28
+ The Payment Kit SDK extends the standard `SuiGrpcClient` to provide payment functionality. Here's
29
+ how to set it up:
30
+
31
+ ```ts
32
+
33
+ // Create a Sui client with Payment Kit extension
34
+ const client = new SuiGrpcClient({
35
+ network: 'testnet',
36
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
37
+ }).$extend(paymentKit());
38
+ ```
39
+
40
+ The client will automatically configure the correct package IDs for the network you're using
41
+ (Testnet or Mainnet).
42
+
43
+ ## Your first payment
44
+
45
+ Let's process a basic registry-based payment using the default payment registry:
46
+
47
+ ```ts
48
+
49
+ // Create or load your keypair
50
+ const keypair = Ed25519Keypair.generate();
51
+ const sender = keypair.getPublicKey().toSuiAddress();
52
+
53
+ // Create the payment transaction
54
+ const tx = client.paymentKit.tx.processRegistryPayment({
55
+ nonce: crypto.randomUUID(), // Unique identifier for this payment
56
+ coinType: '0x2::sui::SUI', // Coin type (SUI in this case)
57
+ amount: 1n * MIST_PER_SUI, // 1 SUI (in MIST)
58
+ receiver,
59
+ sender: sender,
60
+ });
61
+
62
+ // Sign and execute
63
+ const result = await client.signAndExecuteTransaction({
64
+ transaction: tx,
65
+ signer: keypair,
66
+ options: {
67
+ showEffects: true,
68
+ showEvents: true,
69
+ },
70
+ });
71
+
72
+ // Check transaction status
73
+ if (result.$kind === 'FailedTransaction') {
74
+ throw new Error(`Payment failed: ${result.FailedTransaction.status.error?.message}`);
75
+ }
76
+
77
+ console.log('Payment processed:', result.Transaction.digest);
78
+ ```
79
+
80
+ ## Understanding the payment
81
+
82
+ In this example:
83
+
84
+ 1. **Nonce**: A unique identifier (UUIDv4) that prevents duplicate payments when using a registry
85
+ 2. **Coin Type**: The type of coin being transferred (SUI token)
86
+ 3. **Amount**: The payment amount in the smallest unit (MIST for SUI)
87
+ 4. **Receiver**: The address receiving the payment
88
+ 5. **Sender**: The address sending the payment (must match the transaction signer)
89
+ 6. **Registry Name**: The payment registry to use (defaults to `DEFAULT_REGISTRY_NAME`)
90
+
91
+ ## Verifying the payment
92
+
93
+ After processing a payment, you can query the payment record to verify it exists:
94
+
95
+ ```ts
96
+ // Query the payment record
97
+ const paymentRecord = await client.paymentKit.getPaymentRecord({
98
+ nonce: crypto.randomUUID(),
99
+ coinType: '0x2::sui::SUI',
100
+ amount: 1n * MIST_PER_SUI,
101
+ receiver,
102
+ });
103
+
104
+ if (paymentRecord) {
105
+ console.log('Payment verified!');
106
+ console.log('Transaction:', paymentRecord.paymentTransactionDigest);
107
+ console.log('Epoch:', paymentRecord.epochAtTimeOfRecord);
108
+ } else {
109
+ console.log('Payment not found');
110
+ }
111
+ ```
112
+
113
+ ## Processing an ephemeral payment
114
+
115
+ If you don't need duplicate prevention or persistent storage, use ephemeral payments:
116
+
117
+ ```ts
118
+ const tx = client.paymentKit.tx.processEphemeralPayment({
119
+ nonce: crypto.randomUUID(),
120
+ coinType: '0x2::sui::SUI',
121
+ amount: 1n * MIST_PER_SUI,
122
+ receiver,
123
+ sender: sender,
124
+ });
125
+
126
+ const result = await client.signAndExecuteTransaction({
127
+ transaction: tx,
128
+ signer: keypair,
129
+ });
130
+
131
+ // Check transaction status
132
+ if (result.$kind === 'FailedTransaction') {
133
+ throw new Error(`Ephemeral payment failed: ${result.FailedTransaction.status.error?.message}`);
134
+ }
135
+
136
+ console.log('Ephemeral payment processed:', result.Transaction.digest);
137
+ ```
138
+
139
+ Ephemeral payments:
140
+
141
+ - Don't create a `PaymentRecord`
142
+ - Don't prevent duplicates
143
+ - Still emit a `PaymentReceipt` event
144
+ - Have lower gas costs
145
+
146
+ ## Working with different coin types
147
+
148
+ Payment Kit supports any Sui coin type. Here's how to process payments with custom coins:
149
+
150
+ ```ts
151
+ // Example with a custom coin type
152
+ const customCoinType = '0xabcd...::my_coin::MY_COIN';
153
+
154
+ const tx = client.paymentKit.tx.processRegistryPayment({
155
+ nonce: crypto.randomUUID(),
156
+ coinType: customCoinType,
157
+ amount: 5000,
158
+ receiver,
159
+ sender: sender,
160
+ });
161
+
162
+ // Execute the transaction
163
+ const result = await client.signAndExecuteTransaction({
164
+ transaction: tx,
165
+ signer: keypair,
166
+ });
167
+ ```
168
+
169
+ ## Error handling
170
+
171
+ Always wrap payment operations in try-catch blocks:
172
+
173
+ ```ts
174
+ try {
175
+ const tx = client.paymentKit.tx.processRegistryPayment({...});
176
+ const result = await client.signAndExecuteTransaction({
177
+ transaction: tx,
178
+ signer: keypair,
179
+ });
180
+
181
+ if (result.$kind === 'FailedTransaction') {
182
+ throw new Error(`Payment failed: ${result.FailedTransaction.status.error?.message}`);
183
+ }
184
+
185
+ console.log('Success:', result.Transaction.digest);
186
+ } catch (error) {
187
+ if (error.message.includes('Duplicate')) {
188
+ console.error('Payment already processed');
189
+ } else if (error.message.includes('insufficient')) {
190
+ console.error('Insufficient balance');
191
+ } else {
192
+ console.error('Payment failed:', error.message);
193
+ }
194
+ }
195
+ ```
196
+
197
+ ## Creating payment URIs
198
+
199
+ Payment Kit provides helper functions to create and parse Payment Kit transaction URIs. These URIs
200
+ are useful for generating payment links, QR codes, or deep links in your application:
201
+
202
+ ```ts
203
+
204
+ // Create a payment URI
205
+ const paymentUri = createPaymentTransactionUri({
206
+ receiverAddress: '0x123...abc',
207
+ amount: 1000000000n, // 1 SUI in MIST
208
+ coinType: '0x2::sui::SUI',
209
+ nonce: crypto.randomUUID(),
210
+ label: 'Coffee Payment',
211
+ message: 'Payment for espresso',
212
+ registryName: 'my-registry', // Optional: specify a registry name
213
+ // Or use registryId: '0x...' for a specific registry object ID
214
+ });
215
+
216
+ console.log(paymentUri);
217
+ // Output: sui:pay?receiver=0x123...abc&amount=1000000000&coinType=0x2%3A%3Asui%3A%3ASUI&nonce=...&label=Coffee%20Payment&message=Payment%20for%20espresso&registry=my-registry
218
+ ```
219
+
220
+ The URI parameters include:
221
+
222
+ - **receiver**: The Sui address receiving the payment (required)
223
+ - **amount**: The payment amount as a positive bigint (required)
224
+ - **coinType**: The coin type being transferred (required)
225
+ - **nonce**: A unique identifier up to 36 characters (required)
226
+ - **registry**: Either a registry name or object ID (optional)
227
+ - **label**: A short label for the payment (optional)
228
+ - **message**: A longer description message (optional)
229
+ - **iconUrl**: URL to an icon for display purposes (optional)
230
+
231
+ You can then parse URIs back into payment parameters:
232
+
233
+ ```ts
234
+
235
+ // Parse a payment URI
236
+ const params = parsePaymentTransactionUri(paymentUri);
237
+ // Returns: { receiverAddress, amount, coinType, nonce, label?, message?, iconUrl?, registryName? | registryId? }
238
+
239
+ // Use the parsed parameters to create a transaction
240
+ const tx = client.paymentKit.tx.processRegistryPayment({
241
+ receiver: params.receiverAddress,
242
+ amount: params.amount,
243
+ coinType: params.coinType,
244
+ nonce: params.nonce,
245
+ registryName: params.registryName,
246
+ sender: sender,
247
+ });
248
+ ```
249
+
250
+ ## Next steps
251
+
252
+ Now that you understand the basics, explore more advanced features:
253
+
254
+ - [Payment Processing](./payment-processing) - Deep dive into payment models
255
+ - [Registry Management](./registry-management) - Create and configure custom registries
256
+ - [SDK API Reference](./payment-kit-sdk) - Complete SDK API documentation
package/docs/index.md ADDED
@@ -0,0 +1,132 @@
1
+ # Payment Kit
2
+
3
+ > Accept payments in any coin type on the Sui blockchain with built-in duplicate prevention.
4
+
5
+ > **Note:** This package is in active development and should be used with caution. APIs are experimental and
6
+ > subject to breaking changes without notice. We recommend thoroughly testing any implementation
7
+ > before using in production environments.
8
+
9
+ The Sui Payment Kit SDK is a TypeScript library that provides a straightforward and secure way to
10
+ process blockchain payments on the Sui network. It offers flexible payment processing with built-in
11
+ duplicate prevention, configurable payment registries, and comprehensive receipt management.
12
+
13
+ ## Overview
14
+
15
+ Payment Kit enables developers to integrate secure payment processing into their Sui applications
16
+ with minimal setup. The SDK provides two payment models:
17
+
18
+ - **Registry-based payments**: Persistent payment records with duplicate prevention and configurable
19
+ expiration
20
+ - **Ephemeral payments**: Lightweight payment processing without persistent storage
21
+
22
+ All payments emit a `PaymentReceipt` that can be stored offchain for verification and
23
+ record-keeping.
24
+
25
+ ## Key features
26
+
27
+ - **Duplicate Prevention**: Registry-based payments automatically prevent duplicate transactions
28
+ - **Flexible Payment Models**: Choose between registry-based or ephemeral payment processing
29
+ - **Payment Registries**: Create and manage custom payment registries with configurable policies
30
+ - **Receipt Management**: Automatic receipt generation for all payments
31
+ - **Multi-coin Support**: Process payments with any Sui coin type
32
+ - **Configurable Expiration**: Set custom expiration policies for payment records
33
+ - **Fund Management**: Optional registry-managed funds for simplified coin handling
34
+
35
+ ## Installation
36
+
37
+ ```bash npm2yarn
38
+ npm install --save @mysten/payment-kit @mysten/sui
39
+ ```
40
+
41
+ ## Quick start
42
+
43
+ ```ts
44
+
45
+ // Create a Sui client with a Payment Kit extension
46
+ const client = new SuiGrpcClient({
47
+ network: 'testnet',
48
+ baseUrl: 'https://fullnode.testnet.sui.io:443',
49
+ }).$extend(paymentKit());
50
+
51
+ // Process a registry-based payment
52
+ const tx = client.paymentKit.tx.processRegistryPayment({
53
+ nonce: crypto.randomUUID(),
54
+ coinType: '0x2::sui::SUI',
55
+ amount: 1n * MIST_PER_SUI, // 1 SUI in MIST
56
+ receiver: '0x123...abc',
57
+ sender: '0x456...def',
58
+ });
59
+
60
+ // Sign and execute the transaction
61
+ const result = await client.signAndExecuteTransaction({
62
+ transaction: tx,
63
+ signer: keypair,
64
+ });
65
+
66
+ // Check transaction status
67
+ if (result.$kind === 'FailedTransaction') {
68
+ throw new Error(`Payment failed: ${result.FailedTransaction.status.error?.message}`);
69
+ }
70
+ ```
71
+
72
+ ## Network support
73
+
74
+ Payment Kit supports the following Sui networks:
75
+
76
+ - **Mainnet**: Production environment
77
+ - **Testnet**: Testing environment
78
+
79
+ The SDK automatically configures the correct package and object IDs based on the network specified
80
+ in your `SuiGrpcClient` configuration.
81
+
82
+ ## Core concepts
83
+
84
+ ### Payment processing
85
+
86
+ Payment Kit offers two distinct payment processing models to suit different application needs:
87
+
88
+ 1. **Registry-based Payments**: Creates a persistent `PaymentRecord` that prevents duplicate
89
+ payments and provides verifiable proof of payment
90
+ 2. **Ephemeral Payments**: Processes payments without persistent storage, suitable for scenarios
91
+ where duplicate prevention is handled externally
92
+
93
+ ### Payment registries
94
+
95
+ A `PaymentRegistry` manages payment records and configurations. Benefits include:
96
+
97
+ - Centralized payment tracking
98
+ - Configurable expiration policies
99
+ - Optional fund management
100
+ - Custom naming for easy identification and indexing
101
+
102
+ ### Payment records
103
+
104
+ When using registry-based payments, a `PaymentRecord` is created as a Dynamic Field on the registry.
105
+ Records are identified by a composite key derived from:
106
+
107
+ - Payment nonce (unique identifier)
108
+ - Payment amount
109
+ - Coin type
110
+ - Receiver address
111
+
112
+ ### Payment receipts
113
+
114
+ Every payment (registry-based or ephemeral) emits a `PaymentReceipt` event containing:
115
+
116
+ ```ts
117
+ type PaymentReceipt = {
118
+ paymentType: 'Registry' | 'Ephemeral';
119
+ nonce: string;
120
+ amount: number;
121
+ receiver: string;
122
+ coinType: string;
123
+ timestampMs: number;
124
+ };
125
+ ```
126
+
127
+ ## Next steps
128
+
129
+ - [Getting Started Guide](/payment-kit/getting-started) - Detailed setup and usage instructions
130
+ - [Payment Processing](/payment-kit/payment-processing) - Learn about different payment models
131
+ - [Registry Management](/payment-kit/registry-management) - Create and configure payment registries
132
+ - [SDK API Reference](/payment-kit/payment-kit-sdk) - Complete SDK API documentation
@@ -0,0 +1,8 @@
1
+ # Payment Kit
2
+ > Accept payments in any coin type on Sui
3
+
4
+ - [Payment Kit](..md): Accept payments in any coin type on the Sui blockchain with built-in duplicate prevention.
5
+ - [Getting Started](./getting-started.md): Install and set up Payment Kit for your Sui application.
6
+ - [Payment Kit SDK](./payment-kit-sdk.md): Payment Kit SDK API reference and configuration for the PaymentKitClient.
7
+ - [Payment Processing](./payment-processing.md): Process registry-based and ephemeral payments and handle transaction results on Sui.
8
+ - [Registry Management](./registry-management.md): Create, configure, and manage payment registries and accepted coin types on Sui.