@mysten/sui 2.33.1 → 2.34.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/docs/index.md CHANGED
@@ -50,8 +50,8 @@ The following table lists the locations for Sui networks.
50
50
  | Network | Full node | faucet |
51
51
  | ------- | ------------------------------------- | ---------------------------------------- |
52
52
  | local | `http://127.0.0.1:9000` (default) | `http://127.0.0.1:9123/v2/gas` (default) |
53
- | Devnet | `https://fullnode.devnet.sui.io:443` | `https://faucet.devnet.sui.io/v2/gas` |
54
- | Testnet | `https://fullnode.testnet.sui.io:443` | `https://faucet.testnet.sui.io/v2/gas` |
53
+ | Devnet | `https://fullnode.devnet.sui.io:443` | `https://faucet.devnet.sui.io/v3/gas` |
54
+ | Testnet | `https://fullnode.testnet.sui.io:443` | `https://faucet.testnet.sui.io/v3/gas` |
55
55
  | Mainnet | `https://fullnode.mainnet.sui.io:443` | `null` |
56
56
 
57
57
  > **Warning:** Use dedicated nodes/shared services rather than public endpoints for production apps. The public
@@ -92,7 +92,7 @@ console.log('Address:', keypair.toSuiAddress());
92
92
  console.log('Secret key:', keypair.getSecretKey());
93
93
 
94
94
  // Request SUI from the devnet faucet
