@t2000/mpp-sui 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 t2000
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,102 @@
1
+ 'use strict';
2
+
3
+ var mppx = require('mppx');
4
+ var transactions = require('@mysten/sui/transactions');
5
+
6
+ // src/client.ts
7
+ var suiCharge = mppx.Method.from({
8
+ intent: "charge",
9
+ name: "sui",
10
+ schema: {
11
+ credential: {
12
+ payload: mppx.z.object({
13
+ digest: mppx.z.string()
14
+ })
15
+ },
16
+ request: mppx.z.object({
17
+ amount: mppx.z.string(),
18
+ currency: mppx.z.string(),
19
+ recipient: mppx.z.string()
20
+ })
21
+ }
22
+ });
23
+
24
+ // src/utils.ts
25
+ var SUI_USDC_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
26
+ async function fetchCoins(client, owner, coinType) {
27
+ const coins = [];
28
+ let cursor;
29
+ let hasNext = true;
30
+ while (hasNext) {
31
+ const page = await client.getCoins({ owner, coinType, cursor: cursor ?? void 0 });
32
+ coins.push(...page.data.map((c) => ({ coinObjectId: c.coinObjectId, balance: c.balance })));
33
+ cursor = page.nextCursor;
34
+ hasNext = page.hasNextPage;
35
+ }
36
+ return coins;
37
+ }
38
+ function parseAmountToRaw(amount, decimals) {
39
+ const [whole = "0", frac = ""] = amount.split(".");
40
+ const paddedFrac = frac.padEnd(decimals, "0").slice(0, decimals);
41
+ return BigInt(whole + paddedFrac);
42
+ }
43
+
44
+ // src/client.ts
45
+ function sui(options) {
46
+ const address = options.signer.getPublicKey().toSuiAddress();
47
+ return mppx.Method.toClient(suiCharge, {
48
+ async createCredential({ challenge }) {
49
+ const { amount, currency, recipient } = challenge.request;
50
+ const amountRaw = parseAmountToRaw(amount, 6);
51
+ const coins = await fetchCoins(options.client, address, currency);
52
+ if (coins.length === 0) {
53
+ throw new Error(
54
+ `No ${currency.split("::").pop()} balance to pay with`
55
+ );
56
+ }
57
+ const totalBalance = coins.reduce(
58
+ (sum, c) => sum + BigInt(c.balance),
59
+ 0n
60
+ );
61
+ if (totalBalance < amountRaw) {
62
+ const available = Number(totalBalance) / 1e6;
63
+ const requested = Number(amountRaw) / 1e6;
64
+ throw new Error(
65
+ `Not enough USDC to pay $${requested.toFixed(2)} (available: $${available.toFixed(2)})`
66
+ );
67
+ }
68
+ const tx = new transactions.Transaction();
69
+ tx.setSender(address);
70
+ const primaryCoin = tx.object(coins[0].coinObjectId);
71
+ if (coins.length > 1) {
72
+ tx.mergeCoins(
73
+ primaryCoin,
74
+ coins.slice(1).map((c) => tx.object(c.coinObjectId))
75
+ );
76
+ }
77
+ const [payment] = tx.splitCoins(primaryCoin, [amountRaw]);
78
+ tx.transferObjects([payment], recipient);
79
+ let result;
80
+ try {
81
+ result = await options.client.signAndExecuteTransaction({
82
+ signer: options.signer,
83
+ transaction: tx,
84
+ options: { showEffects: true }
85
+ });
86
+ } catch (err) {
87
+ const msg = err instanceof Error ? err.message : String(err);
88
+ throw new Error(`Payment transaction failed: ${msg}`);
89
+ }
90
+ return mppx.Credential.serialize({
91
+ challenge,
92
+ payload: { digest: result.digest }
93
+ });
94
+ }
95
+ });
96
+ }
97
+
98
+ exports.SUI_USDC_TYPE = SUI_USDC_TYPE;
99
+ exports.sui = sui;
100
+ exports.suiCharge = suiCharge;
101
+ //# sourceMappingURL=client.cjs.map
102
+ //# sourceMappingURL=client.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/method.ts","../src/utils.ts","../src/client.ts"],"names":["Method","z","Transaction","Credential"],"mappings":";;;;;;AAEO,IAAM,SAAA,GAAYA,YAAO,IAAA,CAAK;AAAA,EACnC,MAAA,EAAQ,QAAA;AAAA,EACR,IAAA,EAAM,KAAA;AAAA,EACN,MAAA,EAAQ;AAAA,IACN,UAAA,EAAY;AAAA,MACV,OAAA,EAASC,OAAE,MAAA,CAAO;AAAA,QAChB,MAAA,EAAQA,OAAE,MAAA;AAAO,OAClB;AAAA,KACH;AAAA,IACA,OAAA,EAASA,OAAE,MAAA,CAAO;AAAA,MAChB,MAAA,EAAQA,OAAE,MAAA,EAAO;AAAA,MACjB,QAAA,EAAUA,OAAE,MAAA,EAAO;AAAA,MACnB,SAAA,EAAWA,OAAE,MAAA;AAAO,KACrB;AAAA;AAEL,CAAC;;;ACfM,IAAM,aAAA,GACX;AAUF,eAAsB,UAAA,CACpB,MAAA,EACA,KAAA,EACA,QAAA,EACqB;AACrB,EAAA,MAAM,QAAoB,EAAC;AAC3B,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI,OAAA,GAAU,IAAA;AACd,EAAA,OAAO,OAAA,EAAS;AACd,IAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,QAAA,CAAS,EAAE,OAAO,QA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MAAA,GAAS,MAAM,OAAA,CAAQ,MAAA,CAAO,yBAAA,CAA0B;AAAA,UACtD,QAAQ,OAAA,CAAQ,MAAA;AAAA,UAChB,WAAA,EAAa,EAAA;AAAA,UACb,OAAA,EAAS,EAAE,WAAA,EAAa,IAAA;AAAK,SAC9B,CAAA;AAAA,MACH,SAAS,GAAA,EAAc;AACrB,QAAA,MAAM,MAAM,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAC3D,QAAA,MAAM,IAAI,KAAA,CAAM,CAAA,4BAAA,EAA+B,GAAG,CAAA,CAAE,CAAA;AAAA,MACtD;AAEA,MAAA,OAAOC,gBAAW,SAAA,CAAU;AAAA,QAC1B,SAAA;AAAA,QACA,OAAA,EAAS,EAAE,MAAA,EAAQ,MAAA,CAAO,MAAA;AAAO,OAClC,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH","file":"client.cjs","sourcesContent":["import { Method, z } from 'mppx';\n\nexport const suiCharge = Method.from({\n intent: 'charge',\n name: 'sui',\n schema: {\n credential: {\n payload: z.object({\n digest: z.string(),\n }),\n },\n request: z.object({\n amount: z.string(),\n currency: z.string(),\n recipient: z.string(),\n }),\n },\n});\n","import type { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';\n\nexport const SUI_USDC_TYPE =\n '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC';\n\n/**\n * Fetch ALL coins of a given type, handling Sui pagination (max 50 per page).\n */\nexport interface CoinInfo {\n coinObjectId: string;\n balance: string;\n}\n\nexport async function fetchCoins(\n client: SuiJsonRpcClient,\n owner: string,\n coinType: string,\n): Promise<CoinInfo[]> {\n const coins: CoinInfo[] = [];\n let cursor: string | null | undefined;\n let hasNext = true;\n while (hasNext) {\n const page = await client.getCoins({ owner, coinType, cursor: cursor ?? undefined });\n coins.push(...page.data.map((c) => ({ coinObjectId: c.coinObjectId, balance: c.balance })));\n cursor = page.nextCursor;\n hasNext = page.hasNextPage;\n }\n return coins;\n}\n\n/**\n * Parse a string amount to raw bigint units without floating-point math.\n * \"0.01\" with 6 decimals → 10000n\n */\nexport function parseAmountToRaw(amount: string, decimals: number): bigint {\n const [whole = '0', frac = ''] = amount.split('.');\n const paddedFrac = frac.padEnd(decimals, '0').slice(0, decimals);\n return BigInt(whole + paddedFrac);\n}\n","import { Method, Credential } from 'mppx';\nimport type { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';\nimport type { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { suiCharge } from './method.js';\nimport { fetchCoins, parseAmountToRaw } from './utils.js';\n\nexport { suiCharge } from './method.js';\nexport { SUI_USDC_TYPE } from './utils.js';\n\nexport interface SuiChargeOptions {\n client: SuiJsonRpcClient;\n signer: Ed25519Keypair;\n}\n\nexport function sui(options: SuiChargeOptions) {\n const address = options.signer.getPublicKey().toSuiAddress();\n\n return Method.toClient(suiCharge, {\n async createCredential({ challenge }) {\n const { amount, currency, recipient } = challenge.request;\n const amountRaw = parseAmountToRaw(amount, 6);\n\n const coins = await fetchCoins(options.client, address, currency);\n if (coins.length === 0) {\n throw new Error(\n `No ${currency.split('::').pop()} balance to pay with`,\n );\n }\n\n const totalBalance = coins.reduce(\n (sum, c) => sum + BigInt(c.balance),\n 0n,\n );\n if (totalBalance < amountRaw) {\n const available = Number(totalBalance) / 1e6;\n const requested = Number(amountRaw) / 1e6;\n throw new Error(\n `Not enough USDC to pay $${requested.toFixed(2)} (available: $${available.toFixed(2)})`,\n );\n }\n\n const tx = new Transaction();\n tx.setSender(address);\n\n const primaryCoin = tx.object(coins[0].coinObjectId);\n if (coins.length > 1) {\n tx.mergeCoins(\n primaryCoin,\n coins.slice(1).map((c) => tx.object(c.coinObjectId)),\n );\n }\n\n const [payment] = tx.splitCoins(primaryCoin, [amountRaw]);\n tx.transferObjects([payment], recipient);\n\n let result;\n try {\n result = await options.client.signAndExecuteTransaction({\n signer: options.signer,\n transaction: tx,\n options: { showEffects: true },\n });\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Payment transaction failed: ${msg}`);\n }\n\n return Credential.serialize({\n challenge,\n payload: { digest: result.digest },\n });\n },\n });\n}\n"]}
@@ -0,0 +1,29 @@
1
+ import * as zod_v4_core from 'zod/v4/core';
2
+ import * as zod_mini from 'zod/mini';
3
+ import { Method } from 'mppx';
4
+ import { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';
5
+ import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
6
+ export { S as SUI_USDC_TYPE, s as suiCharge } from './utils-CzBi2QXm.cjs';
7
+
8
+ interface SuiChargeOptions {
9
+ client: SuiJsonRpcClient;
10
+ signer: Ed25519Keypair;
11
+ }
12
+ declare function sui(options: SuiChargeOptions): Method.Client<{
13
+ readonly intent: "charge";
14
+ readonly name: "sui";
15
+ readonly schema: {
16
+ readonly credential: {
17
+ readonly payload: zod_mini.ZodMiniObject<{
18
+ digest: zod_mini.ZodMiniString<string>;
19
+ }, zod_v4_core.$strip>;
20
+ };
21
+ readonly request: zod_mini.ZodMiniObject<{
22
+ amount: zod_mini.ZodMiniString<string>;
23
+ currency: zod_mini.ZodMiniString<string>;
24
+ recipient: zod_mini.ZodMiniString<string>;
25
+ }, zod_v4_core.$strip>;
26
+ };
27
+ }, undefined>;
28
+
29
+ export { type SuiChargeOptions, sui };
@@ -0,0 +1,29 @@
1
+ import * as zod_v4_core from 'zod/v4/core';
2
+ import * as zod_mini from 'zod/mini';
3
+ import { Method } from 'mppx';
4
+ import { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';
5
+ import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
6
+ export { S as SUI_USDC_TYPE, s as suiCharge } from './utils-CzBi2QXm.js';
7
+
8
+ interface SuiChargeOptions {
9
+ client: SuiJsonRpcClient;
10
+ signer: Ed25519Keypair;
11
+ }
12
+ declare function sui(options: SuiChargeOptions): Method.Client<{
13
+ readonly intent: "charge";
14
+ readonly name: "sui";
15
+ readonly schema: {
16
+ readonly credential: {
17
+ readonly payload: zod_mini.ZodMiniObject<{
18
+ digest: zod_mini.ZodMiniString<string>;
19
+ }, zod_v4_core.$strip>;
20
+ };
21
+ readonly request: zod_mini.ZodMiniObject<{
22
+ amount: zod_mini.ZodMiniString<string>;
23
+ currency: zod_mini.ZodMiniString<string>;
24
+ recipient: zod_mini.ZodMiniString<string>;
25
+ }, zod_v4_core.$strip>;
26
+ };
27
+ }, undefined>;
28
+
29
+ export { type SuiChargeOptions, sui };
package/dist/client.js ADDED
@@ -0,0 +1,98 @@
1
+ import { Method, z, Credential } from 'mppx';
2
+ import { Transaction } from '@mysten/sui/transactions';
3
+
4
+ // src/client.ts
5
+ var suiCharge = Method.from({
6
+ intent: "charge",
7
+ name: "sui",
8
+ schema: {
9
+ credential: {
10
+ payload: z.object({
11
+ digest: z.string()
12
+ })
13
+ },
14
+ request: z.object({
15
+ amount: z.string(),
16
+ currency: z.string(),
17
+ recipient: z.string()
18
+ })
19
+ }
20
+ });
21
+
22
+ // src/utils.ts
23
+ var SUI_USDC_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
24
+ async function fetchCoins(client, owner, coinType) {
25
+ const coins = [];
26
+ let cursor;
27
+ let hasNext = true;
28
+ while (hasNext) {
29
+ const page = await client.getCoins({ owner, coinType, cursor: cursor ?? void 0 });
30
+ coins.push(...page.data.map((c) => ({ coinObjectId: c.coinObjectId, balance: c.balance })));
31
+ cursor = page.nextCursor;
32
+ hasNext = page.hasNextPage;
33
+ }
34
+ return coins;
35
+ }
36
+ function parseAmountToRaw(amount, decimals) {
37
+ const [whole = "0", frac = ""] = amount.split(".");
38
+ const paddedFrac = frac.padEnd(decimals, "0").slice(0, decimals);
39
+ return BigInt(whole + paddedFrac);
40
+ }
41
+
42
+ // src/client.ts
43
+ function sui(options) {
44
+ const address = options.signer.getPublicKey().toSuiAddress();
45
+ return Method.toClient(suiCharge, {
46
+ async createCredential({ challenge }) {
47
+ const { amount, currency, recipient } = challenge.request;
48
+ const amountRaw = parseAmountToRaw(amount, 6);
49
+ const coins = await fetchCoins(options.client, address, currency);
50
+ if (coins.length === 0) {
51
+ throw new Error(
52
+ `No ${currency.split("::").pop()} balance to pay with`
53
+ );
54
+ }
55
+ const totalBalance = coins.reduce(
56
+ (sum, c) => sum + BigInt(c.balance),
57
+ 0n
58
+ );
59
+ if (totalBalance < amountRaw) {
60
+ const available = Number(totalBalance) / 1e6;
61
+ const requested = Number(amountRaw) / 1e6;
62
+ throw new Error(
63
+ `Not enough USDC to pay $${requested.toFixed(2)} (available: $${available.toFixed(2)})`
64
+ );
65
+ }
66
+ const tx = new Transaction();
67
+ tx.setSender(address);
68
+ const primaryCoin = tx.object(coins[0].coinObjectId);
69
+ if (coins.length > 1) {
70
+ tx.mergeCoins(
71
+ primaryCoin,
72
+ coins.slice(1).map((c) => tx.object(c.coinObjectId))
73
+ );
74
+ }
75
+ const [payment] = tx.splitCoins(primaryCoin, [amountRaw]);
76
+ tx.transferObjects([payment], recipient);
77
+ let result;
78
+ try {
79
+ result = await options.client.signAndExecuteTransaction({
80
+ signer: options.signer,
81
+ transaction: tx,
82
+ options: { showEffects: true }
83
+ });
84
+ } catch (err) {
85
+ const msg = err instanceof Error ? err.message : String(err);
86
+ throw new Error(`Payment transaction failed: ${msg}`);
87
+ }
88
+ return Credential.serialize({
89
+ challenge,
90
+ payload: { digest: result.digest }
91
+ });
92
+ }
93
+ });
94
+ }
95
+
96
+ export { SUI_USDC_TYPE, sui, suiCharge };
97
+ //# sourceMappingURL=client.js.map
98
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/method.ts","../src/utils.ts","../src/client.ts"],"names":["Method"],"mappings":";;;;AAEO,IAAM,SAAA,GAAY,OAAO,IAAA,CAAK;AAAA,EACnC,MAAA,EAAQ,QA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ourcesContent":["import { Method, z } from 'mppx';\n\nexport const suiCharge = Method.from({\n intent: 'charge',\n name: 'sui',\n schema: {\n credential: {\n payload: z.object({\n digest: z.string(),\n }),\n },\n request: z.object({\n amount: z.string(),\n currency: z.string(),\n recipient: z.string(),\n }),\n },\n});\n","import type { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';\n\nexport const SUI_USDC_TYPE =\n '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC';\n\n/**\n * Fetch ALL coins of a given type, handling Sui pagination (max 50 per page).\n */\nexport interface CoinInfo {\n coinObjectId: string;\n balance: string;\n}\n\nexport async function fetchCoins(\n client: SuiJsonRpcClient,\n owner: string,\n coinType: string,\n): Promise<CoinInfo[]> {\n const coins: CoinInfo[] = [];\n let cursor: string | null | undefined;\n let hasNext = true;\n while (hasNext) {\n const page = await client.getCoins({ owner, coinType, cursor: cursor ?? undefined });\n coins.push(...page.data.map((c) => ({ coinObjectId: c.coinObjectId, balance: c.balance })));\n cursor = page.nextCursor;\n hasNext = page.hasNextPage;\n }\n return coins;\n}\n\n/**\n * Parse a string amount to raw bigint units without floating-point math.\n * \"0.01\" with 6 decimals → 10000n\n */\nexport function parseAmountToRaw(amount: string, decimals: number): bigint {\n const [whole = '0', frac = ''] = amount.split('.');\n const paddedFrac = frac.padEnd(decimals, '0').slice(0, decimals);\n return BigInt(whole + paddedFrac);\n}\n","import { Method, Credential } from 'mppx';\nimport type { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';\nimport type { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { suiCharge } from './method.js';\nimport { fetchCoins, parseAmountToRaw } from './utils.js';\n\nexport { suiCharge } from './method.js';\nexport { SUI_USDC_TYPE } from './utils.js';\n\nexport interface SuiChargeOptions {\n client: SuiJsonRpcClient;\n signer: Ed25519Keypair;\n}\n\nexport function sui(options: SuiChargeOptions) {\n const address = options.signer.getPublicKey().toSuiAddress();\n\n return Method.toClient(suiCharge, {\n async createCredential({ challenge }) {\n const { amount, currency, recipient } = challenge.request;\n const amountRaw = parseAmountToRaw(amount, 6);\n\n const coins = await fetchCoins(options.client, address, currency);\n if (coins.length === 0) {\n throw new Error(\n `No ${currency.split('::').pop()} balance to pay with`,\n );\n }\n\n const totalBalance = coins.reduce(\n (sum, c) => sum + BigInt(c.balance),\n 0n,\n );\n if (totalBalance < amountRaw) {\n const available = Number(totalBalance) / 1e6;\n const requested = Number(amountRaw) / 1e6;\n throw new Error(\n `Not enough USDC to pay $${requested.toFixed(2)} (available: $${available.toFixed(2)})`,\n );\n }\n\n const tx = new Transaction();\n tx.setSender(address);\n\n const primaryCoin = tx.object(coins[0].coinObjectId);\n if (coins.length > 1) {\n tx.mergeCoins(\n primaryCoin,\n coins.slice(1).map((c) => tx.object(c.coinObjectId)),\n );\n }\n\n const [payment] = tx.splitCoins(primaryCoin, [amountRaw]);\n tx.transferObjects([payment], recipient);\n\n let result;\n try {\n result = await options.client.signAndExecuteTransaction({\n signer: options.signer,\n transaction: tx,\n options: { showEffects: true },\n });\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Payment transaction failed: ${msg}`);\n }\n\n return Credential.serialize({\n challenge,\n payload: { digest: result.digest },\n });\n },\n });\n}\n"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,151 @@
1
+ 'use strict';
2
+
3
+ var mppx = require('mppx');
4
+ var transactions = require('@mysten/sui/transactions');
5
+ var jsonRpc = require('@mysten/sui/jsonRpc');
6
+ var utils = require('@mysten/sui/utils');
7
+
8
+ // src/method.ts
9
+ var suiCharge = mppx.Method.from({
10
+ intent: "charge",
11
+ name: "sui",
12
+ schema: {
13
+ credential: {
14
+ payload: mppx.z.object({
15
+ digest: mppx.z.string()
16
+ })
17
+ },
18
+ request: mppx.z.object({
19
+ amount: mppx.z.string(),
20
+ currency: mppx.z.string(),
21
+ recipient: mppx.z.string()
22
+ })
23
+ }
24
+ });
25
+
26
+ // src/utils.ts
27
+ var SUI_USDC_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
28
+ async function fetchCoins(client, owner, coinType) {
29
+ const coins = [];
30
+ let cursor;
31
+ let hasNext = true;
32
+ while (hasNext) {
33
+ const page = await client.getCoins({ owner, coinType, cursor: cursor ?? void 0 });
34
+ coins.push(...page.data.map((c) => ({ coinObjectId: c.coinObjectId, balance: c.balance })));
35
+ cursor = page.nextCursor;
36
+ hasNext = page.hasNextPage;
37
+ }
38
+ return coins;
39
+ }
40
+ function parseAmountToRaw(amount, decimals) {
41
+ const [whole = "0", frac = ""] = amount.split(".");
42
+ const paddedFrac = frac.padEnd(decimals, "0").slice(0, decimals);
43
+ return BigInt(whole + paddedFrac);
44
+ }
45
+
46
+ // src/client.ts
47
+ function sui(options) {
48
+ const address = options.signer.getPublicKey().toSuiAddress();
49
+ return mppx.Method.toClient(suiCharge, {
50
+ async createCredential({ challenge }) {
51
+ const { amount, currency, recipient } = challenge.request;
52
+ const amountRaw = parseAmountToRaw(amount, 6);
53
+ const coins = await fetchCoins(options.client, address, currency);
54
+ if (coins.length === 0) {
55
+ throw new Error(
56
+ `No ${currency.split("::").pop()} balance to pay with`
57
+ );
58
+ }
59
+ const totalBalance = coins.reduce(
60
+ (sum, c) => sum + BigInt(c.balance),
61
+ 0n
62
+ );
63
+ if (totalBalance < amountRaw) {
64
+ const available = Number(totalBalance) / 1e6;
65
+ const requested = Number(amountRaw) / 1e6;
66
+ throw new Error(
67
+ `Not enough USDC to pay $${requested.toFixed(2)} (available: $${available.toFixed(2)})`
68
+ );
69
+ }
70
+ const tx = new transactions.Transaction();
71
+ tx.setSender(address);
72
+ const primaryCoin = tx.object(coins[0].coinObjectId);
73
+ if (coins.length > 1) {
74
+ tx.mergeCoins(
75
+ primaryCoin,
76
+ coins.slice(1).map((c) => tx.object(c.coinObjectId))
77
+ );
78
+ }
79
+ const [payment] = tx.splitCoins(primaryCoin, [amountRaw]);
80
+ tx.transferObjects([payment], recipient);
81
+ let result;
82
+ try {
83
+ result = await options.client.signAndExecuteTransaction({
84
+ signer: options.signer,
85
+ transaction: tx,
86
+ options: { showEffects: true }
87
+ });
88
+ } catch (err) {
89
+ const msg = err instanceof Error ? err.message : String(err);
90
+ throw new Error(`Payment transaction failed: ${msg}`);
91
+ }
92
+ return mppx.Credential.serialize({
93
+ challenge,
94
+ payload: { digest: result.digest }
95
+ });
96
+ }
97
+ });
98
+ }
99
+ function sui2(options) {
100
+ const network = options.network ?? "mainnet";
101
+ const client = new jsonRpc.SuiJsonRpcClient({
102
+ url: options.rpcUrl ?? jsonRpc.getJsonRpcFullnodeUrl(network),
103
+ network
104
+ });
105
+ const normalizedRecipient = utils.normalizeSuiAddress(options.recipient);
106
+ return mppx.Method.toServer(suiCharge, {
107
+ defaults: {
108
+ currency: options.currency,
109
+ recipient: options.recipient
110
+ },
111
+ async verify({ credential }) {
112
+ const tx = await client.getTransactionBlock({
113
+ digest: credential.payload.digest,
114
+ options: { showEffects: true, showBalanceChanges: true }
115
+ });
116
+ if (tx.effects?.status?.status !== "success") {
117
+ throw new Error("Transaction failed on-chain");
118
+ }
119
+ const payment = (tx.balanceChanges ?? []).find(
120
+ (bc) => bc.coinType === options.currency && typeof bc.owner === "object" && bc.owner !== null && "AddressOwner" in bc.owner && utils.normalizeSuiAddress(bc.owner.AddressOwner) === normalizedRecipient && Number(bc.amount) > 0
121
+ );
122
+ if (!payment) {
123
+ throw new Error(
124
+ "Payment not found in transaction balance changes"
125
+ );
126
+ }
127
+ const transferredRaw = BigInt(payment.amount);
128
+ const requestedRaw = parseAmountToRaw(credential.challenge.request.amount, 6);
129
+ if (transferredRaw < requestedRaw) {
130
+ throw new Error(
131
+ `Transferred ${transferredRaw} < requested ${requestedRaw} (raw units)`
132
+ );
133
+ }
134
+ return mppx.Receipt.from({
135
+ method: "sui",
136
+ reference: credential.payload.digest,
137
+ status: "success",
138
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
139
+ });
140
+ }
141
+ });
142
+ }
143
+
144
+ exports.SUI_USDC_TYPE = SUI_USDC_TYPE;
145
+ exports.fetchCoins = fetchCoins;
146
+ exports.parseAmountToRaw = parseAmountToRaw;
147
+ exports.suiCharge = suiCharge;
148
+ exports.suiClient = sui;
149
+ exports.suiServer = sui2;
150
+ //# sourceMappingURL=index.cjs.map
151
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/method.ts","../src/utils.ts","../src/client.ts","../src/server.ts"],"names":["Method","z","Transaction","Credential","sui","SuiJsonRpcClient","getJsonRpcFullnodeUrl","normalizeSuiAddress","Receipt"],"mappings":";;;;;;;;AAEO,IAAM,SAAA,GAAYA,YAAO,IAAA,CAAK;AAAA,EACnC,MAAA,EAAQ,QAAA;AAAA,EACR,IAAA,EAAM,KAAA;AAAA,EACN,MAAA,EAAQ;AAAA,IACN,UAAA,EAAY;AAAA,MACV,OAAA,EAASC,OAAE,MAAA,CAAO;AAAA,QAChB,MAAA,EAAQA,OAAE,MAAA;AAAO,OAClB;AAAA,KACH;AAAA,IACA,OAAA,EAASA,OAAE,MAAA,CAAO;AAAA,MAChB,MAAA,EAAQA,OAAE,MAAA,EAAO;AAAA,MACjB,QAAA,EAAUA,OAAE,MAAA,EAAO;AAAA,MACnB,SAAA,EAAWA,OAAE,MAAA;AAAO,KACrB;AAAA;AAEL,CAAC;;;ACfM,IAAM,aAAA,GACX;AAUF,eAAsB,UAAA,CACpB,MAAA,EACA,KAAA,EACA,QAAA,EACqB;AACrB,EAAA,MAAM,QAAoB,EAAC;AAC3B,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI,OAAA,GAAU,IAAA;AACd,EAAA,OAAO,OAAA,EAAS;AACd,IAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,QAAA,CAAS,EAAE,OAAO,QAAA,EAAU,MAAA,EAAQ,MAAA,IAAU,MAAA,EAAW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,CAAA;AACH","file":"index.cjs","sourcesContent":["import { Method, z } from 'mppx';\n\nexport const suiCharge = Method.from({\n intent: 'charge',\n name: 'sui',\n schema: {\n credential: {\n payload: z.object({\n digest: z.string(),\n }),\n },\n request: z.object({\n amount: z.string(),\n currency: z.string(),\n recipient: z.string(),\n }),\n },\n});\n","import type { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';\n\nexport const SUI_USDC_TYPE =\n '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC';\n\n/**\n * Fetch ALL coins of a given type, handling Sui pagination (max 50 per page).\n */\nexport interface CoinInfo {\n coinObjectId: string;\n balance: string;\n}\n\nexport async function fetchCoins(\n client: SuiJsonRpcClient,\n owner: string,\n coinType: string,\n): Promise<CoinInfo[]> {\n const coins: CoinInfo[] = [];\n let cursor: string | null | undefined;\n let hasNext = true;\n while (hasNext) {\n const page = await client.getCoins({ owner, coinType, cursor: cursor ?? undefined });\n coins.push(...page.data.map((c) => ({ coinObjectId: c.coinObjectId, balance: c.balance })));\n cursor = page.nextCursor;\n hasNext = page.hasNextPage;\n }\n return coins;\n}\n\n/**\n * Parse a string amount to raw bigint units without floating-point math.\n * \"0.01\" with 6 decimals → 10000n\n */\nexport function parseAmountToRaw(amount: string, decimals: number): bigint {\n const [whole = '0', frac = ''] = amount.split('.');\n const paddedFrac = frac.padEnd(decimals, '0').slice(0, decimals);\n return BigInt(whole + paddedFrac);\n}\n","import { Method, Credential } from 'mppx';\nimport type { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';\nimport type { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { suiCharge } from './method.js';\nimport { fetchCoins, parseAmountToRaw } from './utils.js';\n\nexport { suiCharge } from './method.js';\nexport { SUI_USDC_TYPE } from './utils.js';\n\nexport interface SuiChargeOptions {\n client: SuiJsonRpcClient;\n signer: Ed25519Keypair;\n}\n\nexport function sui(options: SuiChargeOptions) {\n const address = options.signer.getPublicKey().toSuiAddress();\n\n return Method.toClient(suiCharge, {\n async createCredential({ challenge }) {\n const { amount, currency, recipient } = challenge.request;\n const amountRaw = parseAmountToRaw(amount, 6);\n\n const coins = await fetchCoins(options.client, address, currency);\n if (coins.length === 0) {\n throw new Error(\n `No ${currency.split('::').pop()} balance to pay with`,\n );\n }\n\n const totalBalance = coins.reduce(\n (sum, c) => sum + BigInt(c.balance),\n 0n,\n );\n if (totalBalance < amountRaw) {\n const available = Number(totalBalance) / 1e6;\n const requested = Number(amountRaw) / 1e6;\n throw new Error(\n `Not enough USDC to pay $${requested.toFixed(2)} (available: $${available.toFixed(2)})`,\n );\n }\n\n const tx = new Transaction();\n tx.setSender(address);\n\n const primaryCoin = tx.object(coins[0].coinObjectId);\n if (coins.length > 1) {\n tx.mergeCoins(\n primaryCoin,\n coins.slice(1).map((c) => tx.object(c.coinObjectId)),\n );\n }\n\n const [payment] = tx.splitCoins(primaryCoin, [amountRaw]);\n tx.transferObjects([payment], recipient);\n\n let result;\n try {\n result = await options.client.signAndExecuteTransaction({\n signer: options.signer,\n transaction: tx,\n options: { showEffects: true },\n });\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Payment transaction failed: ${msg}`);\n }\n\n return Credential.serialize({\n challenge,\n payload: { digest: result.digest },\n });\n },\n });\n}\n","import { Method, Receipt } from 'mppx';\nimport { SuiJsonRpcClient, getJsonRpcFullnodeUrl } from '@mysten/sui/jsonRpc';\nimport { normalizeSuiAddress } from '@mysten/sui/utils';\nimport { suiCharge } from './method.js';\nimport { parseAmountToRaw } from './utils.js';\n\nexport { suiCharge } from './method.js';\nexport { SUI_USDC_TYPE } from './utils.js';\n\nexport interface SuiServerOptions {\n currency: string;\n recipient: string;\n rpcUrl?: string;\n network?: 'mainnet' | 'testnet' | 'devnet';\n}\n\nexport function sui(options: SuiServerOptions) {\n const network = options.network ?? 'mainnet';\n const client = new SuiJsonRpcClient({\n url: options.rpcUrl ?? getJsonRpcFullnodeUrl(network),\n network,\n });\n\n const normalizedRecipient = normalizeSuiAddress(options.recipient);\n\n return Method.toServer(suiCharge, {\n defaults: {\n currency: options.currency,\n recipient: options.recipient,\n },\n\n async verify({ credential }) {\n const tx = await client.getTransactionBlock({\n digest: credential.payload.digest,\n options: { showEffects: true, showBalanceChanges: true },\n });\n\n if (tx.effects?.status?.status !== 'success') {\n throw new Error('Transaction failed on-chain');\n }\n\n const payment = (tx.balanceChanges ?? []).find(\n (bc: { coinType: string; owner: unknown; amount: string }) =>\n bc.coinType === options.currency &&\n typeof bc.owner === 'object' &&\n bc.owner !== null &&\n 'AddressOwner' in bc.owner &&\n normalizeSuiAddress((bc.owner as { AddressOwner: string }).AddressOwner) === normalizedRecipient &&\n Number(bc.amount) > 0,\n );\n\n if (!payment) {\n throw new Error(\n 'Payment not found in transaction balance changes',\n );\n }\n\n const transferredRaw = BigInt(payment.amount);\n const requestedRaw = parseAmountToRaw(credential.challenge.request.amount, 6);\n if (transferredRaw < requestedRaw) {\n throw new Error(\n `Transferred ${transferredRaw} < requested ${requestedRaw} (raw units)`,\n );\n }\n\n return Receipt.from({\n method: 'sui',\n reference: credential.payload.digest,\n status: 'success',\n timestamp: new Date().toISOString(),\n });\n },\n });\n}\n"]}
@@ -0,0 +1,8 @@
1
+ export { S as SUI_USDC_TYPE, f as fetchCoins, p as parseAmountToRaw, s as suiCharge } from './utils-CzBi2QXm.cjs';
2
+ export { SuiChargeOptions, sui as suiClient } from './client.cjs';
3
+ export { SuiServerOptions, sui as suiServer } from './server.cjs';
4
+ import 'mppx';
5
+ import '@mysten/sui/jsonRpc';
6
+ import 'zod/v4/core';
7
+ import 'zod/mini';
8
+ import '@mysten/sui/keypairs/ed25519';
@@ -0,0 +1,8 @@
1
+ export { S as SUI_USDC_TYPE, f as fetchCoins, p as parseAmountToRaw, s as suiCharge } from './utils-CzBi2QXm.js';
2
+ export { SuiChargeOptions, sui as suiClient } from './client.js';
3
+ export { SuiServerOptions, sui as suiServer } from './server.js';
4
+ import 'mppx';
5
+ import '@mysten/sui/jsonRpc';
6
+ import 'zod/v4/core';
7
+ import 'zod/mini';
8
+ import '@mysten/sui/keypairs/ed25519';
package/dist/index.js ADDED
@@ -0,0 +1,144 @@
1
+ import { Method, z, Credential, Receipt } from 'mppx';
2
+ import { Transaction } from '@mysten/sui/transactions';
3
+ import { SuiJsonRpcClient, getJsonRpcFullnodeUrl } from '@mysten/sui/jsonRpc';
4
+ import { normalizeSuiAddress } from '@mysten/sui/utils';
5
+
6
+ // src/method.ts
7
+ var suiCharge = Method.from({
8
+ intent: "charge",
9
+ name: "sui",
10
+ schema: {
11
+ credential: {
12
+ payload: z.object({
13
+ digest: z.string()
14
+ })
15
+ },
16
+ request: z.object({
17
+ amount: z.string(),
18
+ currency: z.string(),
19
+ recipient: z.string()
20
+ })
21
+ }
22
+ });
23
+
24
+ // src/utils.ts
25
+ var SUI_USDC_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
26
+ async function fetchCoins(client, owner, coinType) {
27
+ const coins = [];
28
+ let cursor;
29
+ let hasNext = true;
30
+ while (hasNext) {
31
+ const page = await client.getCoins({ owner, coinType, cursor: cursor ?? void 0 });
32
+ coins.push(...page.data.map((c) => ({ coinObjectId: c.coinObjectId, balance: c.balance })));
33
+ cursor = page.nextCursor;
34
+ hasNext = page.hasNextPage;
35
+ }
36
+ return coins;
37
+ }
38
+ function parseAmountToRaw(amount, decimals) {
39
+ const [whole = "0", frac = ""] = amount.split(".");
40
+ const paddedFrac = frac.padEnd(decimals, "0").slice(0, decimals);
41
+ return BigInt(whole + paddedFrac);
42
+ }
43
+
44
+ // src/client.ts
45
+ function sui(options) {
46
+ const address = options.signer.getPublicKey().toSuiAddress();
47
+ return Method.toClient(suiCharge, {
48
+ async createCredential({ challenge }) {
49
+ const { amount, currency, recipient } = challenge.request;
50
+ const amountRaw = parseAmountToRaw(amount, 6);
51
+ const coins = await fetchCoins(options.client, address, currency);
52
+ if (coins.length === 0) {
53
+ throw new Error(
54
+ `No ${currency.split("::").pop()} balance to pay with`
55
+ );
56
+ }
57
+ const totalBalance = coins.reduce(
58
+ (sum, c) => sum + BigInt(c.balance),
59
+ 0n
60
+ );
61
+ if (totalBalance < amountRaw) {
62
+ const available = Number(totalBalance) / 1e6;
63
+ const requested = Number(amountRaw) / 1e6;
64
+ throw new Error(
65
+ `Not enough USDC to pay $${requested.toFixed(2)} (available: $${available.toFixed(2)})`
66
+ );
67
+ }
68
+ const tx = new Transaction();
69
+ tx.setSender(address);
70
+ const primaryCoin = tx.object(coins[0].coinObjectId);
71
+ if (coins.length > 1) {
72
+ tx.mergeCoins(
73
+ primaryCoin,
74
+ coins.slice(1).map((c) => tx.object(c.coinObjectId))
75
+ );
76
+ }
77
+ const [payment] = tx.splitCoins(primaryCoin, [amountRaw]);
78
+ tx.transferObjects([payment], recipient);
79
+ let result;
80
+ try {
81
+ result = await options.client.signAndExecuteTransaction({
82
+ signer: options.signer,
83
+ transaction: tx,
84
+ options: { showEffects: true }
85
+ });
86
+ } catch (err) {
87
+ const msg = err instanceof Error ? err.message : String(err);
88
+ throw new Error(`Payment transaction failed: ${msg}`);
89
+ }
90
+ return Credential.serialize({
91
+ challenge,
92
+ payload: { digest: result.digest }
93
+ });
94
+ }
95
+ });
96
+ }
97
+ function sui2(options) {
98
+ const network = options.network ?? "mainnet";
99
+ const client = new SuiJsonRpcClient({
100
+ url: options.rpcUrl ?? getJsonRpcFullnodeUrl(network),
101
+ network
102
+ });
103
+ const normalizedRecipient = normalizeSuiAddress(options.recipient);
104
+ return Method.toServer(suiCharge, {
105
+ defaults: {
106
+ currency: options.currency,
107
+ recipient: options.recipient
108
+ },
109
+ async verify({ credential }) {
110
+ const tx = await client.getTransactionBlock({
111
+ digest: credential.payload.digest,
112
+ options: { showEffects: true, showBalanceChanges: true }
113
+ });
114
+ if (tx.effects?.status?.status !== "success") {
115
+ throw new Error("Transaction failed on-chain");
116
+ }
117
+ const payment = (tx.balanceChanges ?? []).find(
118
+ (bc) => bc.coinType === options.currency && typeof bc.owner === "object" && bc.owner !== null && "AddressOwner" in bc.owner && normalizeSuiAddress(bc.owner.AddressOwner) === normalizedRecipient && Number(bc.amount) > 0
119
+ );
120
+ if (!payment) {
121
+ throw new Error(
122
+ "Payment not found in transaction balance changes"
123
+ );
124
+ }
125
+ const transferredRaw = BigInt(payment.amount);
126
+ const requestedRaw = parseAmountToRaw(credential.challenge.request.amount, 6);
127
+ if (transferredRaw < requestedRaw) {
128
+ throw new Error(
129
+ `Transferred ${transferredRaw} < requested ${requestedRaw} (raw units)`
130
+ );
131
+ }
132
+ return Receipt.from({
133
+ method: "sui",
134
+ reference: credential.payload.digest,
135
+ status: "success",
136
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
137
+ });
138
+ }
139
+ });
140
+ }
141
+
142
+ export { SUI_USDC_TYPE, fetchCoins, parseAmountToRaw, suiCharge, sui as suiClient, sui2 as suiServer };
143
+ //# sourceMappingURL=index.js.map
144
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/method.ts","../src/utils.ts","../src/client.ts","../src/server.ts"],"names":["Method","sui"],"mappings":";;;;;;AAEO,IAAM,SAAA,GAAY,OAAO,IAAA,CAAK;AAAA,EACnC,MAAA,EAAQ,QAAA;AAAA,EACR,IAAA,EAAM,KAAA;AAAA,EACN,MAAA,EAAQ;AAAA,IACN,UAAA,EAAY;AAAA,MACV,OAAA,EAAS,EAAE,MAAA,CAAO;AAAA,QAChB,MAAA,EAAQ,EAAE,MAAA;AAAO,OAClB;AAAA,KACH;AAAA,IACA,OAAA,EAAS,EAAE,MAAA,CAAO;AAAA,MAChB,MAAA,EAAQ,EAAE,MAAA,EAAO;AAAA,MACjB,QAAA,EAAU,EAAE,MAAA,EAAO;AAAA,MACnB,SAAA,EAAW,EAAE,MAAA;AAAO,KACrB;AAAA;AAEL,CAAC;;;ACfM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AA,aAAA,EAAgB,YAAY,CAAA,YAAA;AAAA,SAC3D;AAAA,MACF;AAEA,MAAA,OAAO,QAAQ,IAAA,CAAK;AAAA,QAClB,MAAA,EAAQ,KAAA;AAAA,QACR,SAAA,EAAW,WAAW,OAAA,CAAQ,MAAA;AAAA,QAC9B,MAAA,EAAQ,SAAA;AAAA,QACR,SAAA,EAAA,iBAAW,IAAI,IAAA,EAAK,EAAE,WAAA;AAAY,OACnC,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH","file":"index.js","sourcesContent":["import { Method, z } from 'mppx';\n\nexport const suiCharge = Method.from({\n intent: 'charge',\n name: 'sui',\n schema: {\n credential: {\n payload: z.object({\n digest: z.string(),\n }),\n },\n request: z.object({\n amount: z.string(),\n currency: z.string(),\n recipient: z.string(),\n }),\n },\n});\n","import type { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';\n\nexport const SUI_USDC_TYPE =\n '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC';\n\n/**\n * Fetch ALL coins of a given type, handling Sui pagination (max 50 per page).\n */\nexport interface CoinInfo {\n coinObjectId: string;\n balance: string;\n}\n\nexport async function fetchCoins(\n client: SuiJsonRpcClient,\n owner: string,\n coinType: string,\n): Promise<CoinInfo[]> {\n const coins: CoinInfo[] = [];\n let cursor: string | null | undefined;\n let hasNext = true;\n while (hasNext) {\n const page = await client.getCoins({ owner, coinType, cursor: cursor ?? undefined });\n coins.push(...page.data.map((c) => ({ coinObjectId: c.coinObjectId, balance: c.balance })));\n cursor = page.nextCursor;\n hasNext = page.hasNextPage;\n }\n return coins;\n}\n\n/**\n * Parse a string amount to raw bigint units without floating-point math.\n * \"0.01\" with 6 decimals → 10000n\n */\nexport function parseAmountToRaw(amount: string, decimals: number): bigint {\n const [whole = '0', frac = ''] = amount.split('.');\n const paddedFrac = frac.padEnd(decimals, '0').slice(0, decimals);\n return BigInt(whole + paddedFrac);\n}\n","import { Method, Credential } from 'mppx';\nimport type { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';\nimport type { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { suiCharge } from './method.js';\nimport { fetchCoins, parseAmountToRaw } from './utils.js';\n\nexport { suiCharge } from './method.js';\nexport { SUI_USDC_TYPE } from './utils.js';\n\nexport interface SuiChargeOptions {\n client: SuiJsonRpcClient;\n signer: Ed25519Keypair;\n}\n\nexport function sui(options: SuiChargeOptions) {\n const address = options.signer.getPublicKey().toSuiAddress();\n\n return Method.toClient(suiCharge, {\n async createCredential({ challenge }) {\n const { amount, currency, recipient } = challenge.request;\n const amountRaw = parseAmountToRaw(amount, 6);\n\n const coins = await fetchCoins(options.client, address, currency);\n if (coins.length === 0) {\n throw new Error(\n `No ${currency.split('::').pop()} balance to pay with`,\n );\n }\n\n const totalBalance = coins.reduce(\n (sum, c) => sum + BigInt(c.balance),\n 0n,\n );\n if (totalBalance < amountRaw) {\n const available = Number(totalBalance) / 1e6;\n const requested = Number(amountRaw) / 1e6;\n throw new Error(\n `Not enough USDC to pay $${requested.toFixed(2)} (available: $${available.toFixed(2)})`,\n );\n }\n\n const tx = new Transaction();\n tx.setSender(address);\n\n const primaryCoin = tx.object(coins[0].coinObjectId);\n if (coins.length > 1) {\n tx.mergeCoins(\n primaryCoin,\n coins.slice(1).map((c) => tx.object(c.coinObjectId)),\n );\n }\n\n const [payment] = tx.splitCoins(primaryCoin, [amountRaw]);\n tx.transferObjects([payment], recipient);\n\n let result;\n try {\n result = await options.client.signAndExecuteTransaction({\n signer: options.signer,\n transaction: tx,\n options: { showEffects: true },\n });\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Payment transaction failed: ${msg}`);\n }\n\n return Credential.serialize({\n challenge,\n payload: { digest: result.digest },\n });\n },\n });\n}\n","import { Method, Receipt } from 'mppx';\nimport { SuiJsonRpcClient, getJsonRpcFullnodeUrl } from '@mysten/sui/jsonRpc';\nimport { normalizeSuiAddress } from '@mysten/sui/utils';\nimport { suiCharge } from './method.js';\nimport { parseAmountToRaw } from './utils.js';\n\nexport { suiCharge } from './method.js';\nexport { SUI_USDC_TYPE } from './utils.js';\n\nexport interface SuiServerOptions {\n currency: string;\n recipient: string;\n rpcUrl?: string;\n network?: 'mainnet' | 'testnet' | 'devnet';\n}\n\nexport function sui(options: SuiServerOptions) {\n const network = options.network ?? 'mainnet';\n const client = new SuiJsonRpcClient({\n url: options.rpcUrl ?? getJsonRpcFullnodeUrl(network),\n network,\n });\n\n const normalizedRecipient = normalizeSuiAddress(options.recipient);\n\n return Method.toServer(suiCharge, {\n defaults: {\n currency: options.currency,\n recipient: options.recipient,\n },\n\n async verify({ credential }) {\n const tx = await client.getTransactionBlock({\n digest: credential.payload.digest,\n options: { showEffects: true, showBalanceChanges: true },\n });\n\n if (tx.effects?.status?.status !== 'success') {\n throw new Error('Transaction failed on-chain');\n }\n\n const payment = (tx.balanceChanges ?? []).find(\n (bc: { coinType: string; owner: unknown; amount: string }) =>\n bc.coinType === options.currency &&\n typeof bc.owner === 'object' &&\n bc.owner !== null &&\n 'AddressOwner' in bc.owner &&\n normalizeSuiAddress((bc.owner as { AddressOwner: string }).AddressOwner) === normalizedRecipient &&\n Number(bc.amount) > 0,\n );\n\n if (!payment) {\n throw new Error(\n 'Payment not found in transaction balance changes',\n );\n }\n\n const transferredRaw = BigInt(payment.amount);\n const requestedRaw = parseAmountToRaw(credential.challenge.request.amount, 6);\n if (transferredRaw < requestedRaw) {\n throw new Error(\n `Transferred ${transferredRaw} < requested ${requestedRaw} (raw units)`,\n );\n }\n\n return Receipt.from({\n method: 'sui',\n reference: credential.payload.digest,\n status: 'success',\n timestamp: new Date().toISOString(),\n });\n },\n });\n}\n"]}
@@ -0,0 +1,83 @@
1
+ 'use strict';
2
+
3
+ var mppx = require('mppx');
4
+ var jsonRpc = require('@mysten/sui/jsonRpc');
5
+ var utils = require('@mysten/sui/utils');
6
+
7
+ // src/server.ts
8
+ var suiCharge = mppx.Method.from({
9
+ intent: "charge",
10
+ name: "sui",
11
+ schema: {
12
+ credential: {
13
+ payload: mppx.z.object({
14
+ digest: mppx.z.string()
15
+ })
16
+ },
17
+ request: mppx.z.object({
18
+ amount: mppx.z.string(),
19
+ currency: mppx.z.string(),
20
+ recipient: mppx.z.string()
21
+ })
22
+ }
23
+ });
24
+
25
+ // src/utils.ts
26
+ var SUI_USDC_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
27
+ function parseAmountToRaw(amount, decimals) {
28
+ const [whole = "0", frac = ""] = amount.split(".");
29
+ const paddedFrac = frac.padEnd(decimals, "0").slice(0, decimals);
30
+ return BigInt(whole + paddedFrac);
31
+ }
32
+
33
+ // src/server.ts
34
+ function sui(options) {
35
+ const network = options.network ?? "mainnet";
36
+ const client = new jsonRpc.SuiJsonRpcClient({
37
+ url: options.rpcUrl ?? jsonRpc.getJsonRpcFullnodeUrl(network),
38
+ network
39
+ });
40
+ const normalizedRecipient = utils.normalizeSuiAddress(options.recipient);
41
+ return mppx.Method.toServer(suiCharge, {
42
+ defaults: {
43
+ currency: options.currency,
44
+ recipient: options.recipient
45
+ },
46
+ async verify({ credential }) {
47
+ const tx = await client.getTransactionBlock({
48
+ digest: credential.payload.digest,
49
+ options: { showEffects: true, showBalanceChanges: true }
50
+ });
51
+ if (tx.effects?.status?.status !== "success") {
52
+ throw new Error("Transaction failed on-chain");
53
+ }
54
+ const payment = (tx.balanceChanges ?? []).find(
55
+ (bc) => bc.coinType === options.currency && typeof bc.owner === "object" && bc.owner !== null && "AddressOwner" in bc.owner && utils.normalizeSuiAddress(bc.owner.AddressOwner) === normalizedRecipient && Number(bc.amount) > 0
56
+ );
57
+ if (!payment) {
58
+ throw new Error(
59
+ "Payment not found in transaction balance changes"
60
+ );
61
+ }
62
+ const transferredRaw = BigInt(payment.amount);
63
+ const requestedRaw = parseAmountToRaw(credential.challenge.request.amount, 6);
64
+ if (transferredRaw < requestedRaw) {
65
+ throw new Error(
66
+ `Transferred ${transferredRaw} < requested ${requestedRaw} (raw units)`
67
+ );
68
+ }
69
+ return mppx.Receipt.from({
70
+ method: "sui",
71
+ reference: credential.payload.digest,
72
+ status: "success",
73
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
74
+ });
75
+ }
76
+ });
77
+ }
78
+
79
+ exports.SUI_USDC_TYPE = SUI_USDC_TYPE;
80
+ exports.sui = sui;
81
+ exports.suiCharge = suiCharge;
82
+ //# sourceMappingURL=server.cjs.map
83
+ //# sourceMappingURL=server.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/method.ts","../src/utils.ts","../src/server.ts"],"names":["Method","z","SuiJsonRpcClient","getJsonRpcFullnodeUrl","normalizeSuiAddress","Receipt"],"mappings":";;;;;;;AAEO,IAAM,SAAA,GAAYA,YAAO,IAAA,CAAK;AAAA,EACnC,MAAA,EAAQ,QAAA;AAAA,EACR,IAAA,EAAM,KAAA;AAAA,EACN,MAAA,EAAQ;AAAA,IACN,UAAA,EAAY;AAAA,MACV,OAAA,EAASC,OAAE,MAAA,CAAO;AAAA,QAChB,MAAA,EAAQA,OAAE,MAAA;AAAO,OAClB;AAAA,KACH;AAAA,IACA,OAAA,EAASA,OAAE,MAAA,CAAO;AAAA,MAChB,MAAA,EAAQA,OAAE,MAAA,EAAO;AAAA,MACjB,QAAA,EAAUA,OAAE,MAAA,EAAO;AAAA,MACnB,SAAA,EAAWA,OAAE,MAAA;AAAO,KACrB;AAAA;AAEL,CAAC;;;ACfM,IAAM,aAAA,GACX;AA+BK,SAAS,gBAAA,CAAiB,QAAgB,QAAA,EAA0B;AACzE,EAAA,MAAM,CAAC,QAAQ,GAAA,EAAK,IAAA,GAAO,EAAE,CAAA,GAAI,MAAA,CAAO,MAAM,GAAG,CAAA;AACjD,EAAA,MAAM,UAAA,GAAa,KAAK,MAAA,CAAO,QAAA,EAAU,GAAG,CAAA,CAAE,KAAA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AAA,CAAG,KAAA,CAAmC,YAAY,CAAA,KAAM,mBAAA,IAC7E,MAAA,CAAO,EAAA,CAAG,MAAM,CAAA,GAAI;AAAA,OACxB;AAEA,MAAA,IAAI,CAAC,OAAA,EAAS;AACZ,QAAA,MAAM,IAAI,KAAA;AAAA,UACR;AAAA,SACF;AAAA,MACF;AAEA,MAAA,MAAM,cAAA,GAAiB,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA;AAC5C,MAAA,MAAM,eAAe,gBAAA,CAAiB,UAAA,CAAW,SAAA,CAAU,OAAA,CAAQ,QAAQ,CAAC,CAAA;AAC5E,MAAA,IAAI,iBAAiB,YAAA,EAAc;AACjC,QAAA,MAAM,IAAI,KAAA;AAAA,UACR,CAAA,YAAA,EAAe,cAAc,CAAA,aAAA,EAAgB,YAAY,CAAA,YAAA;AAAA,SAC3D;AAAA,MACF;AAEA,MAAA,OAAOC,aAAQ,IAAA,CAAK;AAAA,QAClB,MAAA,EAAQ,KAAA;AAAA,QACR,SAAA,EAAW,WAAW,OAAA,CAAQ,MAAA;AAAA,QAC9B,MAAA,EAAQ,SAAA;AAAA,QACR,SAAA,EAAA,iBAAW,IAAI,IAAA,EAAK,EAAE,WAAA;AAAY,OACnC,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH","file":"server.cjs","sourcesContent":["import { Method, z } from 'mppx';\n\nexport const suiCharge = Method.from({\n intent: 'charge',\n name: 'sui',\n schema: {\n credential: {\n payload: z.object({\n digest: z.string(),\n }),\n },\n request: z.object({\n amount: z.string(),\n currency: z.string(),\n recipient: z.string(),\n }),\n },\n});\n","import type { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';\n\nexport const SUI_USDC_TYPE =\n '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC';\n\n/**\n * Fetch ALL coins of a given type, handling Sui pagination (max 50 per page).\n */\nexport interface CoinInfo {\n coinObjectId: string;\n balance: string;\n}\n\nexport async function fetchCoins(\n client: SuiJsonRpcClient,\n owner: string,\n coinType: string,\n): Promise<CoinInfo[]> {\n const coins: CoinInfo[] = [];\n let cursor: string | null | undefined;\n let hasNext = true;\n while (hasNext) {\n const page = await client.getCoins({ owner, coinType, cursor: cursor ?? undefined });\n coins.push(...page.data.map((c) => ({ coinObjectId: c.coinObjectId, balance: c.balance })));\n cursor = page.nextCursor;\n hasNext = page.hasNextPage;\n }\n return coins;\n}\n\n/**\n * Parse a string amount to raw bigint units without floating-point math.\n * \"0.01\" with 6 decimals → 10000n\n */\nexport function parseAmountToRaw(amount: string, decimals: number): bigint {\n const [whole = '0', frac = ''] = amount.split('.');\n const paddedFrac = frac.padEnd(decimals, '0').slice(0, decimals);\n return BigInt(whole + paddedFrac);\n}\n","import { Method, Receipt } from 'mppx';\nimport { SuiJsonRpcClient, getJsonRpcFullnodeUrl } from '@mysten/sui/jsonRpc';\nimport { normalizeSuiAddress } from '@mysten/sui/utils';\nimport { suiCharge } from './method.js';\nimport { parseAmountToRaw } from './utils.js';\n\nexport { suiCharge } from './method.js';\nexport { SUI_USDC_TYPE } from './utils.js';\n\nexport interface SuiServerOptions {\n currency: string;\n recipient: string;\n rpcUrl?: string;\n network?: 'mainnet' | 'testnet' | 'devnet';\n}\n\nexport function sui(options: SuiServerOptions) {\n const network = options.network ?? 'mainnet';\n const client = new SuiJsonRpcClient({\n url: options.rpcUrl ?? getJsonRpcFullnodeUrl(network),\n network,\n });\n\n const normalizedRecipient = normalizeSuiAddress(options.recipient);\n\n return Method.toServer(suiCharge, {\n defaults: {\n currency: options.currency,\n recipient: options.recipient,\n },\n\n async verify({ credential }) {\n const tx = await client.getTransactionBlock({\n digest: credential.payload.digest,\n options: { showEffects: true, showBalanceChanges: true },\n });\n\n if (tx.effects?.status?.status !== 'success') {\n throw new Error('Transaction failed on-chain');\n }\n\n const payment = (tx.balanceChanges ?? []).find(\n (bc: { coinType: string; owner: unknown; amount: string }) =>\n bc.coinType === options.currency &&\n typeof bc.owner === 'object' &&\n bc.owner !== null &&\n 'AddressOwner' in bc.owner &&\n normalizeSuiAddress((bc.owner as { AddressOwner: string }).AddressOwner) === normalizedRecipient &&\n Number(bc.amount) > 0,\n );\n\n if (!payment) {\n throw new Error(\n 'Payment not found in transaction balance changes',\n );\n }\n\n const transferredRaw = BigInt(payment.amount);\n const requestedRaw = parseAmountToRaw(credential.challenge.request.amount, 6);\n if (transferredRaw < requestedRaw) {\n throw new Error(\n `Transferred ${transferredRaw} < requested ${requestedRaw} (raw units)`,\n );\n }\n\n return Receipt.from({\n method: 'sui',\n reference: credential.payload.digest,\n status: 'success',\n timestamp: new Date().toISOString(),\n });\n },\n });\n}\n"]}
@@ -0,0 +1,33 @@
1
+ import * as zod_v4_core from 'zod/v4/core';
2
+ import * as zod_mini from 'zod/mini';
3
+ import { Method } from 'mppx';
4
+ export { S as SUI_USDC_TYPE, s as suiCharge } from './utils-CzBi2QXm.cjs';
5
+ import '@mysten/sui/jsonRpc';
6
+
7
+ interface SuiServerOptions {
8
+ currency: string;
9
+ recipient: string;
10
+ rpcUrl?: string;
11
+ network?: 'mainnet' | 'testnet' | 'devnet';
12
+ }
13
+ declare function sui(options: SuiServerOptions): Method.Server<{
14
+ readonly intent: "charge";
15
+ readonly name: "sui";
16
+ readonly schema: {
17
+ readonly credential: {
18
+ readonly payload: zod_mini.ZodMiniObject<{
19
+ digest: zod_mini.ZodMiniString<string>;
20
+ }, zod_v4_core.$strip>;
21
+ };
22
+ readonly request: zod_mini.ZodMiniObject<{
23
+ amount: zod_mini.ZodMiniString<string>;
24
+ currency: zod_mini.ZodMiniString<string>;
25
+ recipient: zod_mini.ZodMiniString<string>;
26
+ }, zod_v4_core.$strip>;
27
+ };
28
+ }, {
29
+ readonly currency: string;
30
+ readonly recipient: string;
31
+ }, undefined>;
32
+
33
+ export { type SuiServerOptions, sui };
@@ -0,0 +1,33 @@
1
+ import * as zod_v4_core from 'zod/v4/core';
2
+ import * as zod_mini from 'zod/mini';
3
+ import { Method } from 'mppx';
4
+ export { S as SUI_USDC_TYPE, s as suiCharge } from './utils-CzBi2QXm.js';
5
+ import '@mysten/sui/jsonRpc';
6
+
7
+ interface SuiServerOptions {
8
+ currency: string;
9
+ recipient: string;
10
+ rpcUrl?: string;
11
+ network?: 'mainnet' | 'testnet' | 'devnet';
12
+ }
13
+ declare function sui(options: SuiServerOptions): Method.Server<{
14
+ readonly intent: "charge";
15
+ readonly name: "sui";
16
+ readonly schema: {
17
+ readonly credential: {
18
+ readonly payload: zod_mini.ZodMiniObject<{
19
+ digest: zod_mini.ZodMiniString<string>;
20
+ }, zod_v4_core.$strip>;
21
+ };
22
+ readonly request: zod_mini.ZodMiniObject<{
23
+ amount: zod_mini.ZodMiniString<string>;
24
+ currency: zod_mini.ZodMiniString<string>;
25
+ recipient: zod_mini.ZodMiniString<string>;
26
+ }, zod_v4_core.$strip>;
27
+ };
28
+ }, {
29
+ readonly currency: string;
30
+ readonly recipient: string;
31
+ }, undefined>;
32
+
33
+ export { type SuiServerOptions, sui };
package/dist/server.js ADDED
@@ -0,0 +1,79 @@
1
+ import { Method, z, Receipt } from 'mppx';
2
+ import { SuiJsonRpcClient, getJsonRpcFullnodeUrl } from '@mysten/sui/jsonRpc';
3
+ import { normalizeSuiAddress } from '@mysten/sui/utils';
4
+
5
+ // src/server.ts
6
+ var suiCharge = Method.from({
7
+ intent: "charge",
8
+ name: "sui",
9
+ schema: {
10
+ credential: {
11
+ payload: z.object({
12
+ digest: z.string()
13
+ })
14
+ },
15
+ request: z.object({
16
+ amount: z.string(),
17
+ currency: z.string(),
18
+ recipient: z.string()
19
+ })
20
+ }
21
+ });
22
+
23
+ // src/utils.ts
24
+ var SUI_USDC_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
25
+ function parseAmountToRaw(amount, decimals) {
26
+ const [whole = "0", frac = ""] = amount.split(".");
27
+ const paddedFrac = frac.padEnd(decimals, "0").slice(0, decimals);
28
+ return BigInt(whole + paddedFrac);
29
+ }
30
+
31
+ // src/server.ts
32
+ function sui(options) {
33
+ const network = options.network ?? "mainnet";
34
+ const client = new SuiJsonRpcClient({
35
+ url: options.rpcUrl ?? getJsonRpcFullnodeUrl(network),
36
+ network
37
+ });
38
+ const normalizedRecipient = normalizeSuiAddress(options.recipient);
39
+ return Method.toServer(suiCharge, {
40
+ defaults: {
41
+ currency: options.currency,
42
+ recipient: options.recipient
43
+ },
44
+ async verify({ credential }) {
45
+ const tx = await client.getTransactionBlock({
46
+ digest: credential.payload.digest,
47
+ options: { showEffects: true, showBalanceChanges: true }
48
+ });
49
+ if (tx.effects?.status?.status !== "success") {
50
+ throw new Error("Transaction failed on-chain");
51
+ }
52
+ const payment = (tx.balanceChanges ?? []).find(
53
+ (bc) => bc.coinType === options.currency && typeof bc.owner === "object" && bc.owner !== null && "AddressOwner" in bc.owner && normalizeSuiAddress(bc.owner.AddressOwner) === normalizedRecipient && Number(bc.amount) > 0
54
+ );
55
+ if (!payment) {
56
+ throw new Error(
57
+ "Payment not found in transaction balance changes"
58
+ );
59
+ }
60
+ const transferredRaw = BigInt(payment.amount);
61
+ const requestedRaw = parseAmountToRaw(credential.challenge.request.amount, 6);
62
+ if (transferredRaw < requestedRaw) {
63
+ throw new Error(
64
+ `Transferred ${transferredRaw} < requested ${requestedRaw} (raw units)`
65
+ );
66
+ }
67
+ return Receipt.from({
68
+ method: "sui",
69
+ reference: credential.payload.digest,
70
+ status: "success",
71
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
72
+ });
73
+ }
74
+ });
75
+ }
76
+
77
+ export { SUI_USDC_TYPE, sui, suiCharge };
78
+ //# sourceMappingURL=server.js.map
79
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/method.ts","../src/utils.ts","../src/server.ts"],"names":["Method"],"mappings":";;;;;AAEO,IAAM,SAAA,GAAY,OAAO,IAAA,CAAK;AAAA,EACnC,MAAA,EAAQ,QAAA;AAAA,EACR,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SAAA,EAAW,WAAW,OAAA,CAAQ,MAAA;AAAA,QAC9B,MAAA,EAAQ,SAAA;AAAA,QACR,SAAA,EAAA,iBAAW,IAAI,IAAA,EAAK,EAAE,WAAA;AAAY,OACnC,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH","file":"server.js","sourcesContent":["import { Method, z } from 'mppx';\n\nexport const suiCharge = Method.from({\n intent: 'charge',\n name: 'sui',\n schema: {\n credential: {\n payload: z.object({\n digest: z.string(),\n }),\n },\n request: z.object({\n amount: z.string(),\n currency: z.string(),\n recipient: z.string(),\n }),\n },\n});\n","import type { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';\n\nexport const SUI_USDC_TYPE =\n '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC';\n\n/**\n * Fetch ALL coins of a given type, handling Sui pagination (max 50 per page).\n */\nexport interface CoinInfo {\n coinObjectId: string;\n balance: string;\n}\n\nexport async function fetchCoins(\n client: SuiJsonRpcClient,\n owner: string,\n coinType: string,\n): Promise<CoinInfo[]> {\n const coins: CoinInfo[] = [];\n let cursor: string | null | undefined;\n let hasNext = true;\n while (hasNext) {\n const page = await client.getCoins({ owner, coinType, cursor: cursor ?? undefined });\n coins.push(...page.data.map((c) => ({ coinObjectId: c.coinObjectId, balance: c.balance })));\n cursor = page.nextCursor;\n hasNext = page.hasNextPage;\n }\n return coins;\n}\n\n/**\n * Parse a string amount to raw bigint units without floating-point math.\n * \"0.01\" with 6 decimals → 10000n\n */\nexport function parseAmountToRaw(amount: string, decimals: number): bigint {\n const [whole = '0', frac = ''] = amount.split('.');\n const paddedFrac = frac.padEnd(decimals, '0').slice(0, decimals);\n return BigInt(whole + paddedFrac);\n}\n","import { Method, Receipt } from 'mppx';\nimport { SuiJsonRpcClient, getJsonRpcFullnodeUrl } from '@mysten/sui/jsonRpc';\nimport { normalizeSuiAddress } from '@mysten/sui/utils';\nimport { suiCharge } from './method.js';\nimport { parseAmountToRaw } from './utils.js';\n\nexport { suiCharge } from './method.js';\nexport { SUI_USDC_TYPE } from './utils.js';\n\nexport interface SuiServerOptions {\n currency: string;\n recipient: string;\n rpcUrl?: string;\n network?: 'mainnet' | 'testnet' | 'devnet';\n}\n\nexport function sui(options: SuiServerOptions) {\n const network = options.network ?? 'mainnet';\n const client = new SuiJsonRpcClient({\n url: options.rpcUrl ?? getJsonRpcFullnodeUrl(network),\n network,\n });\n\n const normalizedRecipient = normalizeSuiAddress(options.recipient);\n\n return Method.toServer(suiCharge, {\n defaults: {\n currency: options.currency,\n recipient: options.recipient,\n },\n\n async verify({ credential }) {\n const tx = await client.getTransactionBlock({\n digest: credential.payload.digest,\n options: { showEffects: true, showBalanceChanges: true },\n });\n\n if (tx.effects?.status?.status !== 'success') {\n throw new Error('Transaction failed on-chain');\n }\n\n const payment = (tx.balanceChanges ?? []).find(\n (bc: { coinType: string; owner: unknown; amount: string }) =>\n bc.coinType === options.currency &&\n typeof bc.owner === 'object' &&\n bc.owner !== null &&\n 'AddressOwner' in bc.owner &&\n normalizeSuiAddress((bc.owner as { AddressOwner: string }).AddressOwner) === normalizedRecipient &&\n Number(bc.amount) > 0,\n );\n\n if (!payment) {\n throw new Error(\n 'Payment not found in transaction balance changes',\n );\n }\n\n const transferredRaw = BigInt(payment.amount);\n const requestedRaw = parseAmountToRaw(credential.challenge.request.amount, 6);\n if (transferredRaw < requestedRaw) {\n throw new Error(\n `Transferred ${transferredRaw} < requested ${requestedRaw} (raw units)`,\n );\n }\n\n return Receipt.from({\n method: 'sui',\n reference: credential.payload.digest,\n status: 'success',\n timestamp: new Date().toISOString(),\n });\n },\n });\n}\n"]}
@@ -0,0 +1,36 @@
1
+ import { z } from 'mppx';
2
+ import { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';
3
+
4
+ declare const suiCharge: {
5
+ readonly intent: "charge";
6
+ readonly name: "sui";
7
+ readonly schema: {
8
+ readonly credential: {
9
+ readonly payload: z.ZodMiniObject<{
10
+ digest: z.ZodMiniString<string>;
11
+ }, z.core.$strip>;
12
+ };
13
+ readonly request: z.ZodMiniObject<{
14
+ amount: z.ZodMiniString<string>;
15
+ currency: z.ZodMiniString<string>;
16
+ recipient: z.ZodMiniString<string>;
17
+ }, z.core.$strip>;
18
+ };
19
+ };
20
+
21
+ declare const SUI_USDC_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
22
+ /**
23
+ * Fetch ALL coins of a given type, handling Sui pagination (max 50 per page).
24
+ */
25
+ interface CoinInfo {
26
+ coinObjectId: string;
27
+ balance: string;
28
+ }
29
+ declare function fetchCoins(client: SuiJsonRpcClient, owner: string, coinType: string): Promise<CoinInfo[]>;
30
+ /**
31
+ * Parse a string amount to raw bigint units without floating-point math.
32
+ * "0.01" with 6 decimals → 10000n
33
+ */
34
+ declare function parseAmountToRaw(amount: string, decimals: number): bigint;
35
+
36
+ export { SUI_USDC_TYPE as S, fetchCoins as f, parseAmountToRaw as p, suiCharge as s };
@@ -0,0 +1,36 @@
1
+ import { z } from 'mppx';
2
+ import { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';
3
+
4
+ declare const suiCharge: {
5
+ readonly intent: "charge";
6
+ readonly name: "sui";
7
+ readonly schema: {
8
+ readonly credential: {
9
+ readonly payload: z.ZodMiniObject<{
10
+ digest: z.ZodMiniString<string>;
11
+ }, z.core.$strip>;
12
+ };
13
+ readonly request: z.ZodMiniObject<{
14
+ amount: z.ZodMiniString<string>;
15
+ currency: z.ZodMiniString<string>;
16
+ recipient: z.ZodMiniString<string>;
17
+ }, z.core.$strip>;
18
+ };
19
+ };
20
+
21
+ declare const SUI_USDC_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
22
+ /**
23
+ * Fetch ALL coins of a given type, handling Sui pagination (max 50 per page).
24
+ */
25
+ interface CoinInfo {
26
+ coinObjectId: string;
27
+ balance: string;
28
+ }
29
+ declare function fetchCoins(client: SuiJsonRpcClient, owner: string, coinType: string): Promise<CoinInfo[]>;
30
+ /**
31
+ * Parse a string amount to raw bigint units without floating-point math.
32
+ * "0.01" with 6 decimals → 10000n
33
+ */
34
+ declare function parseAmountToRaw(amount: string, decimals: number): bigint;
35
+
36
+ export { SUI_USDC_TYPE as S, fetchCoins as f, parseAmountToRaw as p, suiCharge as s };
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@t2000/mpp-sui",
3
+ "version": "0.1.0",
4
+ "description": "Sui USDC payment method for the Machine Payments Protocol (MPP)",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ },
15
+ "./client": {
16
+ "types": "./dist/client.d.ts",
17
+ "import": "./dist/client.js",
18
+ "require": "./dist/client.cjs"
19
+ },
20
+ "./server": {
21
+ "types": "./dist/server.d.ts",
22
+ "import": "./dist/server.js",
23
+ "require": "./dist/server.cjs"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "README.md"
29
+ ],
30
+ "keywords": [
31
+ "mpp",
32
+ "sui",
33
+ "payment",
34
+ "usdc",
35
+ "ai",
36
+ "agent",
37
+ "402",
38
+ "machine-payments"
39
+ ],
40
+ "author": "t2000",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/mission69b/t2000.git",
44
+ "directory": "packages/mpp-sui"
45
+ },
46
+ "homepage": "https://t2000.ai/mpp",
47
+ "dependencies": {
48
+ "@mysten/sui": "^2",
49
+ "mppx": "^0.4.7",
50
+ "zod": "^4.3.6"
51
+ },
52
+ "devDependencies": {
53
+ "@types/node": "^20",
54
+ "eslint": "^9",
55
+ "tsup": "^8",
56
+ "typescript": "^5",
57
+ "vitest": "^3"
58
+ },
59
+ "license": "MIT",
60
+ "scripts": {
61
+ "build": "tsup",
62
+ "dev": "tsup --watch",
63
+ "test": "vitest run",
64
+ "test:watch": "vitest",
65
+ "typecheck": "tsc --noEmit",
66
+ "lint": "eslint src/",
67
+ "clean": "rm -rf dist"
68
+ }
69
+ }