sui-multi-client 0.0.0-stage → 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 +21 -0
- package/README.md +284 -2
- package/dist/client.d.ts +66 -0
- package/dist/client.js +203 -0
- package/dist/core.d.ts +63 -0
- package/dist/core.js +194 -0
- package/dist/cursors.d.ts +12 -0
- package/dist/cursors.js +48 -0
- package/dist/endpoints.d.ts +16 -0
- package/dist/endpoints.js +17 -0
- package/dist/errors.d.ts +39 -0
- package/dist/errors.js +81 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/types.d.ts +63 -0
- package/dist/types.js +28 -0
- package/package.json +62 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Berk Turan
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,285 @@
|
|
|
1
|
-
#
|
|
1
|
+
# sui-multi-client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A [`@mysten/sui`](https://sdk.mystenlabs.com/typescript) v3 client that sends each call over gRPC
|
|
4
|
+
or GraphQL and falls back to the other transport when the first one fails.
|
|
5
|
+
|
|
6
|
+
[](https://www.npmjs.com/package/sui-multi-client)
|
|
7
|
+
[](./LICENSE)
|
|
8
|
+
[](https://nodejs.org/)
|
|
9
|
+
|
|
10
|
+
`SuiMultiClient` is a regular SDK client: it implements the v3 Core API, so it works anywhere a
|
|
11
|
+
`SuiGrpcClient` or `SuiGraphQLClient` does, including `Transaction.build`, dapp-kit and SDK
|
|
12
|
+
extensions registered with `$extend`. Underneath it holds one `SuiGrpcClient` and one
|
|
13
|
+
`SuiGraphQLClient` and routes each call between them.
|
|
14
|
+
|
|
15
|
+
Use it when you want:
|
|
16
|
+
|
|
17
|
+
- **Availability**: a fullnode outage, rate limit or network error moves the call to the other
|
|
18
|
+
transport instead of failing.
|
|
19
|
+
- **History**: public fullnodes prune old transactions and checkpoints; GraphQL still serves them.
|
|
20
|
+
A "not found" from gRPC is retried on GraphQL.
|
|
21
|
+
- **One client per method**: send some methods to the transport that suits them best.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npm install sui-multi-client @mysten/sui
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`@mysten/sui` `^3.0.0` is a peer dependency. The package is ESM-only and needs Node.js 22 or later
|
|
30
|
+
(or a modern browser), like `@mysten/sui` v3.
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { SuiMultiClient } from "sui-multi-client";
|
|
36
|
+
|
|
37
|
+
const client = new SuiMultiClient({ network: "testnet" });
|
|
38
|
+
|
|
39
|
+
const { balance } = await client.getBalance({ owner: "0x…" });
|
|
40
|
+
const tx = await client.getTransaction({ digest: "…", include: { effects: true } });
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
For `mainnet`, `testnet`, `devnet` and `localnet`, the client uses the public Mysten Labs endpoints
|
|
44
|
+
by default. Pass your own endpoints, or ready clients, for anything else:
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { SuiGraphQLClient } from "@mysten/sui/graphql";
|
|
48
|
+
|
|
49
|
+
const client = new SuiMultiClient({
|
|
50
|
+
network: "mainnet",
|
|
51
|
+
grpc: { baseUrl: "https://my-fullnode.example.com" },
|
|
52
|
+
graphql: new SuiGraphQLClient({
|
|
53
|
+
network: "mainnet",
|
|
54
|
+
url: "https://my-indexer.example.com/graphql",
|
|
55
|
+
headers: { authorization: "Bearer …" },
|
|
56
|
+
}),
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
A ready client must be for the same `network`; the constructor throws otherwise. To confirm both
|
|
61
|
+
endpoints serve the same chain, call `await client.checkTransports()`. It compares their chain
|
|
62
|
+
identifiers and throws if they differ.
|
|
63
|
+
|
|
64
|
+
### With transactions and signers
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { Transaction } from "@mysten/sui/transactions";
|
|
68
|
+
|
|
69
|
+
const tx = new Transaction();
|
|
70
|
+
tx.transferObjects([tx.splitCoins(tx.gas, [1_000])], recipient);
|
|
71
|
+
|
|
72
|
+
const result = await client.signAndExecuteTransaction({ transaction: tx, signer: keypair });
|
|
73
|
+
await client.waitForTransaction({ result });
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Building, gas selection, execution and waiting all go through the routed Core API, so each step
|
|
77
|
+
falls back on its own.
|
|
78
|
+
|
|
79
|
+
### With dapp-kit
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { createDAppKit } from "@mysten/dapp-kit-core";
|
|
83
|
+
import { SuiMultiClient } from "sui-multi-client";
|
|
84
|
+
|
|
85
|
+
export const dAppKit = createDAppKit({
|
|
86
|
+
networks: ["mainnet", "testnet"],
|
|
87
|
+
createClient: (network) => new SuiMultiClient({ network }),
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Transport preferences
|
|
92
|
+
|
|
93
|
+
| Preference | Behavior |
|
|
94
|
+
| ---------------- | ----------------------------------------------------------------- |
|
|
95
|
+
| `grpc-first` | Try gRPC; on a fallback-eligible error, try GraphQL. **Default.** |
|
|
96
|
+
| `graphql-first` | Try GraphQL; on a fallback-eligible error, try gRPC. |
|
|
97
|
+
| `grpc-only` | gRPC only. Errors are those of `SuiGrpcClient`. |
|
|
98
|
+
| `graphql-only` | GraphQL only. Errors are those of `SuiGraphQLClient`. |
|
|
99
|
+
|
|
100
|
+
Set one for every method with `preference`, and override single methods with `methods`:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
const client = new SuiMultiClient({
|
|
104
|
+
network: "mainnet",
|
|
105
|
+
preference: "grpc-first",
|
|
106
|
+
methods: {
|
|
107
|
+
listTransactions: "graphql-first",
|
|
108
|
+
listEvents: "graphql-first",
|
|
109
|
+
executeTransaction: "grpc-only",
|
|
110
|
+
streams: "grpc-only",
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
client.transportOrder("listEvents"); // ["graphql", "grpc"]
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
The keys of `methods` are the Core API method names (`getObjects`, `listCoins`, `getTransaction`,
|
|
118
|
+
`executeTransaction`, `simulateTransaction`, `listEvents`, `resolveTransactionPlugin`, …) plus
|
|
119
|
+
`streams`. Methods the SDK builds on top of those, such as `getObject`, `getDynamicField` and
|
|
120
|
+
`waitForTransaction`, follow the preference of the method they call. The constructor throws on an
|
|
121
|
+
unknown preference or method name; `TRANSPORT_PREFERENCES` and `ROUTED_METHODS` list the valid ones.
|
|
122
|
+
|
|
123
|
+
## When a call falls back
|
|
124
|
+
|
|
125
|
+
The default policy, exported as `isFallbackError`, falls back when the failure is about the
|
|
126
|
+
**endpoint**, not the **request**:
|
|
127
|
+
|
|
128
|
+
| Falls back | Does not fall back |
|
|
129
|
+
| -------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
|
|
130
|
+
| gRPC `UNAVAILABLE`, `DEADLINE_EXCEEDED`, `RESOURCE_EXHAUSTED`, `INTERNAL`, `UNKNOWN`, `UNIMPLEMENTED`, `CANCELLED`, `UNAUTHENTICATED`, `PERMISSION_DENIED` | gRPC `INVALID_ARGUMENT`, `FAILED_PRECONDITION`, … |
|
|
131
|
+
| gRPC `OUT_OF_RANGE`: pruned history | Failed simulations, Move aborts |
|
|
132
|
+
| GraphQL errors the SDK marks retryable (`Unavailable`, `RateLimited`, `ServerError`) | GraphQL validation and other non-retryable errors |
|
|
133
|
+
| `fetch` failures before any response | Any error once the call's `signal` is aborted |
|
|
134
|
+
| `TransactionError` with reason `notFound`, while `fallbackOnNotFound` is on | |
|
|
135
|
+
|
|
136
|
+
SDK errors that wrap a transport failure, such as the `SimulationError` the gRPC transaction
|
|
137
|
+
resolver throws when the fullnode cannot be reached, are judged by the error in their `cause`.
|
|
138
|
+
When the error is not eligible, it is rethrown as it is. When every allowed transport fails with
|
|
139
|
+
an eligible error, the client throws `AllTransportsFailedError`, whose `failures` lists each
|
|
140
|
+
attempt and whose `cause` is the last error. Two exceptions keep the SDK's own error: `*-only`
|
|
141
|
+
preferences, and a transaction that every transport answered "not found" for, which throws the
|
|
142
|
+
SDK's `TransactionError`.
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
import { AllTransportsFailedError } from "sui-multi-client";
|
|
146
|
+
|
|
147
|
+
try {
|
|
148
|
+
await client.getReferenceGasPrice();
|
|
149
|
+
} catch (error) {
|
|
150
|
+
if (error instanceof AllTransportsFailedError) {
|
|
151
|
+
for (const { transport, error: cause } of error.failures) console.warn(transport, cause);
|
|
152
|
+
}
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### `fallbackOnNotFound`
|
|
158
|
+
|
|
159
|
+
On by default. A pruned fullnode answers "not found" for old transactions, and a lagging indexer
|
|
160
|
+
answers "not found" for very new ones, so the other transport is asked too. That costs one extra
|
|
161
|
+
request whenever the transaction really does not exist, including on every poll of
|
|
162
|
+
`waitForTransaction` until the transaction lands. Turn it off with `fallbackOnNotFound: false`.
|
|
163
|
+
|
|
164
|
+
### Your own policy
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
import { isFallbackError } from "sui-multi-client";
|
|
168
|
+
|
|
169
|
+
const client = new SuiMultiClient({
|
|
170
|
+
network: "mainnet",
|
|
171
|
+
shouldFallback: (error, context) =>
|
|
172
|
+
context.method !== "executeTransaction" && isFallbackError(error, context),
|
|
173
|
+
onFallback: ({ method, from, to, error }) => metrics.increment("sui.fallback", { method, from, to }),
|
|
174
|
+
});
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
`context` holds `method`, the failed `transport` and `fallbackOnNotFound`. `onFallback` runs before
|
|
178
|
+
each fallback and may be async; whatever it throws or rejects with is ignored.
|
|
179
|
+
|
|
180
|
+
## Pagination
|
|
181
|
+
|
|
182
|
+
gRPC and GraphQL cursors are not interchangeable: a cursor from one is rejected by the other. So
|
|
183
|
+
every cursor this client returns (`cursor` on object and coin lists, `startCursor` and `endCursor`
|
|
184
|
+
on transaction, event and checkpoint queries) carries the transport that produced it, as in
|
|
185
|
+
`grpc:…` or `graphql:…`. Treat cursors as opaque and pass them back unchanged.
|
|
186
|
+
|
|
187
|
+
A request with a prefixed cursor goes only to that transport, so a page sequence never switches
|
|
188
|
+
transport halfway. If that transport fails, the call fails instead of falling back; start the
|
|
189
|
+
sequence again without a cursor to let the client pick a transport. A request that mixes cursors
|
|
190
|
+
from both transports (`after` from one, `before` from the other) throws `MixedCursorError`.
|
|
191
|
+
Unprefixed cursors are passed through to the preferred transport as they are.
|
|
192
|
+
|
|
193
|
+
## Transactions
|
|
194
|
+
|
|
195
|
+
- **Execution** falls back like any other call. Sending the same signed bytes again is safe: a
|
|
196
|
+
transaction has one digest and the network executes it at most once, so a resend, over either
|
|
197
|
+
transport, returns the same digest and effects instead of executing twice. Use
|
|
198
|
+
`executeTransaction: "grpc-only"` if you would rather handle every failure yourself.
|
|
199
|
+
- **Resolution** (`resolveTransactionPlugin`: gas, object versions, input types) falls back only
|
|
200
|
+
until the resolver has passed control to the next build step. An error after that comes from a
|
|
201
|
+
later step and is rethrown as it is.
|
|
202
|
+
- **Simulation** errors about the transaction itself do not fall back; the other transport would
|
|
203
|
+
give the same answer.
|
|
204
|
+
|
|
205
|
+
## Streams
|
|
206
|
+
|
|
207
|
+
`streamCheckpoints`, `streamTransactions` and `streamEvents` run on the first transport of the
|
|
208
|
+
`streams` preference and do not fall back: the SDK reconnects and resumes them itself, and their
|
|
209
|
+
resume tokens belong to one transport.
|
|
210
|
+
|
|
211
|
+
## Using the inner clients
|
|
212
|
+
|
|
213
|
+
`client.grpc` and `client.graphql` are the `SuiGrpcClient` and `SuiGraphQLClient` underneath, for
|
|
214
|
+
features outside the Core API, such as custom GraphQL queries or gRPC services:
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
const { data } = await client.graphql.query({ query: myQuery, variables: { … } });
|
|
218
|
+
const response = await client.grpc.ledgerService.getServiceInfo({});
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Calls made on them directly do not fall back.
|
|
222
|
+
|
|
223
|
+
## Known differences between the transports
|
|
224
|
+
|
|
225
|
+
The client does not hide them; they show up depending on which transport answers.
|
|
226
|
+
|
|
227
|
+
- **Indexer lag**: GraphQL reads from an indexer that can trail the fullnode by a few seconds, so
|
|
228
|
+
a transaction just executed over gRPC may be "not found" on GraphQL for a moment.
|
|
229
|
+
- **Page sizes**: GraphQL rejects a `limit` above the server's cap; gRPC silently truncates.
|
|
230
|
+
- **Event type filters**: gRPC `listEvents` rejects short addresses in `eventType` (`0x3::…`) with
|
|
231
|
+
`INVALID_ARGUMENT`, while GraphQL accepts them. Use full 64-hex-digit addresses.
|
|
232
|
+
- **Transport-specific fields**: `include` options and result fields that only one transport
|
|
233
|
+
supports, such as gRPC's `protoJson`, are not part of this client's types.
|
|
234
|
+
- **GraphQL errors inside a successful response**: when the GraphQL service answers HTTP 200 with
|
|
235
|
+
an `errors` list, such as a query that timed out on the server, the SDK throws a plain `Error`
|
|
236
|
+
with only the server's message (or an `AggregateError` of them); the error code is not kept. The
|
|
237
|
+
default policy cannot tell those from request errors, so it does not fall back on them. This
|
|
238
|
+
only matters when GraphQL is tried first. To fall back on them anyway, match the message:
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
shouldFallback: (error, context) =>
|
|
242
|
+
isFallbackError(error, context) ||
|
|
243
|
+
(context.transport === "graphql" && error instanceof Error && /timed out/i.test(error.message)),
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
## API
|
|
247
|
+
|
|
248
|
+
| Export | What it is |
|
|
249
|
+
| -------------------------- | -------------------------------------------------------------------------- |
|
|
250
|
+
| `SuiMultiClient` | The client. Same Core API methods as `SuiGrpcClient`, plus the below. |
|
|
251
|
+
| `client.grpc`, `client.graphql` | The inner clients. |
|
|
252
|
+
| `client.transportOrder(method)` | The transports a method tries, in order. |
|
|
253
|
+
| `client.checkTransports()` | Checks both transports serve the same chain; returns its identifier. |
|
|
254
|
+
| `MultiCoreClient` | The routing Core API client, `client.core`. |
|
|
255
|
+
| `isFallbackError` | The default fallback policy. |
|
|
256
|
+
| `AllTransportsFailedError` | Every allowed transport failed. `failures`, `method`, `cause`. |
|
|
257
|
+
| `MixedCursorError` | One request carried cursors from both transports. |
|
|
258
|
+
| `GRPC_ENDPOINTS`, `GRAPHQL_ENDPOINTS` | The default endpoints per network. |
|
|
259
|
+
| `TRANSPORT_PREFERENCES`, `ROUTED_METHODS` | The valid `preference` values and `methods` keys. |
|
|
260
|
+
|
|
261
|
+
### Options
|
|
262
|
+
|
|
263
|
+
| Option | Type | Default |
|
|
264
|
+
| --------------------- | ------------------------------------------ | ----------------------------- |
|
|
265
|
+
| `network` | `SuiClientTypes.Network` | required |
|
|
266
|
+
| `grpc` | `SuiGrpcClient \| { baseUrl }` | public fullnode of `network` |
|
|
267
|
+
| `graphql` | `SuiGraphQLClient \| { url }` | public GraphQL of `network` |
|
|
268
|
+
| `preference` | `TransportPreference` | `"grpc-first"` |
|
|
269
|
+
| `methods` | `Partial<Record<RoutedMethod, TransportPreference>>` | `{}` |
|
|
270
|
+
| `fallbackOnNotFound` | `boolean` | `true` |
|
|
271
|
+
| `shouldFallback` | `(error, context) => boolean` | `isFallbackError` |
|
|
272
|
+
| `onFallback` | `(event: FallbackEvent) => unknown` | none |
|
|
273
|
+
| `mvr` | `SuiClientTypes.MvrOptions` | as in the SDK |
|
|
274
|
+
| `restrictedMoveCalls` | `readonly string[]` | as in the SDK |
|
|
275
|
+
|
|
276
|
+
`mvr` and `restrictedMoveCalls` also go to inner clients built from `{ baseUrl }` or `{ url }`;
|
|
277
|
+
ready clients keep their own.
|
|
278
|
+
|
|
279
|
+
## Development
|
|
280
|
+
|
|
281
|
+
See [CONTRIBUTING.md](./CONTRIBUTING.md).
|
|
282
|
+
|
|
283
|
+
## License
|
|
284
|
+
|
|
285
|
+
[MIT](./LICENSE)
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { BaseClient, type SuiClientTypes } from "@mysten/sui/client";
|
|
2
|
+
import { SuiGraphQLClient } from "@mysten/sui/graphql";
|
|
3
|
+
import { SuiGrpcClient } from "@mysten/sui/grpc";
|
|
4
|
+
import type { TransactionPlugin } from "@mysten/sui/transactions";
|
|
5
|
+
import { MultiCoreClient } from "./core.js";
|
|
6
|
+
import { type SuiMultiClientOptions, type Transport } from "./types.js";
|
|
7
|
+
/**
|
|
8
|
+
* A Sui client that sends each call over gRPC or GraphQL and falls back to the other transport
|
|
9
|
+
* when the first one fails. It is a regular `@mysten/sui` client: pass it wherever a client with
|
|
10
|
+
* the Core API is expected, such as `Transaction.build`, dapp-kit or SDK extensions.
|
|
11
|
+
*/
|
|
12
|
+
export declare class SuiMultiClient extends BaseClient {
|
|
13
|
+
#private;
|
|
14
|
+
core: MultiCoreClient;
|
|
15
|
+
constructor(options: SuiMultiClientOptions);
|
|
16
|
+
/** The gRPC client underneath, for gRPC-only services and options. */
|
|
17
|
+
get grpc(): SuiGrpcClient;
|
|
18
|
+
/** The GraphQL client underneath, for custom GraphQL queries. */
|
|
19
|
+
get graphql(): SuiGraphQLClient;
|
|
20
|
+
get mvr(): SuiClientTypes.MvrMethods;
|
|
21
|
+
/** The transports `method` tries, in order. */
|
|
22
|
+
transportOrder(...args: Parameters<MultiCoreClient["transportOrder"]>): Transport[];
|
|
23
|
+
/**
|
|
24
|
+
* Checks that both transports serve the same chain, by comparing their chain identifiers.
|
|
25
|
+
* Throws when they differ or when either cannot be reached.
|
|
26
|
+
*/
|
|
27
|
+
checkTransports(options?: {
|
|
28
|
+
signal?: AbortSignal;
|
|
29
|
+
}): Promise<{
|
|
30
|
+
chainIdentifier: string;
|
|
31
|
+
}>;
|
|
32
|
+
getObjects<Include extends SuiClientTypes.ObjectInclude = {}>(input: SuiClientTypes.GetObjectsOptions<Include>): Promise<SuiClientTypes.GetObjectsResponse<Include>>;
|
|
33
|
+
getObject<Include extends SuiClientTypes.ObjectInclude = {}>(input: SuiClientTypes.GetObjectOptions<Include>): Promise<SuiClientTypes.GetObjectResponse<Include>>;
|
|
34
|
+
listCoins(input: SuiClientTypes.ListCoinsOptions): Promise<SuiClientTypes.ListCoinsResponse>;
|
|
35
|
+
listOwnedObjects<Include extends SuiClientTypes.ObjectInclude = {}>(input: SuiClientTypes.ListOwnedObjectsOptions<Include>): Promise<SuiClientTypes.ListOwnedObjectsResponse<Include>>;
|
|
36
|
+
getBalance(input: SuiClientTypes.GetBalanceOptions): Promise<SuiClientTypes.GetBalanceResponse>;
|
|
37
|
+
listBalances(input: SuiClientTypes.ListBalancesOptions): Promise<SuiClientTypes.ListBalancesResponse>;
|
|
38
|
+
getCoinMetadata(input: SuiClientTypes.GetCoinMetadataOptions): Promise<SuiClientTypes.GetCoinMetadataResponse>;
|
|
39
|
+
getTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(input: SuiClientTypes.GetTransactionOptions<Include>): Promise<SuiClientTypes.TransactionResult<Include>>;
|
|
40
|
+
executeTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(input: SuiClientTypes.ExecuteTransactionOptions<Include>): Promise<SuiClientTypes.TransactionResult<Include>>;
|
|
41
|
+
signAndExecuteTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(input: SuiClientTypes.SignAndExecuteTransactionOptions<Include>): Promise<SuiClientTypes.TransactionResult<Include>>;
|
|
42
|
+
waitForTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(input: SuiClientTypes.WaitForTransactionOptions<Include>): Promise<SuiClientTypes.TransactionResult<Include>>;
|
|
43
|
+
simulateTransaction<Include extends SuiClientTypes.SimulateTransactionInclude = {}>(input: SuiClientTypes.SimulateTransactionOptions<Include>): Promise<SuiClientTypes.SimulateTransactionResult<Include>>;
|
|
44
|
+
getReferenceGasPrice(input?: SuiClientTypes.GetReferenceGasPriceOptions): Promise<SuiClientTypes.GetReferenceGasPriceResponse>;
|
|
45
|
+
getCurrentSystemState(input?: SuiClientTypes.GetCurrentSystemStateOptions): Promise<SuiClientTypes.GetCurrentSystemStateResponse>;
|
|
46
|
+
getProtocolConfig(input?: SuiClientTypes.GetProtocolConfigOptions): Promise<SuiClientTypes.GetProtocolConfigResponse>;
|
|
47
|
+
getChainIdentifier(input?: SuiClientTypes.GetChainIdentifierOptions): Promise<SuiClientTypes.GetChainIdentifierResponse>;
|
|
48
|
+
listDynamicFields<Include extends SuiClientTypes.DynamicFieldInclude = {}>(input: SuiClientTypes.ListDynamicFieldsOptions<Include>): Promise<SuiClientTypes.ListDynamicFieldsResponse<Include>>;
|
|
49
|
+
getDynamicField(input: SuiClientTypes.GetDynamicFieldOptions): Promise<SuiClientTypes.GetDynamicFieldResponse>;
|
|
50
|
+
getDynamicObjectField<Include extends SuiClientTypes.ObjectInclude = {}>(input: SuiClientTypes.GetDynamicObjectFieldOptions<Include>): Promise<SuiClientTypes.GetDynamicObjectFieldResponse<Include>>;
|
|
51
|
+
getAddressAliases(input: SuiClientTypes.GetAddressAliasesOptions): Promise<SuiClientTypes.GetAddressAliasesResponse>;
|
|
52
|
+
listTransactions<Include extends SuiClientTypes.TransactionInclude = {}>(input: SuiClientTypes.ListTransactionsOptions<Include>): Promise<SuiClientTypes.ListTransactionsResponse<Include>>;
|
|
53
|
+
listEvents(input: SuiClientTypes.ListEventsOptions): Promise<SuiClientTypes.ListEventsResponse>;
|
|
54
|
+
listCheckpoints(input: SuiClientTypes.ListCheckpointsOptions): Promise<SuiClientTypes.ListCheckpointsResponse>;
|
|
55
|
+
getMoveFunction(input: SuiClientTypes.GetMoveFunctionOptions): Promise<SuiClientTypes.GetMoveFunctionResponse>;
|
|
56
|
+
resolveTransactionPlugin(): TransactionPlugin;
|
|
57
|
+
verifySignature(input: SuiClientTypes.VerifySignatureOptions): Promise<SuiClientTypes.VerifySignatureResponse>;
|
|
58
|
+
defaultNameServiceName(input: SuiClientTypes.DefaultNameServiceNameOptions): Promise<SuiClientTypes.DefaultNameServiceNameResponse>;
|
|
59
|
+
resolveNameServiceAddress(input: SuiClientTypes.ResolveNameServiceAddressOptions): Promise<SuiClientTypes.ResolveNameServiceAddressResponse>;
|
|
60
|
+
/** Streams checkpoints on the first transport of the `streams` preference. */
|
|
61
|
+
streamCheckpoints<Include extends SuiClientTypes.StreamCheckpointInclude = {}, Frames extends SuiClientTypes.StreamFrameOptions = {}>(options?: SuiClientTypes.StreamCheckpointsOptions<Include, Frames>): AsyncGenerator<SuiClientTypes.StreamCheckpointFrame<Include, Frames>>;
|
|
62
|
+
/** Streams transactions on the first transport of the `streams` preference. */
|
|
63
|
+
streamTransactions<Include extends SuiClientTypes.TransactionInclude = {}, Frames extends SuiClientTypes.StreamFrameOptions = {}>(options?: SuiClientTypes.StreamTransactionsOptions<Include, Frames>): AsyncGenerator<SuiClientTypes.StreamTransactionFrame<Include, Frames>>;
|
|
64
|
+
/** Streams events on the first transport of the `streams` preference. */
|
|
65
|
+
streamEvents<Frames extends SuiClientTypes.StreamFrameOptions = {}>(options?: SuiClientTypes.StreamEventsOptions<Frames>): AsyncGenerator<SuiClientTypes.StreamEventFrame<Frames>>;
|
|
66
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { BaseClient } from "@mysten/sui/client";
|
|
2
|
+
import { SuiGraphQLClient, isSuiGraphQLClient } from "@mysten/sui/graphql";
|
|
3
|
+
import { SuiGrpcClient, isSuiGrpcClient } from "@mysten/sui/grpc";
|
|
4
|
+
import { MultiCoreClient } from "./core.js";
|
|
5
|
+
import { GRAPHQL_ENDPOINTS, GRPC_ENDPOINTS, isKnownNetwork } from "./endpoints.js";
|
|
6
|
+
import { isFallbackError } from "./errors.js";
|
|
7
|
+
import { ROUTED_METHODS, TRANSPORT_PREFERENCES } from "./types.js";
|
|
8
|
+
/** Rejects preferences and method names TypeScript would catch, for JavaScript callers. */
|
|
9
|
+
function validatePreferences({ preference, methods }) {
|
|
10
|
+
const check = (value, where) => {
|
|
11
|
+
if (value !== undefined && !TRANSPORT_PREFERENCES.includes(value)) {
|
|
12
|
+
throw new TypeError(`SuiMultiClient: ${where} is ${JSON.stringify(value)}; expected one of ${TRANSPORT_PREFERENCES.join(", ")}`);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
check(preference, "preference");
|
|
16
|
+
for (const [method, value] of Object.entries(methods ?? {})) {
|
|
17
|
+
if (!ROUTED_METHODS.includes(method)) {
|
|
18
|
+
throw new TypeError(`SuiMultiClient: methods.${method} is not a routed method; expected one of ${ROUTED_METHODS.join(", ")}`);
|
|
19
|
+
}
|
|
20
|
+
check(value, `methods.${method}`);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function grpcClient(options) {
|
|
24
|
+
const { network, grpc, mvr, restrictedMoveCalls } = options;
|
|
25
|
+
if (isSuiGrpcClient(grpc))
|
|
26
|
+
return grpc;
|
|
27
|
+
const baseUrl = grpc?.baseUrl ?? (isKnownNetwork(network) ? GRPC_ENDPOINTS[network] : undefined);
|
|
28
|
+
if (baseUrl === undefined) {
|
|
29
|
+
throw new TypeError(`SuiMultiClient: network "${network}" has no default gRPC endpoint; pass grpc.baseUrl`);
|
|
30
|
+
}
|
|
31
|
+
return new SuiGrpcClient({ network, baseUrl, mvr, restrictedMoveCalls });
|
|
32
|
+
}
|
|
33
|
+
function graphqlClient(options) {
|
|
34
|
+
const { network, graphql, mvr, restrictedMoveCalls } = options;
|
|
35
|
+
if (isSuiGraphQLClient(graphql))
|
|
36
|
+
return graphql;
|
|
37
|
+
const url = graphql?.url ?? (isKnownNetwork(network) ? GRAPHQL_ENDPOINTS[network] : undefined);
|
|
38
|
+
if (url === undefined) {
|
|
39
|
+
throw new TypeError(`SuiMultiClient: network "${network}" has no default GraphQL endpoint; pass graphql.url`);
|
|
40
|
+
}
|
|
41
|
+
return new SuiGraphQLClient({ network, url, mvr, restrictedMoveCalls });
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* A Sui client that sends each call over gRPC or GraphQL and falls back to the other transport
|
|
45
|
+
* when the first one fails. It is a regular `@mysten/sui` client: pass it wherever a client with
|
|
46
|
+
* the Core API is expected, such as `Transaction.build`, dapp-kit or SDK extensions.
|
|
47
|
+
*/
|
|
48
|
+
export class SuiMultiClient extends BaseClient {
|
|
49
|
+
core;
|
|
50
|
+
#grpc;
|
|
51
|
+
#graphql;
|
|
52
|
+
constructor(options) {
|
|
53
|
+
super({ network: options.network });
|
|
54
|
+
validatePreferences(options);
|
|
55
|
+
this.#grpc = grpcClient(options);
|
|
56
|
+
this.#graphql = graphqlClient(options);
|
|
57
|
+
for (const [transport, client] of [
|
|
58
|
+
["grpc", this.#grpc],
|
|
59
|
+
["graphql", this.#graphql],
|
|
60
|
+
]) {
|
|
61
|
+
if (client.network !== options.network) {
|
|
62
|
+
throw new TypeError(`SuiMultiClient: the ${transport} client is for "${client.network}", not "${options.network}"`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
this.core = new MultiCoreClient({
|
|
66
|
+
base: this,
|
|
67
|
+
network: options.network,
|
|
68
|
+
transports: { grpc: this.#grpc.core, graphql: this.#graphql.core },
|
|
69
|
+
preference: options.preference ?? "grpc-first",
|
|
70
|
+
methods: options.methods ?? {},
|
|
71
|
+
fallbackOnNotFound: options.fallbackOnNotFound ?? true,
|
|
72
|
+
shouldFallback: options.shouldFallback ?? isFallbackError,
|
|
73
|
+
onFallback: options.onFallback,
|
|
74
|
+
mvr: options.mvr,
|
|
75
|
+
restrictedMoveCalls: options.restrictedMoveCalls,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/** The gRPC client underneath, for gRPC-only services and options. */
|
|
79
|
+
get grpc() {
|
|
80
|
+
return this.#grpc;
|
|
81
|
+
}
|
|
82
|
+
/** The GraphQL client underneath, for custom GraphQL queries. */
|
|
83
|
+
get graphql() {
|
|
84
|
+
return this.#graphql;
|
|
85
|
+
}
|
|
86
|
+
get mvr() {
|
|
87
|
+
return this.core.mvr;
|
|
88
|
+
}
|
|
89
|
+
/** The transports `method` tries, in order. */
|
|
90
|
+
transportOrder(...args) {
|
|
91
|
+
return this.core.transportOrder(...args);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Checks that both transports serve the same chain, by comparing their chain identifiers.
|
|
95
|
+
* Throws when they differ or when either cannot be reached.
|
|
96
|
+
*/
|
|
97
|
+
async checkTransports(options) {
|
|
98
|
+
const [grpc, graphql] = await Promise.all([
|
|
99
|
+
this.#grpc.core.getChainIdentifier(options),
|
|
100
|
+
this.#graphql.core.getChainIdentifier(options),
|
|
101
|
+
]);
|
|
102
|
+
if (grpc.chainIdentifier !== graphql.chainIdentifier) {
|
|
103
|
+
throw new Error(`SuiMultiClient: gRPC serves chain ${grpc.chainIdentifier} but GraphQL serves ${graphql.chainIdentifier}`);
|
|
104
|
+
}
|
|
105
|
+
return { chainIdentifier: grpc.chainIdentifier };
|
|
106
|
+
}
|
|
107
|
+
getObjects(input) {
|
|
108
|
+
return this.core.getObjects(input);
|
|
109
|
+
}
|
|
110
|
+
getObject(input) {
|
|
111
|
+
return this.core.getObject(input);
|
|
112
|
+
}
|
|
113
|
+
listCoins(input) {
|
|
114
|
+
return this.core.listCoins(input);
|
|
115
|
+
}
|
|
116
|
+
listOwnedObjects(input) {
|
|
117
|
+
return this.core.listOwnedObjects(input);
|
|
118
|
+
}
|
|
119
|
+
getBalance(input) {
|
|
120
|
+
return this.core.getBalance(input);
|
|
121
|
+
}
|
|
122
|
+
listBalances(input) {
|
|
123
|
+
return this.core.listBalances(input);
|
|
124
|
+
}
|
|
125
|
+
getCoinMetadata(input) {
|
|
126
|
+
return this.core.getCoinMetadata(input);
|
|
127
|
+
}
|
|
128
|
+
getTransaction(input) {
|
|
129
|
+
return this.core.getTransaction(input);
|
|
130
|
+
}
|
|
131
|
+
executeTransaction(input) {
|
|
132
|
+
return this.core.executeTransaction(input);
|
|
133
|
+
}
|
|
134
|
+
signAndExecuteTransaction(input) {
|
|
135
|
+
return this.core.signAndExecuteTransaction(input);
|
|
136
|
+
}
|
|
137
|
+
waitForTransaction(input) {
|
|
138
|
+
return this.core.waitForTransaction(input);
|
|
139
|
+
}
|
|
140
|
+
simulateTransaction(input) {
|
|
141
|
+
return this.core.simulateTransaction(input);
|
|
142
|
+
}
|
|
143
|
+
getReferenceGasPrice(input) {
|
|
144
|
+
return this.core.getReferenceGasPrice(input);
|
|
145
|
+
}
|
|
146
|
+
getCurrentSystemState(input) {
|
|
147
|
+
return this.core.getCurrentSystemState(input);
|
|
148
|
+
}
|
|
149
|
+
getProtocolConfig(input) {
|
|
150
|
+
return this.core.getProtocolConfig(input);
|
|
151
|
+
}
|
|
152
|
+
getChainIdentifier(input) {
|
|
153
|
+
return this.core.getChainIdentifier(input);
|
|
154
|
+
}
|
|
155
|
+
listDynamicFields(input) {
|
|
156
|
+
return this.core.listDynamicFields(input);
|
|
157
|
+
}
|
|
158
|
+
getDynamicField(input) {
|
|
159
|
+
return this.core.getDynamicField(input);
|
|
160
|
+
}
|
|
161
|
+
getDynamicObjectField(input) {
|
|
162
|
+
return this.core.getDynamicObjectField(input);
|
|
163
|
+
}
|
|
164
|
+
getAddressAliases(input) {
|
|
165
|
+
return this.core.getAddressAliases(input);
|
|
166
|
+
}
|
|
167
|
+
listTransactions(input) {
|
|
168
|
+
return this.core.listTransactions(input);
|
|
169
|
+
}
|
|
170
|
+
listEvents(input) {
|
|
171
|
+
return this.core.listEvents(input);
|
|
172
|
+
}
|
|
173
|
+
listCheckpoints(input) {
|
|
174
|
+
return this.core.listCheckpoints(input);
|
|
175
|
+
}
|
|
176
|
+
getMoveFunction(input) {
|
|
177
|
+
return this.core.getMoveFunction(input);
|
|
178
|
+
}
|
|
179
|
+
resolveTransactionPlugin() {
|
|
180
|
+
return this.core.resolveTransactionPlugin();
|
|
181
|
+
}
|
|
182
|
+
verifySignature(input) {
|
|
183
|
+
return this.core.verifySignature(input);
|
|
184
|
+
}
|
|
185
|
+
defaultNameServiceName(input) {
|
|
186
|
+
return this.core.defaultNameServiceName(input);
|
|
187
|
+
}
|
|
188
|
+
resolveNameServiceAddress(input) {
|
|
189
|
+
return this.core.resolveNameServiceAddress(input);
|
|
190
|
+
}
|
|
191
|
+
/** Streams checkpoints on the first transport of the `streams` preference. */
|
|
192
|
+
streamCheckpoints(options) {
|
|
193
|
+
return this.core.streamCheckpoints(options);
|
|
194
|
+
}
|
|
195
|
+
/** Streams transactions on the first transport of the `streams` preference. */
|
|
196
|
+
streamTransactions(options) {
|
|
197
|
+
return this.core.streamTransactions(options);
|
|
198
|
+
}
|
|
199
|
+
/** Streams events on the first transport of the `streams` preference. */
|
|
200
|
+
streamEvents(options) {
|
|
201
|
+
return this.core.streamEvents(options);
|
|
202
|
+
}
|
|
203
|
+
}
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { CoreClient, type BaseClient, type SuiClientTypes } from "@mysten/sui/client";
|
|
2
|
+
import type { TransactionPlugin } from "@mysten/sui/transactions";
|
|
3
|
+
import { type FallbackContext } from "./errors.js";
|
|
4
|
+
import type { FallbackEvent, RoutedMethod, Transport, TransportPreference } from "./types.js";
|
|
5
|
+
export interface MultiCoreClientOptions {
|
|
6
|
+
base: BaseClient;
|
|
7
|
+
network: SuiClientTypes.Network;
|
|
8
|
+
transports: Record<Transport, CoreClient>;
|
|
9
|
+
preference: TransportPreference;
|
|
10
|
+
methods: Partial<Record<RoutedMethod, TransportPreference>>;
|
|
11
|
+
fallbackOnNotFound: boolean;
|
|
12
|
+
shouldFallback: (error: unknown, context: FallbackContext) => boolean;
|
|
13
|
+
onFallback: ((event: FallbackEvent) => unknown) | undefined;
|
|
14
|
+
mvr?: SuiClientTypes.MvrOptions;
|
|
15
|
+
restrictedMoveCalls?: readonly string[];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The Core API of `SuiMultiClient`: every method goes to the transport its preference names, and
|
|
19
|
+
* moves to the other transport when the first fails with a fallback-eligible error.
|
|
20
|
+
*/
|
|
21
|
+
export declare class MultiCoreClient extends CoreClient {
|
|
22
|
+
#private;
|
|
23
|
+
constructor(options: MultiCoreClientOptions);
|
|
24
|
+
/** The transports `method` may use, in the order it tries them. */
|
|
25
|
+
transportOrder(method: RoutedMethod): Transport[];
|
|
26
|
+
getObjects<Include extends SuiClientTypes.ObjectInclude = {}>(options: SuiClientTypes.GetObjectsOptions<Include>): Promise<SuiClientTypes.GetObjectsResponse<Include>>;
|
|
27
|
+
listOwnedObjects<Include extends SuiClientTypes.ObjectInclude = {}>(options: SuiClientTypes.ListOwnedObjectsOptions<Include>): Promise<SuiClientTypes.ListOwnedObjectsResponse<Include>>;
|
|
28
|
+
listCoins(options: SuiClientTypes.ListCoinsOptions): Promise<SuiClientTypes.ListCoinsResponse>;
|
|
29
|
+
getBalance(options: SuiClientTypes.GetBalanceOptions): Promise<SuiClientTypes.GetBalanceResponse>;
|
|
30
|
+
listBalances(options: SuiClientTypes.ListBalancesOptions): Promise<SuiClientTypes.ListBalancesResponse>;
|
|
31
|
+
getCoinMetadata(options: SuiClientTypes.GetCoinMetadataOptions): Promise<SuiClientTypes.GetCoinMetadataResponse>;
|
|
32
|
+
listDynamicFields<Include extends SuiClientTypes.DynamicFieldInclude = {}>(options: SuiClientTypes.ListDynamicFieldsOptions<Include>): Promise<SuiClientTypes.ListDynamicFieldsResponse<Include>>;
|
|
33
|
+
getTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(options: SuiClientTypes.GetTransactionOptions<Include>): Promise<SuiClientTypes.TransactionResult<Include>>;
|
|
34
|
+
/**
|
|
35
|
+
* Executes on the preferred transport and falls back like any other call. Resending the same
|
|
36
|
+
* signed transaction is safe: it has the same digest, so the network executes it at most once.
|
|
37
|
+
*/
|
|
38
|
+
executeTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(options: SuiClientTypes.ExecuteTransactionOptions<Include>): Promise<SuiClientTypes.TransactionResult<Include>>;
|
|
39
|
+
simulateTransaction<Include extends SuiClientTypes.SimulateTransactionInclude = {}>(options: SuiClientTypes.SimulateTransactionOptions<Include>): Promise<SuiClientTypes.SimulateTransactionResult<Include>>;
|
|
40
|
+
listTransactions<Include extends SuiClientTypes.TransactionInclude = {}>(options: SuiClientTypes.ListTransactionsOptions<Include>): Promise<SuiClientTypes.ListTransactionsResponse<Include>>;
|
|
41
|
+
listEvents(options: SuiClientTypes.ListEventsOptions): Promise<SuiClientTypes.ListEventsResponse>;
|
|
42
|
+
listCheckpoints(options: SuiClientTypes.ListCheckpointsOptions): Promise<SuiClientTypes.ListCheckpointsResponse>;
|
|
43
|
+
/**
|
|
44
|
+
* Resolves transactions (gas, object versions, input types) on the preferred transport, falling
|
|
45
|
+
* back to the other one's resolver. Once a resolver has handed over to the next plugin, errors
|
|
46
|
+
* are rethrown as they are: they come from later plugins, and resolving again would repeat them.
|
|
47
|
+
*/
|
|
48
|
+
resolveTransactionPlugin(): TransactionPlugin;
|
|
49
|
+
getReferenceGasPrice(options?: SuiClientTypes.GetReferenceGasPriceOptions): Promise<SuiClientTypes.GetReferenceGasPriceResponse>;
|
|
50
|
+
getCurrentSystemState(options?: SuiClientTypes.GetCurrentSystemStateOptions): Promise<SuiClientTypes.GetCurrentSystemStateResponse>;
|
|
51
|
+
getProtocolConfig(options?: SuiClientTypes.GetProtocolConfigOptions): Promise<SuiClientTypes.GetProtocolConfigResponse>;
|
|
52
|
+
getChainIdentifier(options?: SuiClientTypes.GetChainIdentifierOptions): Promise<SuiClientTypes.GetChainIdentifierResponse>;
|
|
53
|
+
getMoveFunction(options: SuiClientTypes.GetMoveFunctionOptions): Promise<SuiClientTypes.GetMoveFunctionResponse>;
|
|
54
|
+
verifySignature(options: SuiClientTypes.VerifySignatureOptions): Promise<SuiClientTypes.VerifySignatureResponse>;
|
|
55
|
+
defaultNameServiceName(options: SuiClientTypes.DefaultNameServiceNameOptions): Promise<SuiClientTypes.DefaultNameServiceNameResponse>;
|
|
56
|
+
resolveNameServiceAddress(options: SuiClientTypes.ResolveNameServiceAddressOptions): Promise<SuiClientTypes.ResolveNameServiceAddressResponse>;
|
|
57
|
+
/**
|
|
58
|
+
* Ledger streams run on the first transport of the `streams` preference. They reconnect and
|
|
59
|
+
* resume on their own, and their resume tokens belong to one transport, so they do not fall back.
|
|
60
|
+
* @internal
|
|
61
|
+
*/
|
|
62
|
+
protected createLedgerStreamAdapter(request: any): any;
|
|
63
|
+
}
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { CoreClient } from "@mysten/sui/client";
|
|
2
|
+
import { unwrapCursorOptions, wrapCursorFields } from "./cursors.js";
|
|
3
|
+
import { AllTransportsFailedError, isNotFound } from "./errors.js";
|
|
4
|
+
/** Cursor fields of the object-list methods and of the ledger query methods. */
|
|
5
|
+
const PAGE_REQUEST = ["cursor"];
|
|
6
|
+
const PAGE_RESPONSE = ["cursor"];
|
|
7
|
+
const LEDGER_REQUEST = ["after", "before"];
|
|
8
|
+
const LEDGER_RESPONSE = ["startCursor", "endCursor"];
|
|
9
|
+
/**
|
|
10
|
+
* The Core API of `SuiMultiClient`: every method goes to the transport its preference names, and
|
|
11
|
+
* moves to the other transport when the first fails with a fallback-eligible error.
|
|
12
|
+
*/
|
|
13
|
+
export class MultiCoreClient extends CoreClient {
|
|
14
|
+
#transports;
|
|
15
|
+
#preference;
|
|
16
|
+
#methods;
|
|
17
|
+
#fallbackOnNotFound;
|
|
18
|
+
#shouldFallback;
|
|
19
|
+
#onFallback;
|
|
20
|
+
constructor(options) {
|
|
21
|
+
super({
|
|
22
|
+
base: options.base,
|
|
23
|
+
network: options.network,
|
|
24
|
+
mvr: options.mvr,
|
|
25
|
+
restrictedMoveCalls: options.restrictedMoveCalls,
|
|
26
|
+
});
|
|
27
|
+
this.#transports = options.transports;
|
|
28
|
+
this.#preference = options.preference;
|
|
29
|
+
this.#methods = options.methods;
|
|
30
|
+
this.#fallbackOnNotFound = options.fallbackOnNotFound;
|
|
31
|
+
this.#shouldFallback = options.shouldFallback;
|
|
32
|
+
this.#onFallback = options.onFallback;
|
|
33
|
+
}
|
|
34
|
+
/** The transports `method` may use, in the order it tries them. */
|
|
35
|
+
transportOrder(method) {
|
|
36
|
+
switch (this.#methods[method] ?? this.#preference) {
|
|
37
|
+
case "grpc-first":
|
|
38
|
+
return ["grpc", "graphql"];
|
|
39
|
+
case "graphql-first":
|
|
40
|
+
return ["graphql", "grpc"];
|
|
41
|
+
case "grpc-only":
|
|
42
|
+
return ["grpc"];
|
|
43
|
+
case "graphql-only":
|
|
44
|
+
return ["graphql"];
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Runs `call` on each allowed transport in turn until one succeeds. An error that is not
|
|
49
|
+
* fallback-eligible, or any error once `signal` is aborted, is rethrown as it is. When every
|
|
50
|
+
* transport fails with an eligible error, throws `AllTransportsFailedError`.
|
|
51
|
+
*/
|
|
52
|
+
async #route(method, signal, call, { order = this.transportOrder(method), canFallback } = {}) {
|
|
53
|
+
const failures = [];
|
|
54
|
+
for (const [index, transport] of order.entries()) {
|
|
55
|
+
try {
|
|
56
|
+
return await call(this.#transports[transport], transport);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
const next = order[index + 1];
|
|
60
|
+
const eligible = !signal?.aborted &&
|
|
61
|
+
(canFallback?.() ?? true) &&
|
|
62
|
+
this.#shouldFallback(error, { method, transport, fallbackOnNotFound: this.#fallbackOnNotFound });
|
|
63
|
+
if (!eligible)
|
|
64
|
+
throw error;
|
|
65
|
+
failures.push({ transport, error });
|
|
66
|
+
if (next === undefined)
|
|
67
|
+
break;
|
|
68
|
+
this.#notify({ method, from: transport, to: next, error });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// A single allowed transport that failed keeps its own error, so `*-only` behaves like that
|
|
72
|
+
// transport's client. When every transport answered "not found", that is the answer: callers
|
|
73
|
+
// keep getting the SDK's own `TransactionError`.
|
|
74
|
+
if (failures.length === 1 || failures.every(({ error }) => isNotFound(error)))
|
|
75
|
+
throw failures.at(-1).error;
|
|
76
|
+
throw new AllTransportsFailedError(method, failures);
|
|
77
|
+
}
|
|
78
|
+
/** Routes a paginated call, keeping a page sequence on the transport that started it. */
|
|
79
|
+
async #routePaged(method, options, requestFields, responseFields, call) {
|
|
80
|
+
const { options: unwrapped, pinned } = unwrapCursorOptions(method, options, requestFields);
|
|
81
|
+
const order = pinned === null ? this.transportOrder(method) : [pinned];
|
|
82
|
+
return this.#route(method, options.signal, async (client, transport) => wrapCursorFields(transport, await call(client, unwrapped), responseFields), { order });
|
|
83
|
+
}
|
|
84
|
+
#notify(event) {
|
|
85
|
+
// A failing listener must not change the result of the call, nor leave an unhandled rejection.
|
|
86
|
+
try {
|
|
87
|
+
const result = this.#onFallback?.(event);
|
|
88
|
+
if (result instanceof Promise)
|
|
89
|
+
result.catch(() => { });
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
// Ignored, as above.
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// Objects and coins
|
|
96
|
+
getObjects(options) {
|
|
97
|
+
return this.#route("getObjects", options.signal, (client) => client.getObjects(options));
|
|
98
|
+
}
|
|
99
|
+
listOwnedObjects(options) {
|
|
100
|
+
return this.#routePaged("listOwnedObjects", options, PAGE_REQUEST, PAGE_RESPONSE, (client, o) => client.listOwnedObjects(o));
|
|
101
|
+
}
|
|
102
|
+
listCoins(options) {
|
|
103
|
+
return this.#routePaged("listCoins", options, PAGE_REQUEST, PAGE_RESPONSE, (client, o) => client.listCoins(o));
|
|
104
|
+
}
|
|
105
|
+
getBalance(options) {
|
|
106
|
+
return this.#route("getBalance", options.signal, (client) => client.getBalance(options));
|
|
107
|
+
}
|
|
108
|
+
listBalances(options) {
|
|
109
|
+
return this.#routePaged("listBalances", options, PAGE_REQUEST, PAGE_RESPONSE, (client, o) => client.listBalances(o));
|
|
110
|
+
}
|
|
111
|
+
getCoinMetadata(options) {
|
|
112
|
+
return this.#route("getCoinMetadata", options.signal, (client) => client.getCoinMetadata(options));
|
|
113
|
+
}
|
|
114
|
+
listDynamicFields(options) {
|
|
115
|
+
return this.#routePaged("listDynamicFields", options, PAGE_REQUEST, PAGE_RESPONSE, (client, o) => client.listDynamicFields(o));
|
|
116
|
+
}
|
|
117
|
+
// Transactions
|
|
118
|
+
getTransaction(options) {
|
|
119
|
+
return this.#route("getTransaction", options.signal, (client) => client.getTransaction(options));
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Executes on the preferred transport and falls back like any other call. Resending the same
|
|
123
|
+
* signed transaction is safe: it has the same digest, so the network executes it at most once.
|
|
124
|
+
*/
|
|
125
|
+
executeTransaction(options) {
|
|
126
|
+
return this.#route("executeTransaction", options.signal, (client) => client.executeTransaction(options));
|
|
127
|
+
}
|
|
128
|
+
simulateTransaction(options) {
|
|
129
|
+
return this.#route("simulateTransaction", options.signal, (client) => client.simulateTransaction(options));
|
|
130
|
+
}
|
|
131
|
+
listTransactions(options) {
|
|
132
|
+
return this.#routePaged("listTransactions", options, LEDGER_REQUEST, LEDGER_RESPONSE, (client, o) => client.listTransactions(o));
|
|
133
|
+
}
|
|
134
|
+
listEvents(options) {
|
|
135
|
+
return this.#routePaged("listEvents", options, LEDGER_REQUEST, LEDGER_RESPONSE, (client, o) => client.listEvents(o));
|
|
136
|
+
}
|
|
137
|
+
listCheckpoints(options) {
|
|
138
|
+
return this.#routePaged("listCheckpoints", options, LEDGER_REQUEST, LEDGER_RESPONSE, (client, o) => client.listCheckpoints(o));
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Resolves transactions (gas, object versions, input types) on the preferred transport, falling
|
|
142
|
+
* back to the other one's resolver. Once a resolver has handed over to the next plugin, errors
|
|
143
|
+
* are rethrown as they are: they come from later plugins, and resolving again would repeat them.
|
|
144
|
+
*/
|
|
145
|
+
resolveTransactionPlugin() {
|
|
146
|
+
return async (transactionData, options, next) => {
|
|
147
|
+
let handedOver = false;
|
|
148
|
+
const handOver = () => {
|
|
149
|
+
handedOver = true;
|
|
150
|
+
return next();
|
|
151
|
+
};
|
|
152
|
+
await this.#route("resolveTransactionPlugin", undefined, (client) => client.resolveTransactionPlugin()(transactionData, options, handOver), { canFallback: () => !handedOver });
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
// Network state
|
|
156
|
+
getReferenceGasPrice(options) {
|
|
157
|
+
return this.#route("getReferenceGasPrice", options?.signal, (client) => client.getReferenceGasPrice(options));
|
|
158
|
+
}
|
|
159
|
+
getCurrentSystemState(options) {
|
|
160
|
+
return this.#route("getCurrentSystemState", options?.signal, (client) => client.getCurrentSystemState(options));
|
|
161
|
+
}
|
|
162
|
+
getProtocolConfig(options) {
|
|
163
|
+
return this.#route("getProtocolConfig", options?.signal, (client) => client.getProtocolConfig(options));
|
|
164
|
+
}
|
|
165
|
+
getChainIdentifier(options) {
|
|
166
|
+
return this.#route("getChainIdentifier", options?.signal, (client) => client.getChainIdentifier(options));
|
|
167
|
+
}
|
|
168
|
+
// Move, signatures and names
|
|
169
|
+
getMoveFunction(options) {
|
|
170
|
+
return this.#route("getMoveFunction", options.signal, (client) => client.getMoveFunction(options));
|
|
171
|
+
}
|
|
172
|
+
verifySignature(options) {
|
|
173
|
+
return this.#route("verifySignature", options.signal, (client) => client.verifySignature(options));
|
|
174
|
+
}
|
|
175
|
+
defaultNameServiceName(options) {
|
|
176
|
+
return this.#route("defaultNameServiceName", options.signal, (client) => client.defaultNameServiceName(options));
|
|
177
|
+
}
|
|
178
|
+
resolveNameServiceAddress(options) {
|
|
179
|
+
return this.#route("resolveNameServiceAddress", options.signal, (client) => client.resolveNameServiceAddress(options));
|
|
180
|
+
}
|
|
181
|
+
// Streams
|
|
182
|
+
/**
|
|
183
|
+
* Ledger streams run on the first transport of the `streams` preference. They reconnect and
|
|
184
|
+
* resume on their own, and their resume tokens belong to one transport, so they do not fall back.
|
|
185
|
+
* @internal
|
|
186
|
+
*/
|
|
187
|
+
// The request and adapter types are not exported by @mysten/sui, and the method is protected.
|
|
188
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
189
|
+
createLedgerStreamAdapter(request) {
|
|
190
|
+
const transport = this.transportOrder("streams")[0];
|
|
191
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
192
|
+
return this.#transports[transport].createLedgerStreamAdapter(request);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Transport } from "./types.js";
|
|
2
|
+
export declare function wrapCursor(transport: Transport, cursor: string | null | undefined): string | null;
|
|
3
|
+
/**
|
|
4
|
+
* Strips the transport prefix from the cursor fields of `options`. Returns the unwrapped options
|
|
5
|
+
* and the transport the cursors pin the call to, or `null` when they carry no prefix.
|
|
6
|
+
*/
|
|
7
|
+
export declare function unwrapCursorOptions<T extends object>(method: string, options: T, fields: readonly string[]): {
|
|
8
|
+
options: T;
|
|
9
|
+
pinned: Transport | null;
|
|
10
|
+
};
|
|
11
|
+
/** Prefixes the cursor fields of a response with `transport`. */
|
|
12
|
+
export declare function wrapCursorFields<T extends object>(transport: Transport, response: T, fields: readonly string[]): T;
|
package/dist/cursors.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { MixedCursorError } from "./errors.js";
|
|
2
|
+
/**
|
|
3
|
+
* gRPC and GraphQL page cursors are not interchangeable: a cursor from one is rejected by the
|
|
4
|
+
* other. Every cursor this client returns is prefixed with the transport that produced it, so the
|
|
5
|
+
* next page goes back to that transport.
|
|
6
|
+
*/
|
|
7
|
+
const PREFIXES = { grpc: "grpc:", graphql: "graphql:" };
|
|
8
|
+
export function wrapCursor(transport, cursor) {
|
|
9
|
+
return cursor == null ? null : PREFIXES[transport] + cursor;
|
|
10
|
+
}
|
|
11
|
+
function unwrapCursor(cursor) {
|
|
12
|
+
for (const transport of Object.keys(PREFIXES)) {
|
|
13
|
+
if (cursor.startsWith(PREFIXES[transport])) {
|
|
14
|
+
return { transport, cursor: cursor.slice(PREFIXES[transport].length) };
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return { transport: null, cursor };
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Strips the transport prefix from the cursor fields of `options`. Returns the unwrapped options
|
|
21
|
+
* and the transport the cursors pin the call to, or `null` when they carry no prefix.
|
|
22
|
+
*/
|
|
23
|
+
export function unwrapCursorOptions(method, options, fields) {
|
|
24
|
+
let pinned = null;
|
|
25
|
+
const unwrapped = { ...options };
|
|
26
|
+
for (const field of fields) {
|
|
27
|
+
const value = unwrapped[field];
|
|
28
|
+
if (typeof value !== "string")
|
|
29
|
+
continue;
|
|
30
|
+
const { transport, cursor } = unwrapCursor(value);
|
|
31
|
+
unwrapped[field] = cursor;
|
|
32
|
+
if (transport === null)
|
|
33
|
+
continue;
|
|
34
|
+
if (pinned !== null && pinned !== transport)
|
|
35
|
+
throw new MixedCursorError(method);
|
|
36
|
+
pinned = transport;
|
|
37
|
+
}
|
|
38
|
+
return { options: unwrapped, pinned };
|
|
39
|
+
}
|
|
40
|
+
/** Prefixes the cursor fields of a response with `transport`. */
|
|
41
|
+
export function wrapCursorFields(transport, response, fields) {
|
|
42
|
+
const wrapped = { ...response };
|
|
43
|
+
for (const field of fields) {
|
|
44
|
+
if (field in wrapped)
|
|
45
|
+
wrapped[field] = wrapCursor(transport, wrapped[field]);
|
|
46
|
+
}
|
|
47
|
+
return wrapped;
|
|
48
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Public gRPC (fullnode) endpoints of the networks Mysten Labs runs. */
|
|
2
|
+
export declare const GRPC_ENDPOINTS: {
|
|
3
|
+
readonly mainnet: "https://fullnode.mainnet.sui.io:443";
|
|
4
|
+
readonly testnet: "https://fullnode.testnet.sui.io:443";
|
|
5
|
+
readonly devnet: "https://fullnode.devnet.sui.io:443";
|
|
6
|
+
readonly localnet: "http://127.0.0.1:9000";
|
|
7
|
+
};
|
|
8
|
+
/** Public GraphQL endpoints of the networks Mysten Labs runs. */
|
|
9
|
+
export declare const GRAPHQL_ENDPOINTS: {
|
|
10
|
+
readonly mainnet: "https://graphql.mainnet.sui.io/graphql";
|
|
11
|
+
readonly testnet: "https://graphql.testnet.sui.io/graphql";
|
|
12
|
+
readonly devnet: "https://graphql.devnet.sui.io/graphql";
|
|
13
|
+
readonly localnet: "http://127.0.0.1:9125/graphql";
|
|
14
|
+
};
|
|
15
|
+
export type KnownNetwork = keyof typeof GRPC_ENDPOINTS;
|
|
16
|
+
export declare function isKnownNetwork(network: string): network is KnownNetwork;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Public gRPC (fullnode) endpoints of the networks Mysten Labs runs. */
|
|
2
|
+
export const GRPC_ENDPOINTS = {
|
|
3
|
+
mainnet: "https://fullnode.mainnet.sui.io:443",
|
|
4
|
+
testnet: "https://fullnode.testnet.sui.io:443",
|
|
5
|
+
devnet: "https://fullnode.devnet.sui.io:443",
|
|
6
|
+
localnet: "http://127.0.0.1:9000",
|
|
7
|
+
};
|
|
8
|
+
/** Public GraphQL endpoints of the networks Mysten Labs runs. */
|
|
9
|
+
export const GRAPHQL_ENDPOINTS = {
|
|
10
|
+
mainnet: "https://graphql.mainnet.sui.io/graphql",
|
|
11
|
+
testnet: "https://graphql.testnet.sui.io/graphql",
|
|
12
|
+
devnet: "https://graphql.devnet.sui.io/graphql",
|
|
13
|
+
localnet: "http://127.0.0.1:9125/graphql",
|
|
14
|
+
};
|
|
15
|
+
export function isKnownNetwork(network) {
|
|
16
|
+
return Object.hasOwn(GRPC_ENDPOINTS, network);
|
|
17
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { SuiClientError } from "@mysten/sui/client";
|
|
2
|
+
import type { Transport } from "./types.js";
|
|
3
|
+
/** What `shouldFallback` is told about a failed call. */
|
|
4
|
+
export interface FallbackContext {
|
|
5
|
+
/** The routed Core API method, such as `getTransaction`. */
|
|
6
|
+
method: string;
|
|
7
|
+
/** The transport whose call failed. */
|
|
8
|
+
transport: Transport;
|
|
9
|
+
/** Whether to also fall back when the failed transport answered "not found". */
|
|
10
|
+
fallbackOnNotFound: boolean;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The default `shouldFallback`. Falls back when the transport failed (network errors, rate
|
|
14
|
+
* limits, server errors, pruned history), and on "not found" answers when `fallbackOnNotFound` is
|
|
15
|
+
* set, because one transport may not have indexed or may have pruned what the other still has.
|
|
16
|
+
* Never falls back on errors about the request itself, such as an invalid argument or a failed
|
|
17
|
+
* simulation, since the other transport would give the same answer.
|
|
18
|
+
*/
|
|
19
|
+
export declare function isFallbackError(error: unknown, context: FallbackContext): boolean;
|
|
20
|
+
/** Whether `error` is the SDK's "transaction not found" answer. */
|
|
21
|
+
export declare function isNotFound(error: unknown): boolean;
|
|
22
|
+
/** One failed attempt inside an {@link AllTransportsFailedError}. */
|
|
23
|
+
export interface TransportFailure {
|
|
24
|
+
transport: Transport;
|
|
25
|
+
error: unknown;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Thrown when every transport a call was allowed to use failed with a fallback-eligible error.
|
|
29
|
+
* `failures` lists each attempt in order; `cause` is the last one's error.
|
|
30
|
+
*/
|
|
31
|
+
export declare class AllTransportsFailedError extends SuiClientError {
|
|
32
|
+
readonly method: string;
|
|
33
|
+
readonly failures: readonly TransportFailure[];
|
|
34
|
+
constructor(method: string, failures: readonly TransportFailure[]);
|
|
35
|
+
}
|
|
36
|
+
/** Thrown when one request carries cursors from different transports. */
|
|
37
|
+
export declare class MixedCursorError extends SuiClientError {
|
|
38
|
+
constructor(method: string);
|
|
39
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { SuiClientError, TransactionError } from "@mysten/sui/client";
|
|
2
|
+
/**
|
|
3
|
+
* gRPC status codes that describe the endpoint rather than the request: the same request may
|
|
4
|
+
* succeed on another transport. `OUT_OF_RANGE` is what a pruned fullnode returns for history it no
|
|
5
|
+
* longer keeps, which an archival GraphQL service can still serve.
|
|
6
|
+
*/
|
|
7
|
+
const FALLBACK_GRPC_CODES = new Set([
|
|
8
|
+
"UNAVAILABLE",
|
|
9
|
+
"DEADLINE_EXCEEDED",
|
|
10
|
+
"RESOURCE_EXHAUSTED",
|
|
11
|
+
"INTERNAL",
|
|
12
|
+
"UNKNOWN",
|
|
13
|
+
"UNIMPLEMENTED",
|
|
14
|
+
"OUT_OF_RANGE",
|
|
15
|
+
"CANCELLED",
|
|
16
|
+
"UNAUTHENTICATED",
|
|
17
|
+
"PERMISSION_DENIED",
|
|
18
|
+
]);
|
|
19
|
+
/**
|
|
20
|
+
* The default `shouldFallback`. Falls back when the transport failed (network errors, rate
|
|
21
|
+
* limits, server errors, pruned history), and on "not found" answers when `fallbackOnNotFound` is
|
|
22
|
+
* set, because one transport may not have indexed or may have pruned what the other still has.
|
|
23
|
+
* Never falls back on errors about the request itself, such as an invalid argument or a failed
|
|
24
|
+
* simulation, since the other transport would give the same answer.
|
|
25
|
+
*/
|
|
26
|
+
export function isFallbackError(error, context) {
|
|
27
|
+
if (isNotFound(error))
|
|
28
|
+
return context.fallbackOnNotFound;
|
|
29
|
+
return isTransportFailure(error, 0);
|
|
30
|
+
}
|
|
31
|
+
/** How many `cause` links to follow; SDK wrappers nest one or two deep. */
|
|
32
|
+
const MAX_CAUSE_DEPTH = 4;
|
|
33
|
+
function isTransportFailure(error, depth) {
|
|
34
|
+
if (!(error instanceof Error))
|
|
35
|
+
return false;
|
|
36
|
+
// SuiGraphQLRequestError sets `reason` when repeating the request may succeed.
|
|
37
|
+
if (error instanceof SuiClientError && "reason" in error) {
|
|
38
|
+
const reason = error.reason;
|
|
39
|
+
return reason === "Unavailable" || reason === "RateLimited" || reason === "ServerError";
|
|
40
|
+
}
|
|
41
|
+
// gRPC failures are protobuf-ts RpcErrors, recognised by shape so this package needs no
|
|
42
|
+
// direct dependency on @protobuf-ts/runtime-rpc.
|
|
43
|
+
const code = error.code;
|
|
44
|
+
if (error.name === "RpcError" && typeof code === "string")
|
|
45
|
+
return FALLBACK_GRPC_CODES.has(code);
|
|
46
|
+
// A fetch that failed before any response, as thrown by undici and browsers.
|
|
47
|
+
if (error.name === "TypeError" && /fetch/i.test(error.message))
|
|
48
|
+
return true;
|
|
49
|
+
// The SDK wraps some transport failures in its own errors: the gRPC transaction resolver throws
|
|
50
|
+
// a SimulationError whose `cause` is the RpcError. Judge those by what they wrap. A real
|
|
51
|
+
// simulation failure carries no cause, and a wrapped request error is still not eligible.
|
|
52
|
+
return error instanceof SuiClientError && depth < MAX_CAUSE_DEPTH && isTransportFailure(error.cause, depth + 1);
|
|
53
|
+
}
|
|
54
|
+
/** Whether `error` is the SDK's "transaction not found" answer. */
|
|
55
|
+
export function isNotFound(error) {
|
|
56
|
+
return error instanceof TransactionError && error.reason === "notFound";
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Thrown when every transport a call was allowed to use failed with a fallback-eligible error.
|
|
60
|
+
* `failures` lists each attempt in order; `cause` is the last one's error.
|
|
61
|
+
*/
|
|
62
|
+
export class AllTransportsFailedError extends SuiClientError {
|
|
63
|
+
method;
|
|
64
|
+
failures;
|
|
65
|
+
constructor(method, failures) {
|
|
66
|
+
const summary = failures
|
|
67
|
+
.map(({ transport, error }) => `${transport}: ${error instanceof Error ? error.message : String(error)}`)
|
|
68
|
+
.join("; ");
|
|
69
|
+
super(`${method} failed on every transport (${summary})`, { cause: failures.at(-1)?.error });
|
|
70
|
+
this.name = "AllTransportsFailedError";
|
|
71
|
+
this.method = method;
|
|
72
|
+
this.failures = failures;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** Thrown when one request carries cursors from different transports. */
|
|
76
|
+
export class MixedCursorError extends SuiClientError {
|
|
77
|
+
constructor(method) {
|
|
78
|
+
super(`${method} was given cursors from different transports; a page sequence must stay on one transport`);
|
|
79
|
+
this.name = "MixedCursorError";
|
|
80
|
+
}
|
|
81
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { SuiMultiClient } from "./client.js";
|
|
2
|
+
export { MultiCoreClient, type MultiCoreClientOptions } from "./core.js";
|
|
3
|
+
export { GRAPHQL_ENDPOINTS, GRPC_ENDPOINTS, type KnownNetwork } from "./endpoints.js";
|
|
4
|
+
export { AllTransportsFailedError, MixedCursorError, isFallbackError, type FallbackContext, type TransportFailure, } from "./errors.js";
|
|
5
|
+
export { ROUTED_METHODS, TRANSPORT_PREFERENCES, type FallbackEvent, type RoutedMethod, type SuiMultiClientOptions, type Transport, type TransportPreference, } from "./types.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { SuiMultiClient } from "./client.js";
|
|
2
|
+
export { MultiCoreClient } from "./core.js";
|
|
3
|
+
export { GRAPHQL_ENDPOINTS, GRPC_ENDPOINTS } from "./endpoints.js";
|
|
4
|
+
export { AllTransportsFailedError, MixedCursorError, isFallbackError, } from "./errors.js";
|
|
5
|
+
export { ROUTED_METHODS, TRANSPORT_PREFERENCES, } from "./types.js";
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { SuiClientTypes } from "@mysten/sui/client";
|
|
2
|
+
import type { SuiGraphQLClient } from "@mysten/sui/graphql";
|
|
3
|
+
import type { SuiGrpcClient } from "@mysten/sui/grpc";
|
|
4
|
+
import type { FallbackContext } from "./errors.js";
|
|
5
|
+
/** A transport the client can send a call over. */
|
|
6
|
+
export type Transport = "grpc" | "graphql";
|
|
7
|
+
/** The values of {@link TransportPreference}. */
|
|
8
|
+
export declare const TRANSPORT_PREFERENCES: readonly ["grpc-first", "graphql-first", "grpc-only", "graphql-only"];
|
|
9
|
+
/**
|
|
10
|
+
* How a call picks its transport. `*-first` tries that transport and falls back to the other on a
|
|
11
|
+
* fallback-eligible error; `*-only` never falls back.
|
|
12
|
+
*/
|
|
13
|
+
export type TransportPreference = (typeof TRANSPORT_PREFERENCES)[number];
|
|
14
|
+
/** The Core API methods the client routes, plus `streams` for the ledger streams. */
|
|
15
|
+
export declare const ROUTED_METHODS: readonly ["getObjects", "listOwnedObjects", "listCoins", "getBalance", "listBalances", "getCoinMetadata", "getTransaction", "executeTransaction", "simulateTransaction", "getReferenceGasPrice", "getCurrentSystemState", "getProtocolConfig", "getChainIdentifier", "listDynamicFields", "listTransactions", "listEvents", "listCheckpoints", "getMoveFunction", "verifySignature", "defaultNameServiceName", "resolveNameServiceAddress", "resolveTransactionPlugin", "streams"];
|
|
16
|
+
/** A method `methods` can set a preference for. */
|
|
17
|
+
export type RoutedMethod = (typeof ROUTED_METHODS)[number];
|
|
18
|
+
/** Reported to `onFallback` each time a call moves to the other transport. */
|
|
19
|
+
export interface FallbackEvent {
|
|
20
|
+
method: RoutedMethod;
|
|
21
|
+
from: Transport;
|
|
22
|
+
to: Transport;
|
|
23
|
+
error: unknown;
|
|
24
|
+
}
|
|
25
|
+
export interface SuiMultiClientOptions {
|
|
26
|
+
/** The network both transports serve. Known networks get default endpoints. */
|
|
27
|
+
network: SuiClientTypes.Network;
|
|
28
|
+
/**
|
|
29
|
+
* The gRPC side: a ready `SuiGrpcClient`, or its `baseUrl`. Defaults to the public fullnode of
|
|
30
|
+
* `network` for mainnet, testnet, devnet and localnet.
|
|
31
|
+
*/
|
|
32
|
+
grpc?: SuiGrpcClient | {
|
|
33
|
+
baseUrl: string;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* The GraphQL side: a ready `SuiGraphQLClient`, or its `url`. Defaults to the public GraphQL
|
|
37
|
+
* service of `network` for mainnet, testnet, devnet and localnet.
|
|
38
|
+
*/
|
|
39
|
+
graphql?: SuiGraphQLClient | {
|
|
40
|
+
url: string;
|
|
41
|
+
};
|
|
42
|
+
/** The preference for every method without its own entry in `methods`. Defaults to `grpc-first`. */
|
|
43
|
+
preference?: TransportPreference;
|
|
44
|
+
/** Per-method preferences, overriding `preference`. */
|
|
45
|
+
methods?: Partial<Record<RoutedMethod, TransportPreference>>;
|
|
46
|
+
/**
|
|
47
|
+
* Whether a "not found" answer from one transport is retried on the other. A pruned fullnode
|
|
48
|
+
* answers "not found" for old transactions, and a lagging indexer for new ones. Defaults to
|
|
49
|
+
* `true`; it costs one extra request whenever the answer really is "not found".
|
|
50
|
+
*/
|
|
51
|
+
fallbackOnNotFound?: boolean;
|
|
52
|
+
/** Decides whether an error moves the call to the other transport. Defaults to `isFallbackError`. */
|
|
53
|
+
shouldFallback?: (error: unknown, context: FallbackContext) => boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Called each time a call falls back, for logging and metrics. It may be async; what it throws
|
|
56
|
+
* or rejects with is ignored and never changes the result of the call.
|
|
57
|
+
*/
|
|
58
|
+
onFallback?: (event: FallbackEvent) => unknown;
|
|
59
|
+
/** Move Registry options, as on `SuiGrpcClient`. */
|
|
60
|
+
mvr?: SuiClientTypes.MvrOptions;
|
|
61
|
+
/** Move calls transactions built with this client may not make, as on `SuiGrpcClient`. */
|
|
62
|
+
restrictedMoveCalls?: readonly string[];
|
|
63
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** The values of {@link TransportPreference}. */
|
|
2
|
+
export const TRANSPORT_PREFERENCES = ["grpc-first", "graphql-first", "grpc-only", "graphql-only"];
|
|
3
|
+
/** The Core API methods the client routes, plus `streams` for the ledger streams. */
|
|
4
|
+
export const ROUTED_METHODS = [
|
|
5
|
+
"getObjects",
|
|
6
|
+
"listOwnedObjects",
|
|
7
|
+
"listCoins",
|
|
8
|
+
"getBalance",
|
|
9
|
+
"listBalances",
|
|
10
|
+
"getCoinMetadata",
|
|
11
|
+
"getTransaction",
|
|
12
|
+
"executeTransaction",
|
|
13
|
+
"simulateTransaction",
|
|
14
|
+
"getReferenceGasPrice",
|
|
15
|
+
"getCurrentSystemState",
|
|
16
|
+
"getProtocolConfig",
|
|
17
|
+
"getChainIdentifier",
|
|
18
|
+
"listDynamicFields",
|
|
19
|
+
"listTransactions",
|
|
20
|
+
"listEvents",
|
|
21
|
+
"listCheckpoints",
|
|
22
|
+
"getMoveFunction",
|
|
23
|
+
"verifySignature",
|
|
24
|
+
"defaultNameServiceName",
|
|
25
|
+
"resolveNameServiceAddress",
|
|
26
|
+
"resolveTransactionPlugin",
|
|
27
|
+
"streams",
|
|
28
|
+
];
|
package/package.json
CHANGED
|
@@ -1,6 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sui-multi-client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A Sui Core API client that uses gRPC and GraphQL together and falls back from one to the other when a transport fails",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"import": "./dist/index.js",
|
|
10
|
+
"default": "./dist/index.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
22
|
+
"typecheck": "tsc --noEmit",
|
|
23
|
+
"lint": "eslint .",
|
|
24
|
+
"test": "vitest run",
|
|
25
|
+
"test:integration": "vitest run --config vitest.integration.config.ts",
|
|
26
|
+
"prepublishOnly": "yarn lint && yarn typecheck && yarn test && yarn build"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"sui",
|
|
30
|
+
"sui-client",
|
|
31
|
+
"core-api",
|
|
32
|
+
"graphql",
|
|
33
|
+
"grpc",
|
|
34
|
+
"fallback",
|
|
35
|
+
"failover",
|
|
36
|
+
"typescript"
|
|
37
|
+
],
|
|
38
|
+
"author": "Berk Turan",
|
|
39
|
+
"license": "MIT",
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "git+https://github.com/berk-turan/sui-multi-client.git"
|
|
43
|
+
},
|
|
44
|
+
"bugs": {
|
|
45
|
+
"url": "https://github.com/berk-turan/sui-multi-client/issues"
|
|
46
|
+
},
|
|
47
|
+
"homepage": "https://github.com/berk-turan/sui-multi-client#readme",
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=22"
|
|
50
|
+
},
|
|
51
|
+
"peerDependencies": {
|
|
52
|
+
"@mysten/sui": "^3.0.0"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@eslint/js": "^10.0.1",
|
|
56
|
+
"@mysten/sui": "^3.1.1",
|
|
57
|
+
"@types/node": "^24.19.4",
|
|
58
|
+
"eslint": "^10.0.0",
|
|
59
|
+
"typescript": "~6.0.3",
|
|
60
|
+
"typescript-eslint": "^8.74.0",
|
|
61
|
+
"vite": "^8.4.1",
|
|
62
|
+
"vitest": "^5.1.2"
|
|
63
|
+
}
|
|
64
|
+
}
|