95
- await requestSuiFromFaucetV2({
95
+ await requestSuiFromFaucetV3({
96
96
  host: getFaucetHost('devnet'),
97
97
  recipient: keypair.toSuiAddress(),
98
98
  });
@@ -183,17 +183,57 @@ node transfer.ts
183
183
 
184
184
  ### Faucet
185
185
 
186
- Devnet, Testnet, and local networks include faucets that mint SUI. Use `requestSuiFromFaucetV2` to
187
- request SUI programmatically:
186
+ Use `requestSuiFromFaucetV3` on Devnet and Testnet. It fetches a challenge from `/v3/challenge`,
187
+ computes Argon2d proof-of-work, and submits the proof to `/v3/gas`:
188
188
 
189
189
  ```typescript
190
190
 
191
- await requestSuiFromFaucetV2({
191
+ const result = await requestSuiFromFaucetV3({
192
192
  host: getFaucetHost('testnet'),
193
- recipient: '0xYourAddress',
193
+ recipient: '0xYourAddress', // Replace with your Sui address.
194
+ timeout: 180_000,
194
195
  });
196
+
197
+ console.log(result.digest, result.amountMist);
195
198
  ```
196
199
 
200
+ V3 credits the recipient's address balance, not a coin object. Its response contains `digest`,
201
+ `recipient`, `amountMist`, and `difficulty`; it does not contain V2's `coins_sent`. Amounts are
202
+ returned as decimal strings to preserve precision. The faucet sets the payout amount.
203
+
204
+ Set `host` to the faucet's origin (scheme, hostname, and optional port), such as
205
+ `https://faucet.testnet.sui.io`. The API must serve `/v3/challenge` and `/v3/gas` at the origin
206
+ root. Path prefixes such as `/faucet` are not supported; any path in `host` is discarded.
207
+
208
+ Optional `headers` apply to both requests. The `timeout` covers fetching, solving, and submission,
209
+ and defaults to 180,000 milliseconds. Pass an `AbortSignal` as `signal` to cancel earlier.
210
+
211
+ The helper uses Node's asynchronous native Argon2d when available (Node 24.7 or newer), with Noble
212
+ as the fallback for Node 22 and browsers. Native hashing does not require an addon. Browser apps can
213
+ run the helper in a Web Worker to keep proof-of-work off the UI thread.
214
+
215
+ For a local **no-PoW faucet**, keep using V2:
216
+
217
+ ```typescript
218
+
219
+ await requestSuiFromFaucetV2({
220
+ host: getFaucetHost('localnet'),
221
+ recipient: '0xYourAddress', // Replace with your Sui address.
222
+ });
223
+ ```
224
+
225
+ For a local **PoW faucet**, use `requestSuiFromFaucetV3` and set `host` to its origin, with
226
+ `/v3/challenge` and `/v3/gas` served at the origin root. If it listens on the default local faucet
227
+ port, use `getFaucetHost('localnet')`. The helper does not infer the protocol from the host or fall
228
+ back to V2.
229
+
230
+ V3 refreshes expired challenges before submission but never automatically retries a payout. HTTP 429
231
+ throws `FaucetRateLimitError`. Other HTTP errors throw `FaucetError`, which exposes `status` and,
232
+ when provided by the server, `code` and a transaction `digest`. Non-JSON error responses use a
233
+ fallback message and preserve the parse error as `cause`. If a digest is present, resolve that
234
+ transaction before requesting another payout. A timeout or connection loss during submission does
235
+ not prove the payout failed; do not blindly retry it.
236
+
197
237
  > **Note:** Faucets on Devnet and Testnet are rate limited. If you hit the limit, wait before trying again.
198
238
  > For Testnet, you can also get SUI through the web UI at `faucet.sui.io` or through the [Sui
199
239
  > Discord](https://discord.gg/sui) faucet channels.
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "author": "Mysten Labs <build@mystenlabs.com>",
4
4
  "description": "Sui TypeScript API",
5
5
  "homepage": "https://sdk.mystenlabs.com",
6
- "version": "2.33.1",
6
+ "version": "2.34.0",
7
7
  "license": "Apache-2.0",
8
8
  "sideEffects": false,
9
9
  "files": [
@@ -138,7 +138,7 @@
138
138
  "@graphql-codegen/typescript": "6.1.0",
139
139
  "@graphql-codegen/typescript-document-nodes": "6.1.0",
140
140
  "@graphql-codegen/typescript-operations": "^6.1.6",
141
- "@grpc/grpc-js": ">=1.14.4",
141
+ "@grpc/grpc-js": ">=1.14.5",
142
142
  "@parcel/watcher": "^2.6.0",
143
143
  "@protobuf-ts/grpc-transport": "^2.11.1",
144
144
  "@types/node": "^26.2.0",
@@ -168,8 +168,8 @@
168
168
  "graphql": "^17.0.2",
169
169
  "poseidon-lite": "0.3.0",
170
170
  "valibot": "^1.4.2",
171
- "@mysten/bcs": "^2.1.2",
172
- "@mysten/utils": "^0.4.1"
171
+ "@mysten/utils": "^0.4.1",
172
+ "@mysten/bcs": "^2.1.2"
173
173
  },
174
174
  "scripts": {
175
175
  "clean": "rm -rf tsconfig.tsbuildinfo ./dist",
@@ -0,0 +1,133 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { literal, object, parse } from 'valibot';
5
+
6
+ import { isValidSuiAddress, normalizeSuiAddress } from '../utils/sui-types.js';
7
+ import { FaucetRateLimitError } from './faucet.js';
8
+ import {
9
+ FaucetAddress,
10
+ FaucetAmount,
11
+ FaucetChallenge,
12
+ FaucetDifficulty,
13
+ FaucetDigest,
14
+ solveFaucetChallenge,
15
+ } from './pow.js';
16
+
17
+ export interface FaucetResponseV3 {
18
+ status: 'success';
19
+ digest: string;
20
+ recipient: string;
21
+ amountMist: string;
22
+ difficulty: string;
23
+ }
24
+
25
+ /** A faucet HTTP error. Resolve any transaction digest before requesting another payout. */
26
+ export class FaucetError extends Error {
27
+ readonly status: number;
28
+ readonly code?: string;
29
+ readonly digest?: string;
30
+
31
+ constructor(
32
+ message: string,
33
+ options: { status: number; code?: string; digest?: string; cause?: unknown },
34
+ ) {
35
+ super(message, { cause: options.cause });
36
+ this.name = 'FaucetError';
37
+ this.status = options.status;
38
+ this.code = options.code;
39
+ this.digest = options.digest;
40
+ }
41
+ }
42
+
43
+ const FaucetResponse = object({
44
+ status: literal('success'),
45
+ digest: FaucetDigest,
46
+ recipient: FaucetAddress,
47
+ amountMist: FaucetAmount,
48
+ difficulty: FaucetDifficulty,
49
+ });
50
+
51
+ /**
52
+ * Request SUI from a PoW faucet on devnet, testnet, or localnet.
53
+ * Fetches and solves a challenge, then submits one payout request without retrying it.
54
+ */
55
+ export async function requestSuiFromFaucetV3(input: {
56
+ host: string;
57
+ recipient: string;
58
+ headers?: HeadersInit;
59
+ signal?: AbortSignal;
60
+ /** Maximum time for fetching, solving, and submitting, in milliseconds. Defaults to 180000. */
61
+ timeout?: number;
62
+ }): Promise<FaucetResponseV3> {
63
+ if (!input.recipient.replace(/^0x/i, '')) throw new Error('Invalid faucet recipient');
64
+ const recipient = normalizeSuiAddress(input.recipient);
65
+ if (!isValidSuiAddress(recipient)) throw new Error('Invalid faucet recipient');
66
+ const timeout = AbortSignal.timeout(input.timeout ?? 180_000);
67
+ const signal = input.signal ? AbortSignal.any([input.signal, timeout]) : timeout;
68
+ const headers = new Headers(input.headers);
69
+ headers.set('Content-Type', 'application/json');
70
+
71
+ async function request(path: string, body?: object): Promise<unknown> {
72
+ signal.throwIfAborted();
73
+ const response = await fetch(new URL(path, input.host).toString(), {
74
+ method: body ? 'POST' : 'GET',
75
+ headers,
76
+ body: body ? JSON.stringify(body) : undefined,
77
+ signal,
78
+ });
79
+ if (response.status === 429) {
80
+ throw new FaucetRateLimitError('Too many requests to the faucet. Please retry later.');
81
+ }
82
+ let parseError: unknown;
83
+ const result = await response.json().catch((cause: unknown) => {
84
+ signal.throwIfAborted();
85
+ if (response.ok) {
86
+ throw new Error(`Invalid faucet response (HTTP ${response.status})`, { cause });
87
+ }
88
+ parseError = cause;
89
+ });
90
+ if (!response.ok) {
91
+ throw new FaucetError(
92
+ typeof result?.error === 'string'
93
+ ? result.error
94
+ : `Faucet request failed (HTTP ${response.status})`,
95
+ {
96
+ status: response.status,
97
+ cause: parseError,
98
+ code: typeof result?.code === 'string' ? result.code : undefined,
99
+ digest: typeof result?.digest === 'string' ? result.digest : undefined,
100
+ },
101
+ );
102
+ }
103
+ return result;
104
+ }
105
+
106
+ while (true) {
107
+ const startedAt = Date.now();
108
+ const challenge = parse(
109
+ FaucetChallenge,
110
+ await request(`/v3/challenge?${new URLSearchParams({ recipient })}`),
111
+ { abortPipeEarly: true },
112
+ );
113
+ if (challenge.recipient !== recipient) throw new Error('Faucet challenge recipient mismatch');
114
+ // Reserve part of the window for submission; refresh only before a payout has been attempted.
115
+ const proof = await solveFaucetChallenge(
116
+ challenge,
117
+ startedAt + challenge.windowSeconds * 800,
118
+ signal,
119
+ );
120
+ if (!proof) continue;
121
+ const result = parse(
122
+ FaucetResponse,
123
+ await request('/v3/gas', {
124
+ recipient,
125
+ checkpointSeq: challenge.checkpointSeq,
126
+ ...proof,
127
+ }),
128
+ { abortPipeEarly: true },
129
+ );
130
+ if (result.recipient !== recipient) throw new Error('Faucet response recipient mismatch');
131
+ return result;
132
+ }
133
+ }
@@ -2,3 +2,5 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
4
  export { requestSuiFromFaucetV2, getFaucetHost, FaucetRateLimitError } from './faucet.js';
5
+ export { requestSuiFromFaucetV3, FaucetError } from './faucet-v3.js';
6
+ export type { FaucetResponseV3 } from './faucet-v3.js';
@@ -0,0 +1,172 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { toHex } from '@mysten/bcs';
5
+ import { argon2dAsync } from '@noble/hashes/argon2.js';
6
+ import type { InferOutput } from 'valibot';
7
+ import {
8
+ check,
9
+ integer,
10
+ literal,
11
+ maxLength,
12
+ minValue,
13
+ number,
14
+ object,
15
+ pipe,
16
+ regex,
17
+ string,
18
+ } from 'valibot';
19
+
20
+ import { isValidTransactionDigest } from '../utils/sui-types.js';
21
+
22
+ const U64 = 1n << 64n;
23
+
24
+ export const FaucetU64 = pipe(
25
+ string(),
26
+ regex(/^(0|[1-9][0-9]{0,19})$/),
27
+ check((value) => BigInt(value) < U64),
28
+ );
29
+ export const FaucetAmount = pipe(
30
+ FaucetU64,
31
+ check((value) => BigInt(value) > 0n),
32
+ );
33
+ export const FaucetAddress = pipe(string(), regex(/^0x[0-9a-f]{64}$/));
34
+ export const FaucetDigest = pipe(
35
+ string(),
36
+ check((value) => value.length <= 44 && isValidTransactionDigest(value)),
37
+ );
38
+ export const FaucetDifficulty = pipe(
39
+ FaucetU64,
40
+ check((value) => BigInt(value) >= 2n && BigInt(value) <= 1n << 48n),
41
+ );
42
+
43
+ // PoW version 1 fixes these costs; never let a server choose the client's memory allocation.
44
+ export const FaucetChallenge = pipe(
45
+ object({
46
+ version: literal(1),
47
+ domain: literal('sui-faucet-pow/1'),
48
+ algorithm: literal('argon2d'),
49
+ argon2Version: literal(19),
50
+ salt: literal('sui-faucet-pow-1'),
51
+ memorySize: literal(8192),
52
+ iterations: literal(1),
53
+ parallelism: literal(1),
54
+ hashLength: literal(32),
55
+ chainId: FaucetDigest,
56
+ checkpointSeq: FaucetU64,
57
+ checkpointDigest: FaucetDigest,
58
+ randomBytes: pipe(
59
+ string(),
60
+ maxLength(1024),
61
+ regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/),
62
+ ),
63
+ faucetAddress: FaucetAddress,
64
+ recipient: FaucetAddress,
65
+ difficulty: FaucetDifficulty,
66
+ threshold: FaucetU64,
67
+ windowSeconds: pipe(number(), integer(), minValue(1)),
68
+ amountMist: FaucetAmount,
69
+ }),
70
+ check((value) => BigInt(value.threshold) === U64 / BigInt(value.difficulty)),
71
+ );
72
+
73
+ type Challenge = InferOutput<typeof FaucetChallenge>;
74
+
75
+ type NativeArgon2 = (
76
+ algorithm: 'argon2d',
77
+ parameters: {
78
+ message: string;
79
+ nonce: string;
80
+ parallelism: number;
81
+ tagLength: number;
82
+ memory: number;
83
+ passes: number;
84
+ },
85
+ callback: (error: Error | null, hash: Uint8Array) => void,
86
+ ) => void;
87
+
88
+ type NodeRuntime = {
89
+ process?: {
90
+ getBuiltinModule?: (id: 'node:crypto') => { argon2?: NativeArgon2 } | undefined;
91
+ };
92
+ };
93
+
94
+ export function hashFaucetProof(challenge: Challenge, nonce: bigint): Promise<Uint8Array> {
95
+ const preimage = [
96
+ challenge.domain,
97
+ challenge.chainId,
98
+ challenge.checkpointSeq,
99
+ challenge.checkpointDigest,
100
+ challenge.randomBytes,
101
+ challenge.faucetAddress,
102
+ challenge.recipient,
103
+ nonce.toString(),
104
+ ].join('\n');
105
+
106
+ // Avoid Node imports so browser bundles can use the Noble fallback without polyfills.
107
+ const nativeArgon2 = (globalThis as NodeRuntime).process?.getBuiltinModule?.(
108
+ 'node:crypto',
109
+ )?.argon2;
110
+ if (nativeArgon2) {
111
+ return new Promise((resolve, reject) => {
112
+ nativeArgon2(
113
+ 'argon2d',
114
+ {
115
+ message: preimage,
116
+ nonce: challenge.salt,
117
+ parallelism: 1,
118
+ tagLength: 32,
119
+ memory: 8192,
120
+ passes: 1,
121
+ },
122
+ (error, hash) => {
123
+ if (error) reject(error);
124
+ else resolve(hash);
125
+ },
126
+ );
127
+ });
128
+ }
129
+
130
+ return argon2dAsync(preimage, challenge.salt, {
131
+ version: 19,
132
+ m: 8192,
133
+ t: 1,
134
+ p: 1,
135
+ dkLen: 32,
136
+ });
137
+ }
138
+
139
+ export async function solveFaucetChallenge(
140
+ challenge: Challenge,
141
+ deadline: number,
142
+ signal: AbortSignal,
143
+ ) {
144
+ let nonce = globalThis.crypto.getRandomValues(new BigUint64Array(1))[0];
145
+ const threshold = BigInt(challenge.threshold);
146
+ while (Date.now() < deadline) {
147
+ signal.throwIfAborted();
148
+ let onAbort!: () => void;
149
+ let hash: Uint8Array;
150
+ try {
151
+ // Stop waiting even if native hashing is still queued in the worker pool.
152
+ hash = await Promise.race([
153
+ new Promise<never>((_, reject) => {
154
+ onAbort = () => reject(signal.reason);
155
+ signal.addEventListener('abort', onAbort, { once: true });
156
+ }),
157
+ hashFaucetProof(challenge, nonce),
158
+ ]);
159
+ } finally {
160
+ signal.removeEventListener('abort', onAbort);
161
+ }
162
+ // Yield to timers and cancellation, even when the hash implementation only yields microtasks.
163
+ await new Promise((resolve) => setTimeout(resolve, 0));
164
+ signal.throwIfAborted();
165
+ if (Date.now() >= deadline) break;
166
+ if (new DataView(hash.buffer, hash.byteOffset, hash.byteLength).getBigUint64(0) < threshold) {
167
+ return { nonce: nonce.toString(), hashHex: toHex(hash) };
168
+ }
169
+ nonce = (nonce + 1n) % U64;
170
+ }
171
+ return null;
172
+ }
@@ -789,19 +789,16 @@ export class GraphQLCoreClient extends CoreClient {
789
789
  async defaultNameServiceName(
790
790
  options: SuiClientTypes.DefaultNameServiceNameOptions,
791
791
  ): Promise<SuiClientTypes.DefaultNameServiceNameResponse> {
792
- const name = await this.#graphqlQuery(
793
- {
794
- query: DefaultSuinsNameDocument,
795
- signal: options.signal,
796
- variables: {
797
- address: options.address,
798
- },
799
- },
800
- (result) => result.address?.defaultNameRecord?.domain ?? null,
801
- );
792
+ const { data, errors } = await this.#graphqlClient.query({
793
+ query: DefaultSuinsNameDocument,
794
+ signal: options.signal,
795
+ variables: { address: options.address },
796
+ });
797
+
798
+ handleGraphQLErrors(errors);
802
799
 
803
800
  return {
804
- data: { name: name },
801
+ data: { name: data?.address?.defaultNameRecord?.domain ?? null },
805
802
  };
806
803
  }
807
804
 
package/src/grpc/core.ts CHANGED
@@ -833,20 +833,22 @@ export class GrpcCoreClient extends CoreClient {
833
833
  async defaultNameServiceName(
834
834
  options: SuiClientTypes.DefaultNameServiceNameOptions,
835
835
  ): Promise<SuiClientTypes.DefaultNameServiceNameResponse> {
836
- const name =
837
- (
838
- await this.#client.nameService.reverseLookupName(
839
- {
840
- address: options.address,
841
- },
842
- { abort: options.signal },
843
- )
844
- ).response.record?.name ?? null;
845
- return {
846
- data: {
847
- name,
848
- },
849
- };
836
+ try {
837
+ const { response } = await this.#client.nameService.reverseLookupName(
838
+ { address: options.address },
839
+ { abort: options.signal },
840
+ );
841
+
842
+ return { data: { name: response.record?.name ?? null } };
843
+ } catch (error) {
844
+ // The reverse lookup reports an address without a default name (or whose default name
845
+ // has expired) the same way a forward lookup reports a missing name.
846
+ if (isNameServiceResolutionMiss(error)) {
847
+ return { data: { name: null } };
848
+ }
849
+
850
+ throw error;
851
+ }
850
852
  }
851
853
 
852
854
  async resolveNameServiceAddress(
package/src/version.ts CHANGED
@@ -3,4 +3,4 @@
3
3
 
4
4
  // This file is generated by genversion.mjs. Do not edit it directly.
5
5
 
6
- export const PACKAGE_VERSION = '2.33.1';
6
+ export const PACKAGE_VERSION = '2.34.0';