@opendatalabs/vana-sdk 0.1.0-alpha.f2a82f7 → 0.1.0-alpha.f35bb9c
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/dist/controllers/base.cjs +0 -33
- package/dist/controllers/base.cjs.map +1 -1
- package/dist/controllers/base.d.ts +0 -10
- package/dist/controllers/base.js +0 -33
- package/dist/controllers/base.js.map +1 -1
- package/dist/controllers/data.cjs +19 -26
- package/dist/controllers/data.cjs.map +1 -1
- package/dist/controllers/data.d.ts +9 -9
- package/dist/controllers/data.js +19 -26
- package/dist/controllers/data.js.map +1 -1
- package/dist/controllers/permissions.cjs +65 -124
- package/dist/controllers/permissions.cjs.map +1 -1
- package/dist/controllers/permissions.d.ts +11 -20
- package/dist/controllers/permissions.js +65 -124
- package/dist/controllers/permissions.js.map +1 -1
- package/dist/core.cjs +1 -4
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.ts +1 -2
- package/dist/core.js +1 -4
- package/dist/core.js.map +1 -1
- package/dist/index.node.cjs +0 -2
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.d.ts +4 -27
- package/dist/index.node.js +0 -2
- package/dist/index.node.js.map +1 -1
- package/dist/server/relayerHandler.cjs +87 -201
- package/dist/server/relayerHandler.cjs.map +1 -1
- package/dist/server/relayerHandler.d.ts +1 -3
- package/dist/server/relayerHandler.js +87 -201
- package/dist/server/relayerHandler.js.map +1 -1
- package/dist/types/config.cjs.map +1 -1
- package/dist/types/config.d.ts +0 -32
- package/dist/types/config.js.map +1 -1
- package/dist/types/controller-context.cjs.map +1 -1
- package/dist/types/controller-context.d.ts +1 -3
- package/dist/types/generics.cjs.map +1 -1
- package/dist/types/generics.d.ts +1 -1
- package/dist/types/index.cjs.map +1 -1
- package/dist/types/index.d.ts +2 -3
- package/dist/types/index.js.map +1 -1
- package/dist/types/operations.cjs.map +1 -1
- package/dist/types/operations.d.ts +0 -46
- package/dist/types/operations.js.map +1 -1
- package/dist/types/relayer.cjs.map +1 -1
- package/dist/types/relayer.d.ts +8 -19
- package/dist/utils/ipfs.cjs +4 -2
- package/dist/utils/ipfs.cjs.map +1 -1
- package/dist/utils/ipfs.d.ts +1 -1
- package/dist/utils/ipfs.js +4 -2
- package/dist/utils/ipfs.js.map +1 -1
- package/package.json +1 -3
|
@@ -1,168 +1,46 @@
|
|
|
1
|
-
import { v4 as uuidv4 } from "uuid";
|
|
2
1
|
import { SignatureError } from "../errors";
|
|
3
2
|
import { recoverTypedDataAddress, getAddress } from "viem";
|
|
4
|
-
async function handleRelayerOperation(sdk, request
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
if (request.type === "status_check") {
|
|
8
|
-
const state = await store.get(request.operationId);
|
|
9
|
-
if (!state) return { type: "error", error: "Operation not found" };
|
|
10
|
-
if (state.status === "confirmed")
|
|
11
|
-
return {
|
|
12
|
-
type: "confirmed",
|
|
13
|
-
hash: state.transactionHash,
|
|
14
|
-
receipt: state.finalReceipt
|
|
15
|
-
};
|
|
16
|
-
if (state.status === "failed")
|
|
17
|
-
return { type: "error", error: state.error ?? "Operation failed" };
|
|
18
|
-
if (state.status === "pending") {
|
|
19
|
-
try {
|
|
20
|
-
const publicClient = sdk.publicClient;
|
|
21
|
-
if (publicClient) {
|
|
22
|
-
let receipt;
|
|
23
|
-
try {
|
|
24
|
-
receipt = await publicClient.getTransactionReceipt({
|
|
25
|
-
hash: state.transactionHash
|
|
26
|
-
});
|
|
27
|
-
} catch (receiptError) {
|
|
28
|
-
if (receiptError?.name !== "TransactionReceiptNotFoundError") {
|
|
29
|
-
console.warn(
|
|
30
|
-
`\u26A0\uFE0F [Relayer] Unexpected error checking receipt:`,
|
|
31
|
-
receiptError?.message ?? receiptError
|
|
32
|
-
);
|
|
33
|
-
}
|
|
34
|
-
receipt = null;
|
|
35
|
-
}
|
|
36
|
-
if (receipt) {
|
|
37
|
-
const updatedState = {
|
|
38
|
-
...state,
|
|
39
|
-
status: receipt.status === "success" ? "confirmed" : "failed",
|
|
40
|
-
finalReceipt: receipt,
|
|
41
|
-
...receipt.status !== "success" && {
|
|
42
|
-
error: "Transaction reverted on chain"
|
|
43
|
-
}
|
|
44
|
-
};
|
|
45
|
-
await store.set(request.operationId, updatedState);
|
|
46
|
-
if (receipt.status === "success") {
|
|
47
|
-
return {
|
|
48
|
-
type: "confirmed",
|
|
49
|
-
hash: state.transactionHash,
|
|
50
|
-
receipt
|
|
51
|
-
};
|
|
52
|
-
} else {
|
|
53
|
-
return {
|
|
54
|
-
type: "error",
|
|
55
|
-
error: "Transaction reverted on chain"
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
} else {
|
|
60
|
-
console.warn(
|
|
61
|
-
"\u26A0\uFE0F [Relayer] No public client available for status checking"
|
|
62
|
-
);
|
|
63
|
-
}
|
|
64
|
-
} catch (error) {
|
|
65
|
-
console.error(
|
|
66
|
-
`\u274C [Relayer] Unexpected error in status check:`,
|
|
67
|
-
error
|
|
68
|
-
);
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
return { type: "pending", operationId: request.operationId };
|
|
72
|
-
}
|
|
73
|
-
const operationId = uuidv4();
|
|
74
|
-
try {
|
|
75
|
-
const txResult = await routeAndExecuteRequest(sdk, request, options);
|
|
76
|
-
if ("hash" in txResult) {
|
|
77
|
-
await store.set(operationId, {
|
|
78
|
-
status: "pending",
|
|
79
|
-
transactionHash: txResult.hash,
|
|
80
|
-
originalRequest: request,
|
|
81
|
-
nonce: options?.nonce,
|
|
82
|
-
retryCount: 0,
|
|
83
|
-
lastAttemptedGas: {
|
|
84
|
-
maxFeePerGas: options?.maxFeePerGas?.toString(),
|
|
85
|
-
maxPriorityFeePerGas: options?.maxPriorityFeePerGas?.toString()
|
|
86
|
-
},
|
|
87
|
-
submittedAt: Date.now()
|
|
88
|
-
});
|
|
89
|
-
return { type: "pending", operationId };
|
|
90
|
-
} else {
|
|
91
|
-
return { type: "direct", result: txResult };
|
|
92
|
-
}
|
|
93
|
-
} catch (e) {
|
|
94
|
-
const error = e instanceof Error ? e : new Error("Unknown error during operation submission");
|
|
95
|
-
return { type: "error", error: error.message };
|
|
96
|
-
}
|
|
97
|
-
} else {
|
|
98
|
-
if (request.type === "status_check") {
|
|
99
|
-
return {
|
|
100
|
-
type: "error",
|
|
101
|
-
error: "Stateless relayer does not support operation status checks."
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
try {
|
|
105
|
-
const txResult = await routeAndExecuteRequest(sdk, request, options);
|
|
106
|
-
if ("hash" in txResult) {
|
|
107
|
-
return { type: "submitted", hash: txResult.hash };
|
|
108
|
-
} else {
|
|
109
|
-
return { type: "direct", result: txResult };
|
|
110
|
-
}
|
|
111
|
-
} catch (e) {
|
|
112
|
-
const error = e instanceof Error ? e : new Error("Unknown error during operation submission");
|
|
113
|
-
return { type: "error", error: error.message };
|
|
114
|
-
}
|
|
3
|
+
async function handleRelayerOperation(sdk, request) {
|
|
4
|
+
if (request.type === "signed") {
|
|
5
|
+
return handleSignedOperation(sdk, request);
|
|
115
6
|
}
|
|
7
|
+
return handleDirectOperation(sdk, request);
|
|
116
8
|
}
|
|
117
|
-
async function
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
domain
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
9
|
+
async function handleSignedOperation(sdk, request) {
|
|
10
|
+
const { typedData, signature, expectedUserAddress } = request;
|
|
11
|
+
let recoveredAddress;
|
|
12
|
+
try {
|
|
13
|
+
recoveredAddress = await recoverTypedDataAddress({
|
|
14
|
+
domain: {
|
|
15
|
+
...typedData.domain,
|
|
16
|
+
chainId: typedData.domain.chainId ? BigInt(typedData.domain.chainId) : void 0
|
|
17
|
+
},
|
|
18
|
+
types: typedData.types,
|
|
19
|
+
primaryType: typedData.primaryType,
|
|
20
|
+
message: typedData.message,
|
|
21
|
+
signature
|
|
22
|
+
});
|
|
23
|
+
} catch (error) {
|
|
24
|
+
throw new SignatureError(
|
|
25
|
+
`Signature verification failed: ${error instanceof Error ? error.message : "Unknown error"}`
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
if (expectedUserAddress) {
|
|
29
|
+
const normalizedExpected = getAddress(expectedUserAddress);
|
|
30
|
+
const normalizedSigner = getAddress(recoveredAddress);
|
|
31
|
+
if (normalizedSigner !== normalizedExpected) {
|
|
133
32
|
throw new SignatureError(
|
|
134
|
-
`
|
|
33
|
+
`Security verification failed: Recovered signer address (${normalizedSigner}) does not match expected user address (${normalizedExpected})`
|
|
135
34
|
);
|
|
136
35
|
}
|
|
137
|
-
if (expectedUserAddress) {
|
|
138
|
-
const normalizedExpected = getAddress(expectedUserAddress);
|
|
139
|
-
const normalizedSigner = getAddress(recoveredAddress);
|
|
140
|
-
if (normalizedSigner !== normalizedExpected) {
|
|
141
|
-
throw new SignatureError(
|
|
142
|
-
`Security verification failed: Recovered signer address (${normalizedSigner}) does not match expected user address (${normalizedExpected})`
|
|
143
|
-
);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
return await routeSignedOperation(sdk, typedData, signature, options);
|
|
147
|
-
} else if (request.type === "direct") {
|
|
148
|
-
return await handleDirectOperation(sdk, request, options);
|
|
149
36
|
}
|
|
150
|
-
|
|
37
|
+
const result = await routeSignedOperation(sdk, typedData, signature);
|
|
38
|
+
return {
|
|
39
|
+
type: "signed",
|
|
40
|
+
hash: result.hash
|
|
41
|
+
};
|
|
151
42
|
}
|
|
152
|
-
async function routeSignedOperation(sdk, typedData, signature
|
|
153
|
-
const validPrimaryTypes = [
|
|
154
|
-
"Permission",
|
|
155
|
-
"RevokePermission",
|
|
156
|
-
"TrustServer",
|
|
157
|
-
"AddServer",
|
|
158
|
-
"UntrustServer",
|
|
159
|
-
"ServerFilesAndPermission"
|
|
160
|
-
];
|
|
161
|
-
if (!validPrimaryTypes.includes(typedData.primaryType)) {
|
|
162
|
-
throw new Error(
|
|
163
|
-
`Unsupported operation type: ${typedData.primaryType}. Supported types: ${validPrimaryTypes.join(", ")}`
|
|
164
|
-
);
|
|
165
|
-
}
|
|
43
|
+
async function routeSignedOperation(sdk, typedData, signature) {
|
|
166
44
|
const primaryType = typedData.primaryType;
|
|
167
45
|
switch (primaryType) {
|
|
168
46
|
case "Permission":
|
|
@@ -171,8 +49,7 @@ async function routeSignedOperation(sdk, typedData, signature, options) {
|
|
|
171
49
|
...typedData,
|
|
172
50
|
primaryType: "Permission"
|
|
173
51
|
},
|
|
174
|
-
signature
|
|
175
|
-
options
|
|
52
|
+
signature
|
|
176
53
|
);
|
|
177
54
|
case "RevokePermission":
|
|
178
55
|
return sdk.permissions.submitSignedRevoke(
|
|
@@ -180,8 +57,7 @@ async function routeSignedOperation(sdk, typedData, signature, options) {
|
|
|
180
57
|
...typedData,
|
|
181
58
|
primaryType: "RevokePermission"
|
|
182
59
|
},
|
|
183
|
-
signature
|
|
184
|
-
options
|
|
60
|
+
signature
|
|
185
61
|
);
|
|
186
62
|
case "TrustServer":
|
|
187
63
|
return sdk.permissions.submitSignedTrustServer(
|
|
@@ -189,8 +65,7 @@ async function routeSignedOperation(sdk, typedData, signature, options) {
|
|
|
189
65
|
...typedData,
|
|
190
66
|
primaryType: "TrustServer"
|
|
191
67
|
},
|
|
192
|
-
signature
|
|
193
|
-
options
|
|
68
|
+
signature
|
|
194
69
|
);
|
|
195
70
|
case "AddServer":
|
|
196
71
|
return sdk.permissions.submitSignedAddAndTrustServer(
|
|
@@ -198,8 +73,7 @@ async function routeSignedOperation(sdk, typedData, signature, options) {
|
|
|
198
73
|
...typedData,
|
|
199
74
|
primaryType: "AddServer"
|
|
200
75
|
},
|
|
201
|
-
signature
|
|
202
|
-
options
|
|
76
|
+
signature
|
|
203
77
|
);
|
|
204
78
|
case "UntrustServer":
|
|
205
79
|
return sdk.permissions.submitSignedUntrustServer(
|
|
@@ -207,8 +81,7 @@ async function routeSignedOperation(sdk, typedData, signature, options) {
|
|
|
207
81
|
...typedData,
|
|
208
82
|
primaryType: "UntrustServer"
|
|
209
83
|
},
|
|
210
|
-
signature
|
|
211
|
-
options
|
|
84
|
+
signature
|
|
212
85
|
);
|
|
213
86
|
case "ServerFilesAndPermission":
|
|
214
87
|
return sdk.permissions.submitSignedAddServerFilesAndPermissions(
|
|
@@ -216,81 +89,94 @@ async function routeSignedOperation(sdk, typedData, signature, options) {
|
|
|
216
89
|
...typedData,
|
|
217
90
|
primaryType: "ServerFilesAndPermission"
|
|
218
91
|
},
|
|
219
|
-
signature
|
|
220
|
-
options
|
|
92
|
+
signature
|
|
221
93
|
);
|
|
222
94
|
// TODO: RegisterGrantee with signature is not supported until
|
|
223
95
|
// DataPortabilityGrantees contract adds registerGranteeWithSignature function
|
|
224
96
|
// case "RegisterGrantee":
|
|
225
97
|
// return sdk.permissions.submitSignedRegisterGrantee(...);
|
|
226
98
|
default:
|
|
227
|
-
throw new Error(
|
|
228
|
-
`Unsupported operation type: ${typedData.primaryType}. Supported types: Permission, RevokePermission, TrustServer, AddServer, UntrustServer, ServerFilesAndPermission`
|
|
229
|
-
);
|
|
99
|
+
throw new Error(`Unsupported operation type: ${typedData.primaryType}`);
|
|
230
100
|
}
|
|
231
101
|
}
|
|
232
|
-
async function handleDirectOperation(sdk, request
|
|
102
|
+
async function handleDirectOperation(sdk, request) {
|
|
233
103
|
switch (request.operation) {
|
|
234
104
|
case "submitFileAddition": {
|
|
235
105
|
const { url, userAddress } = request.params;
|
|
236
106
|
const result = await sdk.data.addFileWithPermissions(
|
|
237
107
|
url,
|
|
238
108
|
userAddress,
|
|
239
|
-
[]
|
|
109
|
+
[]
|
|
240
110
|
// No permissions
|
|
241
|
-
options
|
|
242
111
|
);
|
|
243
|
-
|
|
112
|
+
const eventData = await sdk.waitForTransactionEvents(result);
|
|
113
|
+
const fileId = eventData.expectedEvents?.FileAdded?.fileId;
|
|
114
|
+
if (!fileId) {
|
|
115
|
+
throw new Error("Failed to get fileId from transaction events");
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
type: "direct",
|
|
119
|
+
result: {
|
|
120
|
+
fileId: Number(fileId),
|
|
121
|
+
transactionHash: result.hash
|
|
122
|
+
}
|
|
123
|
+
};
|
|
244
124
|
}
|
|
245
125
|
case "submitFileAdditionWithPermissions": {
|
|
246
126
|
const { url, userAddress, permissions } = request.params;
|
|
247
127
|
const result = await sdk.data.addFileWithPermissions(
|
|
248
128
|
url,
|
|
249
129
|
userAddress,
|
|
250
|
-
permissions
|
|
251
|
-
options
|
|
130
|
+
permissions
|
|
252
131
|
);
|
|
253
|
-
|
|
132
|
+
const eventData = await sdk.waitForTransactionEvents(result);
|
|
133
|
+
const fileId = eventData.expectedEvents?.FileAdded?.fileId;
|
|
134
|
+
if (!fileId) {
|
|
135
|
+
throw new Error("Failed to get fileId from transaction events");
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
type: "direct",
|
|
139
|
+
result: {
|
|
140
|
+
fileId: Number(fileId),
|
|
141
|
+
transactionHash: result.hash
|
|
142
|
+
}
|
|
143
|
+
};
|
|
254
144
|
}
|
|
255
145
|
case "submitFileAdditionComplete": {
|
|
256
146
|
const { url, userAddress, permissions, schemaId, ownerAddress } = request.params;
|
|
257
|
-
const
|
|
147
|
+
const result = await sdk.data.addFileWithEncryptedPermissionsAndSchema(
|
|
258
148
|
url,
|
|
259
149
|
ownerAddress ?? userAddress,
|
|
260
150
|
permissions,
|
|
261
151
|
// Already in correct format with encrypted 'key' field
|
|
262
|
-
schemaId
|
|
263
|
-
options
|
|
152
|
+
schemaId
|
|
264
153
|
);
|
|
265
|
-
const
|
|
266
|
-
const
|
|
267
|
-
if (!
|
|
268
|
-
|
|
269
|
-
throw new Error("FileAdded event not found in transaction");
|
|
154
|
+
const eventData = await sdk.waitForTransactionEvents(result);
|
|
155
|
+
const fileId = eventData.expectedEvents?.FileAdded?.fileId;
|
|
156
|
+
if (!fileId) {
|
|
157
|
+
throw new Error("Failed to get fileId from transaction events");
|
|
270
158
|
}
|
|
271
|
-
const fileId = Number(fileAddedEvent.fileId);
|
|
272
159
|
return {
|
|
273
|
-
|
|
274
|
-
|
|
160
|
+
type: "direct",
|
|
161
|
+
result: {
|
|
162
|
+
fileId: Number(fileId),
|
|
163
|
+
transactionHash: result.hash
|
|
164
|
+
}
|
|
275
165
|
};
|
|
276
166
|
}
|
|
277
167
|
case "storeGrantFile": {
|
|
278
168
|
const grantFile = request.params;
|
|
279
|
-
const dataController = sdk.data;
|
|
280
|
-
const context = dataController.context;
|
|
281
|
-
if (!context?.storageManager) {
|
|
282
|
-
throw new Error(
|
|
283
|
-
"Storage configuration is required for storing grant files"
|
|
284
|
-
);
|
|
285
|
-
}
|
|
286
169
|
const blob = new Blob([JSON.stringify(grantFile)], {
|
|
287
170
|
type: "application/json"
|
|
288
171
|
});
|
|
289
|
-
const
|
|
290
|
-
blob,
|
|
291
|
-
`grant-${Date.now()}.json`
|
|
292
|
-
);
|
|
293
|
-
return {
|
|
172
|
+
const result = await sdk.data.upload({
|
|
173
|
+
content: blob,
|
|
174
|
+
filename: `grant-${Date.now()}.json`
|
|
175
|
+
});
|
|
176
|
+
return {
|
|
177
|
+
type: "direct",
|
|
178
|
+
result: { url: result.url }
|
|
179
|
+
};
|
|
294
180
|
}
|
|
295
181
|
default: {
|
|
296
182
|
const exhaustiveCheck = request;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/relayerHandler.ts"],"sourcesContent":["import { v4 as uuidv4 } from \"uuid\";\nimport type { VanaInstance } from \"../index.node\";\nimport type {\n UnifiedRelayerRequest,\n UnifiedRelayerResponse,\n DirectRelayerRequest,\n} from \"../types/relayer\";\nimport type {\n TransactionResult,\n TransactionOptions,\n IOperationStore,\n OperationState,\n TransactionReceipt,\n} from \"../types\";\nimport type { Contract, Fn } from \"../generated/event-types\";\nimport type {\n GenericTypedData,\n PermissionGrantTypedData,\n RevokePermissionTypedData,\n TrustServerTypedData,\n AddAndTrustServerTypedData,\n ServerFilesAndPermissionTypedData,\n TypedDataPrimaryType,\n} from \"../types/permissions\";\nimport { SignatureError } from \"../errors\";\nimport { recoverTypedDataAddress, getAddress, type Hash } from \"viem\";\n\n/**\n * Universal handler for all relayer operations.\n *\n * This function processes both EIP-712 signed operations and direct operations,\n * automatically routing to the appropriate SDK methods.\n *\n * @param sdk - Initialized Vana SDK instance\n * @param request - The unified relayer request\n * @returns Promise resolving to operation-specific response\n *\n * @category Server\n * @example\n * ```typescript\n * // In your server endpoint (Next.js example):\n * import { handleRelayerOperation } from '@opendatalabs/vana-sdk/node';\n *\n * export async function POST(request: NextRequest) {\n * try {\n * const body = await request.json();\n * const vana = getServerVanaInstance(); // Your server SDK instance\n *\n * const result = await handleRelayerOperation(vana, body);\n *\n * return NextResponse.json(result);\n * } catch (error) {\n * return NextResponse.json(\n * { error: error.message },\n * { status: 500 }\n * );\n * }\n * }\n * ```\n */\nexport async function handleRelayerOperation(\n sdk: VanaInstance, // The public signature is generic\n request: UnifiedRelayerRequest,\n options?: TransactionOptions,\n): Promise<UnifiedRelayerResponse> {\n // Type assertion required: VanaInstance public interface doesn't expose operationStore\n // to maintain API simplicity, but server-side handler needs access for stateful mode.\n // The factory overloads guarantee this is safe for relayer-configured instances.\n // TODO(TYPES): Consider exposing operationStore through a server-specific interface\n\n const store = (sdk as any).operationStore as IOperationStore | undefined;\n\n // --- STATEFUL (ROBUST) MODE ---\n // This block executes ONLY if the developer provided an IOperationStore.\n if (store) {\n if (request.type === \"status_check\") {\n const state = await store.get(request.operationId);\n if (!state) return { type: \"error\", error: \"Operation not found\" };\n\n // If already confirmed or failed, return immediately\n if (state.status === \"confirmed\")\n return {\n type: \"confirmed\",\n hash: state.transactionHash,\n receipt: state.finalReceipt,\n };\n if (state.status === \"failed\")\n return { type: \"error\", error: state.error ?? \"Operation failed\" };\n\n // For pending operations, check the blockchain for transaction status\n if (state.status === \"pending\") {\n try {\n // Get a public client to check transaction status\n // The SDK stores it as a direct property\n const publicClient = (sdk as any).publicClient;\n\n if (publicClient) {\n // Check if transaction has been mined\n let receipt;\n try {\n receipt = await publicClient.getTransactionReceipt({\n hash: state.transactionHash,\n });\n } catch (receiptError: any) {\n // Transaction not found is expected - it may not be mined yet\n if (receiptError?.name !== \"TransactionReceiptNotFoundError\") {\n // Unexpected error - log but don't fail\n console.warn(\n `⚠️ [Relayer] Unexpected error checking receipt:`,\n receiptError?.message ?? receiptError,\n );\n }\n // Continue returning pending status\n receipt = null;\n }\n\n if (receipt) {\n // Update the operation state based on transaction status\n const updatedState: OperationState = {\n ...state,\n status: receipt.status === \"success\" ? \"confirmed\" : \"failed\",\n finalReceipt: receipt as TransactionReceipt,\n ...(receipt.status !== \"success\" && {\n error: \"Transaction reverted on chain\",\n }),\n };\n\n // Persist the updated state\n await store.set(request.operationId, updatedState);\n\n // Return the appropriate response\n if (receipt.status === \"success\") {\n return {\n type: \"confirmed\",\n hash: state.transactionHash,\n receipt: receipt as TransactionReceipt,\n };\n } else {\n return {\n type: \"error\",\n error: \"Transaction reverted on chain\",\n };\n }\n }\n } else {\n console.warn(\n \"⚠️ [Relayer] No public client available for status checking\",\n );\n }\n } catch (error) {\n console.error(\n `❌ [Relayer] Unexpected error in status check:`,\n error,\n );\n // Don't fail the operation, just continue returning pending\n }\n }\n\n return { type: \"pending\", operationId: request.operationId };\n }\n\n const operationId = uuidv4();\n try {\n const txResult = await routeAndExecuteRequest(sdk, request, options);\n // We only store state for operations that result in a transaction.\n if (\"hash\" in txResult) {\n await store.set(operationId, {\n status: \"pending\",\n transactionHash: txResult.hash,\n originalRequest: request,\n nonce: options?.nonce,\n retryCount: 0,\n lastAttemptedGas: {\n maxFeePerGas: options?.maxFeePerGas?.toString(),\n maxPriorityFeePerGas: options?.maxPriorityFeePerGas?.toString(),\n },\n submittedAt: Date.now(),\n });\n return { type: \"pending\", operationId };\n } else {\n // This handles non-transactional direct operations like `storeGrantFile`\n return { type: \"direct\", result: txResult };\n }\n } catch (e) {\n const error =\n e instanceof Error\n ? e\n : new Error(\"Unknown error during operation submission\");\n // We don't create a persistent error state for an initial submission failure.\n return { type: \"error\", error: error.message };\n }\n }\n\n // --- STATELESS (SIMPLE) MODE ---\n // This block executes if no IOperationStore was provided. Fire-and-forget.\n else {\n if (request.type === \"status_check\") {\n return {\n type: \"error\",\n error: \"Stateless relayer does not support operation status checks.\",\n };\n }\n\n try {\n const txResult = await routeAndExecuteRequest(sdk, request, options);\n\n // For stateless relayers, we can only handle transactional results.\n if (\"hash\" in txResult) {\n return { type: \"submitted\", hash: txResult.hash };\n } else {\n // Non-transactional direct operations can return their result directly.\n return { type: \"direct\", result: txResult };\n }\n } catch (e) {\n const error =\n e instanceof Error\n ? e\n : new Error(\"Unknown error during operation submission\");\n return { type: \"error\", error: error.message };\n }\n }\n}\n\n/**\n * Helper function to route and execute requests.\n * This simply delegates to the appropriate handler based on request type.\n */\nasync function routeAndExecuteRequest(\n sdk: VanaInstance,\n request: UnifiedRelayerRequest,\n options?: TransactionOptions,\n): Promise<\n | TransactionResult<Contract, Fn<Contract>>\n | { url: string }\n | { fileId: number; transactionHash: Hash }\n> {\n if (request.type === \"signed\") {\n const { typedData, signature, expectedUserAddress } = request;\n\n // Step 1: Verify the signature (security check)\n let recoveredAddress: `0x${string}`;\n try {\n recoveredAddress = await recoverTypedDataAddress({\n domain: {\n ...typedData.domain,\n chainId: typedData.domain.chainId\n ? BigInt(typedData.domain.chainId)\n : undefined,\n },\n types: typedData.types,\n primaryType: typedData.primaryType,\n message: typedData.message as unknown as Record<string, unknown>,\n signature,\n });\n } catch (error) {\n // Handle signature verification errors\n throw new SignatureError(\n `Signature verification failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n\n // Optional security check: Verify the signer matches expected address\n if (expectedUserAddress) {\n const normalizedExpected = getAddress(expectedUserAddress);\n const normalizedSigner = getAddress(recoveredAddress);\n\n if (normalizedSigner !== normalizedExpected) {\n throw new SignatureError(\n `Security verification failed: Recovered signer address (${normalizedSigner}) does not match expected user address (${normalizedExpected})`,\n );\n }\n }\n\n // Step 2: Route to appropriate SDK method based on primaryType\n return await routeSignedOperation(sdk, typedData, signature, options);\n } else if (request.type === \"direct\") {\n return await handleDirectOperation(sdk, request, options);\n }\n throw new Error(\"Invalid request type for execution\");\n}\n\n/**\n * Route signed operations to the appropriate SDK method with type safety.\n *\n * Returns a TransactionResult for one of the valid contracts and their functions.\n * Using Contract and Fn<Contract> ensures we're working with known contract types.\n */\nasync function routeSignedOperation(\n sdk: VanaInstance,\n typedData: GenericTypedData,\n signature: Hash,\n options?: TransactionOptions,\n): Promise<TransactionResult<Contract, Fn<Contract>>> {\n // Validate primaryType before casting\n const validPrimaryTypes: readonly TypedDataPrimaryType[] = [\n \"Permission\",\n \"RevokePermission\",\n \"TrustServer\",\n \"AddServer\",\n \"UntrustServer\",\n \"ServerFilesAndPermission\",\n ] as const;\n\n if (\n !validPrimaryTypes.includes(typedData.primaryType as TypedDataPrimaryType)\n ) {\n throw new Error(\n `Unsupported operation type: ${typedData.primaryType}. ` +\n `Supported types: ${validPrimaryTypes.join(\", \")}`,\n );\n }\n\n const primaryType = typedData.primaryType as TypedDataPrimaryType;\n\n // Type-safe routing based on primaryType\n switch (primaryType) {\n case \"Permission\":\n // TypeScript knows this is a Permission operation\n return sdk.permissions.submitSignedGrant(\n {\n ...typedData,\n primaryType: \"Permission\",\n } as PermissionGrantTypedData,\n signature,\n options,\n );\n\n case \"RevokePermission\":\n return sdk.permissions.submitSignedRevoke(\n {\n ...typedData,\n primaryType: \"RevokePermission\",\n } as RevokePermissionTypedData,\n signature,\n options,\n );\n\n case \"TrustServer\":\n // Note: TrustServer operation is deprecated but still supported for backwards compatibility\n // New implementations should use AddServer (AddAndTrustServer) instead\n return sdk.permissions.submitSignedTrustServer(\n {\n ...typedData,\n primaryType: \"TrustServer\",\n } as TrustServerTypedData,\n signature,\n options,\n );\n\n case \"AddServer\":\n return sdk.permissions.submitSignedAddAndTrustServer(\n {\n ...typedData,\n primaryType: \"AddServer\",\n } as AddAndTrustServerTypedData,\n signature,\n options,\n );\n\n case \"UntrustServer\":\n return sdk.permissions.submitSignedUntrustServer(\n {\n ...typedData,\n primaryType: \"UntrustServer\",\n } as GenericTypedData,\n signature,\n options,\n );\n\n case \"ServerFilesAndPermission\":\n return sdk.permissions.submitSignedAddServerFilesAndPermissions(\n {\n ...typedData,\n primaryType: \"ServerFilesAndPermission\",\n } as ServerFilesAndPermissionTypedData,\n signature,\n options,\n );\n\n // TODO: RegisterGrantee with signature is not supported until\n // DataPortabilityGrantees contract adds registerGranteeWithSignature function\n // case \"RegisterGrantee\":\n // return sdk.permissions.submitSignedRegisterGrantee(...);\n\n default:\n // This should never be reached due to validation above, but TypeScript requires it\n throw new Error(\n `Unsupported operation type: ${typedData.primaryType}. ` +\n `Supported types: Permission, RevokePermission, TrustServer, AddServer, UntrustServer, ServerFilesAndPermission`,\n );\n }\n}\n\n/**\n * Handle direct (non-signed) operations\n */\nasync function handleDirectOperation(\n sdk: VanaInstance,\n request: DirectRelayerRequest,\n options?: TransactionOptions,\n): Promise<\n | TransactionResult<Contract, Fn<Contract>>\n | { url: string }\n | { fileId: number; transactionHash: Hash }\n> {\n switch (request.operation) {\n case \"submitFileAddition\": {\n const { url, userAddress } = request.params;\n\n // Use SDK to add file with no permissions\n const result = await sdk.data.addFileWithPermissions(\n url,\n userAddress,\n [], // No permissions\n options,\n );\n\n // Return the TransactionResult directly\n return result;\n }\n\n case \"submitFileAdditionWithPermissions\": {\n const { url, userAddress, permissions } = request.params;\n\n // Use SDK to add file with permissions\n const result = await sdk.data.addFileWithPermissions(\n url,\n userAddress,\n permissions,\n options,\n );\n\n // Return the TransactionResult directly\n return result;\n }\n\n case \"submitFileAdditionComplete\": {\n const { url, userAddress, permissions, schemaId, ownerAddress } =\n request.params;\n\n // Permissions are already encrypted, use the appropriate method\n // No mapping needed - permissions already have { account, key } format\n const txResult = await sdk.data.addFileWithEncryptedPermissionsAndSchema(\n url,\n ownerAddress ?? userAddress,\n permissions, // Already in correct format with encrypted 'key' field\n schemaId,\n options,\n );\n\n // File uploads need synchronous response with fileId\n // Use the SDK's built-in event parsing - it knows how to extract events from TransactionResult\n // The SDK has waitForTransactionEvents as a public method\n const eventResult = await (sdk as any).waitForTransactionEvents(txResult);\n const fileAddedEvent = eventResult.expectedEvents?.FileAdded;\n\n if (!fileAddedEvent || !fileAddedEvent.fileId) {\n console.error(\"Event result:\", eventResult);\n throw new Error(\"FileAdded event not found in transaction\");\n }\n\n const fileId = Number(fileAddedEvent.fileId);\n\n // Return as a direct result that the SDK expects\n return {\n fileId,\n transactionHash: txResult.hash,\n };\n }\n\n case \"storeGrantFile\": {\n const grantFile = request.params;\n\n // Access the data controller's context which has storage\n const dataController = sdk.data as any;\n const context = dataController.context;\n\n if (!context?.storageManager) {\n throw new Error(\n \"Storage configuration is required for storing grant files\",\n );\n }\n\n // Convert grant file to blob for storage\n const blob = new Blob([JSON.stringify(grantFile)], {\n type: \"application/json\",\n });\n\n // Upload directly to storage (IPFS) without blockchain transaction\n const uploadResult = await context.storageManager.upload(\n blob,\n `grant-${Date.now()}.json`,\n );\n\n return { url: uploadResult.url };\n }\n\n default: {\n // TypeScript exhaustiveness check - ensures all cases are handled at compile time\n const exhaustiveCheck: never = request;\n // Return exhaustiveCheck to satisfy TypeScript while throwing an error\n // This should never be reached if all cases are handled\n return exhaustiveCheck;\n }\n }\n}\n"],"mappings":"AAAA,SAAS,MAAM,cAAc;AAwB7B,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB,kBAA6B;AAmC/D,eAAsB,uBACpB,KACA,SACA,SACiC;AAMjC,QAAM,QAAS,IAAY;AAI3B,MAAI,OAAO;AACT,QAAI,QAAQ,SAAS,gBAAgB;AACnC,YAAM,QAAQ,MAAM,MAAM,IAAI,QAAQ,WAAW;AACjD,UAAI,CAAC,MAAO,QAAO,EAAE,MAAM,SAAS,OAAO,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,MACF;AAGA,aAAO;AAAA,IACT;AAAA,IAEA,KAAK,8BAA8B;AACjC,YAAM,EAAE,KAAK,aAAa,aAAa,UAAU,aAAa,IAC5D,QAAQ;AAIV,YAAM,WAAW,MAAM,IAAI,KAAK;AAAA,QAC9B;AAAA,QACA,gBAAgB;AAAA,QAChB;AAAA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAKA,YAAM,cAAc,MAAO,IAAY,yBAAyB,QAAQ;AACxE,YAAM,iBAAiB,YAAY,gBAAgB;AAEnD,UAAI,CAAC,kBAAkB,CAAC,eAAe,QAAQ;AAC7C,gBAAQ,MAAM,iBAAiB,WAAW;AAC1C,cAAM,IAAI,MAAM,0CAA0C;AAAA,MAC5D;AAEA,YAAM,SAAS,OAAO,eAAe,MAAM;AAG3C,aAAO;AAAA,QACL;AAAA,QACA,iBAAiB,SAAS;AAAA,MAC5B;AAAA,IACF;AAAA,IAEA,KAAK,kBAAkB;AACrB,YAAM,YAAY,QAAQ;AAG1B,YAAM,iBAAiB,IAAI;AAC3B,YAAM,UAAU,eAAe;AAE/B,UAAI,CAAC,SAAS,gBAAgB;AAC5B,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAGA,YAAM,OAAO,IAAI,KAAK,CAAC,KAAK,UAAU,SAAS,CAAC,GAAG;AAAA,QACjD,MAAM;AAAA,MACR,CAAC;AAGD,YAAM,eAAe,MAAM,QAAQ,eAAe;AAAA,QAChD;AAAA,QACA,SAAS,KAAK,IAAI,CAAC;AAAA,MACrB;AAEA,aAAO,EAAE,KAAK,aAAa,IAAI;AAAA,IACjC;AAAA,IAEA,SAAS;AAEP,YAAM,kBAAyB;AAG/B,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/server/relayerHandler.ts"],"sourcesContent":["import type { VanaInstance } from \"../index.node\";\nimport type {\n UnifiedRelayerRequest,\n UnifiedRelayerResponse,\n SignedRelayerRequest,\n DirectRelayerRequest,\n} from \"../types/relayer\";\nimport type {\n GenericTypedData,\n PermissionGrantTypedData,\n RevokePermissionTypedData,\n TrustServerTypedData,\n AddAndTrustServerTypedData,\n ServerFilesAndPermissionTypedData,\n TypedDataPrimaryType,\n} from \"../types/permissions\";\nimport { SignatureError } from \"../errors\";\nimport { recoverTypedDataAddress, getAddress, type Hash } from \"viem\";\n\n/**\n * Universal handler for all relayer operations.\n *\n * This function processes both EIP-712 signed operations and direct operations,\n * automatically routing to the appropriate SDK methods.\n *\n * @param sdk - Initialized Vana SDK instance\n * @param request - The unified relayer request\n * @returns Promise resolving to operation-specific response\n *\n * @category Server\n * @example\n * ```typescript\n * // In your server endpoint (Next.js example):\n * import { handleRelayerOperation } from '@opendatalabs/vana-sdk/node';\n *\n * export async function POST(request: NextRequest) {\n * try {\n * const body = await request.json();\n * const vana = getServerVanaInstance(); // Your server SDK instance\n *\n * const result = await handleRelayerOperation(vana, body);\n *\n * return NextResponse.json(result);\n * } catch (error) {\n * return NextResponse.json(\n * { error: error.message },\n * { status: 500 }\n * );\n * }\n * }\n * ```\n */\nexport async function handleRelayerOperation(\n sdk: VanaInstance,\n request: UnifiedRelayerRequest,\n): Promise<UnifiedRelayerResponse> {\n // Handle signed operations (EIP-712)\n if (request.type === \"signed\") {\n return handleSignedOperation(sdk, request);\n }\n\n // Handle direct operations (non-signed)\n return handleDirectOperation(sdk, request);\n}\n\n/**\n * Handle EIP-712 signed operations with full type safety\n */\nasync function handleSignedOperation(\n sdk: VanaInstance,\n request: SignedRelayerRequest,\n): Promise<UnifiedRelayerResponse> {\n const { typedData, signature, expectedUserAddress } = request;\n\n // Step 1: Verify the signature (security check)\n let recoveredAddress: `0x${string}`;\n try {\n recoveredAddress = await recoverTypedDataAddress({\n domain: {\n ...typedData.domain,\n chainId: typedData.domain.chainId\n ? BigInt(typedData.domain.chainId)\n : undefined,\n },\n types: typedData.types,\n primaryType: typedData.primaryType,\n message: typedData.message as unknown as Record<string, unknown>,\n signature,\n });\n } catch (error) {\n // Handle signature verification errors\n throw new SignatureError(\n `Signature verification failed: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n\n // Optional security check: Verify the signer matches expected address\n if (expectedUserAddress) {\n const normalizedExpected = getAddress(expectedUserAddress);\n const normalizedSigner = getAddress(recoveredAddress);\n\n if (normalizedSigner !== normalizedExpected) {\n throw new SignatureError(\n `Security verification failed: Recovered signer address (${normalizedSigner}) does not match expected user address (${normalizedExpected})`,\n );\n }\n }\n\n // Step 2: Route to appropriate SDK method based on primaryType\n // Using proper type narrowing instead of unsafe casts\n const result = await routeSignedOperation(sdk, typedData, signature);\n\n // Return the transaction hash with type\n return {\n type: \"signed\",\n hash: result.hash,\n };\n}\n\n/**\n * Route signed operations to the appropriate SDK method with type safety\n */\nasync function routeSignedOperation(\n sdk: VanaInstance,\n typedData: GenericTypedData,\n signature: Hash,\n) {\n const primaryType = typedData.primaryType as TypedDataPrimaryType;\n\n // Type-safe routing based on primaryType\n switch (primaryType) {\n case \"Permission\":\n // TypeScript knows this is a Permission operation\n return sdk.permissions.submitSignedGrant(\n {\n ...typedData,\n primaryType: \"Permission\",\n } as PermissionGrantTypedData,\n signature,\n );\n\n case \"RevokePermission\":\n return sdk.permissions.submitSignedRevoke(\n {\n ...typedData,\n primaryType: \"RevokePermission\",\n } as RevokePermissionTypedData,\n signature,\n );\n\n case \"TrustServer\":\n return sdk.permissions.submitSignedTrustServer(\n {\n ...typedData,\n primaryType: \"TrustServer\",\n } as TrustServerTypedData,\n signature,\n );\n\n case \"AddServer\":\n return sdk.permissions.submitSignedAddAndTrustServer(\n {\n ...typedData,\n primaryType: \"AddServer\",\n } as AddAndTrustServerTypedData,\n signature,\n );\n\n case \"UntrustServer\":\n return sdk.permissions.submitSignedUntrustServer(\n {\n ...typedData,\n primaryType: \"UntrustServer\",\n } as GenericTypedData,\n signature,\n );\n\n case \"ServerFilesAndPermission\":\n return sdk.permissions.submitSignedAddServerFilesAndPermissions(\n {\n ...typedData,\n primaryType: \"ServerFilesAndPermission\",\n } as ServerFilesAndPermissionTypedData,\n signature,\n );\n\n // TODO: RegisterGrantee with signature is not supported until\n // DataPortabilityGrantees contract adds registerGranteeWithSignature function\n // case \"RegisterGrantee\":\n // return sdk.permissions.submitSignedRegisterGrantee(...);\n\n default:\n throw new Error(`Unsupported operation type: ${typedData.primaryType}`);\n }\n}\n\n/**\n * Handle direct (non-signed) operations\n */\nasync function handleDirectOperation(\n sdk: VanaInstance,\n request: DirectRelayerRequest,\n): Promise<UnifiedRelayerResponse> {\n switch (request.operation) {\n case \"submitFileAddition\": {\n const { url, userAddress } = request.params;\n\n // Use SDK to add file with no permissions\n const result = await sdk.data.addFileWithPermissions(\n url,\n userAddress,\n [], // No permissions\n );\n\n // Wait for transaction events to get fileId\n const eventData = await sdk.waitForTransactionEvents(result);\n const fileId = eventData.expectedEvents?.FileAdded?.fileId;\n\n if (!fileId) {\n throw new Error(\"Failed to get fileId from transaction events\");\n }\n\n return {\n type: \"direct\",\n result: {\n fileId: Number(fileId),\n transactionHash: result.hash,\n },\n };\n }\n\n case \"submitFileAdditionWithPermissions\": {\n const { url, userAddress, permissions } = request.params;\n\n // Use SDK to add file with permissions\n const result = await sdk.data.addFileWithPermissions(\n url,\n userAddress,\n permissions,\n );\n\n // Wait for transaction events to get fileId\n const eventData = await sdk.waitForTransactionEvents(result);\n const fileId = eventData.expectedEvents?.FileAdded?.fileId;\n\n if (!fileId) {\n throw new Error(\"Failed to get fileId from transaction events\");\n }\n\n return {\n type: \"direct\",\n result: {\n fileId: Number(fileId),\n transactionHash: result.hash,\n },\n };\n }\n\n case \"submitFileAdditionComplete\": {\n const { url, userAddress, permissions, schemaId, ownerAddress } =\n request.params;\n\n // Permissions are already encrypted, use the appropriate method\n // No mapping needed - permissions already have { account, key } format\n const result = await sdk.data.addFileWithEncryptedPermissionsAndSchema(\n url,\n ownerAddress ?? userAddress,\n permissions, // Already in correct format with encrypted 'key' field\n schemaId,\n );\n\n // Wait for transaction events to get fileId\n const eventData = await sdk.waitForTransactionEvents(result);\n const fileId = eventData.expectedEvents?.FileAdded?.fileId;\n\n if (!fileId) {\n throw new Error(\"Failed to get fileId from transaction events\");\n }\n\n return {\n type: \"direct\",\n result: {\n fileId: Number(fileId),\n transactionHash: result.hash,\n },\n };\n }\n\n case \"storeGrantFile\": {\n const grantFile = request.params;\n\n // Store grant file using SDK's data controller\n // Convert grant file to blob for storage\n const blob = new Blob([JSON.stringify(grantFile)], {\n type: \"application/json\",\n });\n\n // Upload using the data controller\n const result = await sdk.data.upload({\n content: blob,\n filename: `grant-${Date.now()}.json`,\n });\n\n return {\n type: \"direct\",\n result: { url: result.url },\n };\n }\n\n default: {\n // TypeScript exhaustiveness check - ensures all cases are handled at compile time\n const exhaustiveCheck: never = request;\n // Return exhaustiveCheck to satisfy TypeScript while throwing an error\n // This should never be reached if all cases are handled\n return exhaustiveCheck;\n }\n }\n}\n"],"mappings":"AAgBA,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB,kBAA6B;AAmC/D,eAAsB,uBACpB,KACA,SACiC;AAEjC,MAAI,QAAQ,SAAS,UAAU;AAC7B,WAAO,sBAAsB,KAAK,OAAO;AAAA,EAC3C;AAGA,SAAO,sBAAsB,KAAK,OAAO;AAC3C;AAKA,eAAe,sBACb,KACA,SACiC;AACjC,QAAM,EAAE,WAAW,WAAW,oBAAoB,IAAI;AAGtD,MAAI;AACJ,MAAI;AACF,uBAAmB,MAAM,wBAAwB;AAAA,MAC/C,QAAQ;AAAA,QACN,GAAG,UAAU;AAAA,QACb,SAAS,UAAU,OAAO,UACtB,OAAO,UAAU,OAAO,OAAO,IAC/B;AAAA,MACN;AAAA,MACA,OAAO,UAAU;AAAA,MACjB,aAAa,UAAU;AAAA,MACvB,SAAS,UAAU;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH,SAAS,OAAO;AAEd,UAAM,IAAI;AAAA,MACR,kCAAkC,iBAAiB,QAAQ,MAAM,UAAU,eAAe;AAAA,IAC5F;AA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S,UAAU,gBAAgB,WAAW;AAEpD,UAAI,CAAC,QAAQ;AACX,cAAM,IAAI,MAAM,8CAA8C;AAAA,MAChE;AAEA,aAAO;AAAA,QACL,MAAM;AAAA,QACN,QAAQ;AAAA,UACN,QAAQ,OAAO,MAAM;AAAA,UACrB,iBAAiB,OAAO;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAAA,IAEA,KAAK,kBAAkB;AACrB,YAAM,YAAY,QAAQ;AAI1B,YAAM,OAAO,IAAI,KAAK,CAAC,KAAK,UAAU,SAAS,CAAC,GAAG;AAAA,QACjD,MAAM;AAAA,MACR,CAAC;AAGD,YAAM,SAAS,MAAM,IAAI,KAAK,OAAO;AAAA,QACnC,SAAS;AAAA,QACT,UAAU,SAAS,KAAK,IAAI,CAAC;AAAA,MAC/B,CAAC;AAED,aAAO;AAAA,QACL,MAAM;AAAA,QACN,QAAQ,EAAE,KAAK,OAAO,IAAI;AAAA,MAC5B;AAAA,IACF;AAAA,IAEA,SAAS;AAEP,YAAM,kBAAyB;AAG/B,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/config.ts"],"sourcesContent":["import type { WalletClient, PublicClient, Account, Address, Chain } from \"viem\";\nimport type { VanaChainId, VanaChain } from \"./chains\";\nimport type {\n StorageProvider,\n StorageUploadResult,\n StorageListOptions,\n} from \"./storage\";\n\nimport type { RelayerConfig } from \"./relayer\";\nimport type { IOperationStore } from \"./operations\";\n\n/**\n * Marker interface to indicate that a Vana instance has storage configured.\n * Used for compile-time type safety to ensure storage-dependent methods\n * are only called on properly configured instances.\n *\n * @category Configuration\n */\nexport interface StorageRequiredMarker {\n readonly __storageRequired: true;\n}\n\n/**\n * Configures storage providers for SDK file operations.\n *\n * @remarks\n * Supports multiple backends with automatic fallback.\n * IPFS for decentralization, Pinata for reliability,\n * Google Drive for development, custom for flexibility.\n *\n * **Provider Selection:**\n * - IPFS: Decentralized, permanent storage ideal for production\n * - Pinata: Managed IPFS with guaranteed availability\n * - Google Drive: Centralized, suitable for development/testing\n * - Custom providers: Implement StorageProvider interface\n *\n * @category Configuration\n * @example\n * ```typescript\n * const storage: StorageConfig = {\n * providers: {\n * ipfs: new IPFSStorage({ gateway: 'https://gateway.pinata.cloud' }),\n * pinata: new PinataStorage({ apiKey: 'key', secretKey: 'secret' })\n * },\n * defaultProvider: 'ipfs'\n * };\n * ```\n */\nexport interface StorageConfig {\n /**\n * Map of provider name to storage provider instance.\n * Common provider names: \"ipfs\", \"pinata\", \"googledrive\", \"s3\".\n * Custom names allowed for custom provider implementations.\n */\n providers: Record<string, StorageProvider>;\n /**\n * Default provider name to use when none specified.\n * Must match a key in the providers map. Falls back to first provider if not specified.\n */\n defaultProvider?: string;\n}\n\n/**\n * Download relayer callbacks for proxying CORS-restricted downloads.\n *\n * Provides a callback to proxy download requests through your application server\n * when direct browser access fails due to CORS restrictions (e.g., Google Drive).\n *\n * IMPORTANT SECURITY REQUIREMENTS for your proxy endpoint:\n * 1. MUST block requests to private/internal IPs (SSRF protection)\n * 2. SHOULD NOT restrict domains (files can be hosted anywhere)\n *\n * @category Configuration\n * @example Client-side implementation:\n * ```typescript\n * const downloadRelayer: DownloadRelayerCallbacks = {\n * async proxyDownload(url) {\n * const response = await fetch('/api/proxy', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ url })\n * });\n * return response.blob();\n * }\n * };\n * ```\n *\n * @example Server-side proxy endpoint (Next.js):\n * ```typescript\n * // /api/proxy/route.ts\n * import { promises as dns } from 'dns';\n * import { isIPv4 } from 'net';\n *\n * async function handleProxy(url: string) {\n * const { hostname } = new URL(url);\n *\n * // Resolve hostname to IP (handle localhost specially)\n * const ip = hostname === 'localhost' ? '127.0.0.1' :\n * isIPv4(hostname) ? hostname :\n * await dns.lookup(hostname).then(r => r.address);\n *\n * // SSRF Protection: Block private/internal IPs\n * if (isIPv4(ip)) {\n * const [a, b] = ip.split('.').map(Number);\n * if (a === 10 || a === 127 || a === 0 ||\n * (a === 172 && b >= 16 && b <= 31) ||\n * (a === 192 && b === 168) ||\n * (a === 169 && b === 254) ||\n * a >= 224) { // Also block multicast/reserved\n * return new Response('Private/internal addresses not allowed', { status: 403 });\n * }\n * }\n *\n * // Proxy the request\n * const response = await fetch(url, { redirect: 'manual' });\n *\n * // Handle redirects (with recursion limit)\n * if (response.status >= 301 && response.status <= 308) {\n * const location = response.headers.get('location');\n * if (location) return handleProxy(new URL(location, url).href);\n * }\n *\n * const data = await response.arrayBuffer();\n * return new Response(data, {\n * headers: {\n * 'Content-Type': response.headers.get('content-type') || 'application/octet-stream',\n * 'Access-Control-Allow-Origin': '*'\n * }\n * });\n * }\n * ```\n */\nexport interface DownloadRelayerCallbacks {\n /**\n * Proxy a download request through your application server\n *\n * @param url - The URL to download from\n * @returns Promise resolving to the downloaded content as a Blob\n */\n proxyDownload: (url: string) => Promise<Blob>;\n}\n\n/**\n * Storage callback functions for flexible storage operations.\n *\n * Instead of hardcoding storage behavior (HTTP endpoints, etc.), users can provide\n * custom callback functions to handle storage operations in any way they choose.\n * This pattern matches the relayer callbacks approach, providing maximum flexibility.\n *\n * @category Configuration\n * @example\n * ```typescript\n * const storageCallbacks: StorageCallbacks = {\n * async upload(blob, filename, metadata) {\n * // Custom implementation - could be HTTP, S3, local filesystem, etc.\n * const formData = new FormData();\n * formData.append('file', blob, filename);\n * const response = await fetch('/api/storage/upload', {\n * method: 'POST',\n * body: formData\n * });\n * const data = await response.json();\n * return {\n * url: data.url,\n * size: blob.size,\n * contentType: blob.type,\n * metadata: data.metadata\n * };\n * },\n *\n * async download(identifier) {\n * const response = await fetch(`/api/storage/download/${identifier}`);\n * return response.blob();\n * }\n * };\n * ```\n */\nexport interface StorageCallbacks {\n /**\n * Upload a blob to storage\n *\n * @param blob - The data to upload\n * @param filename - Optional filename hint\n * @param metadata - Optional metadata for the upload\n * @returns Upload result with identifier and metadata\n */\n upload: (\n blob: Blob,\n filename?: string,\n metadata?: Record<string, unknown>,\n ) => Promise<StorageUploadResult>;\n\n /**\n * Download data from storage\n *\n * @param identifier - The storage identifier (could be URL, hash, path, or any unique ID)\n * @param options - Optional download options\n * @returns The downloaded data as a Blob\n */\n download: (\n identifier: string,\n options?: StorageDownloadOptions,\n ) => Promise<Blob>;\n\n /**\n * List stored items (optional)\n *\n * @param prefix - Optional prefix to filter results\n * @param options - Optional listing options\n * @returns Array of storage items with metadata\n */\n list?: (\n prefix?: string,\n options?: StorageListOptions,\n ) => Promise<StorageListResult>;\n\n /**\n * Delete a stored item (optional)\n *\n * @param identifier - The storage identifier to delete\n * @returns Promise that resolves to true if deletion succeeded\n */\n delete?: (identifier: string) => Promise<boolean>;\n\n /**\n * Extract identifier from a URL or return as-is (optional)\n * Used for backward compatibility with URL-based systems\n *\n * @param url - The URL to extract from\n * @returns The extracted identifier\n */\n extractIdentifier?: (url: string) => string;\n}\n\n/**\n * Options for storage download operations\n *\n * @category Configuration\n */\nexport interface StorageDownloadOptions {\n /** Optional HTTP headers */\n headers?: Record<string, string>;\n /** Optional abort signal for cancellation */\n signal?: AbortSignal;\n /** Optional byte range for partial downloads */\n range?: { start?: number; end?: number };\n}\n\n/**\n * Result from storage list operations\n *\n * @category Configuration\n */\nexport interface StorageListResult {\n /** Array of storage items */\n items: Array<{\n /** Item identifier */\n identifier: string;\n /** Item size in bytes */\n size?: number;\n /** Last modified timestamp */\n lastModified?: Date;\n /** Item metadata */\n metadata?: Record<string, unknown>;\n }>;\n /** Continuation token for pagination */\n continuationToken?: string;\n /** Whether more results are available */\n hasMore?: boolean;\n}\n\n/**\n * Base configuration interface without storage requirements\n *\n * @category Configuration\n */\nexport interface BaseConfig {\n /**\n * Optional relayer configuration for handling gasless transactions.\n * Can be a URL string for convenience, or a callback for full control.\n *\n * @example\n * ```typescript\n * // Simple URL (SDK handles transport)\n * relayer: '/api/relay'\n *\n * // Full control with callback\n * relayer: async (request) => {\n * const response = await fetch('/api/relay', {\n * method: 'POST',\n * body: JSON.stringify(request)\n * });\n * return response.json();\n * }\n * ```\n */\n relayer?: RelayerConfig;\n\n /**\n * Optional download relayer for proxying CORS-restricted downloads.\n * Provides a proxy mechanism for files stored on servers with CORS restrictions.\n */\n downloadRelayer?: DownloadRelayerCallbacks;\n\n /**\n * Optional storage providers configuration for file upload/download.\n * Required for: upload(), grant() without pre-stored URLs, schema operations.\n * See StorageConfig for provider selection guidance.\n */\n storage?: StorageConfig;\n\n /**\n * Optional subgraph URL for querying user files and permissions.\n * If not provided, defaults to the built-in subgraph URL for the current chain.\n * Can be overridden per method call if needed.\n * Obtain chain-specific URLs from Vana documentation or deployment info.\n */\n subgraphUrl?: string;\n /**\n * Optional default IPFS gateways to use for fetching files.\n * These gateways will be used by default in fetchFromIPFS unless overridden per-call.\n * If not provided, the SDK will use public gateways.\n * Order matters: first successful gateway is used.\n *\n * @example ['https://gateway.pinata.cloud', 'https://ipfs.io']\n */\n ipfsGateways?: string[];\n /**\n * Default personal server base URL for server operations.\n * Required for ServerController methods like getIdentity(), createOperation(), etc.\n *\n * @example 'https://my-personal-server.example.com'\n */\n defaultPersonalServerUrl?: string;\n\n /**\n * Optional operation store for tracking async relayed transactions.\n * When provided with a relayer, enables resilient transaction management\n * with polling support for pending operations.\n *\n * @example\n * ```typescript\n * const vana = createVana({\n * walletClient,\n * relayer: '/api/relay',\n * operationStore: myOperationStore\n * });\n * ```\n */\n operationStore?: IOperationStore;\n}\n\n/**\n * Base configuration interface that requires storage for storage-dependent operations\n *\n * @category Configuration\n */\nexport interface BaseConfigWithStorage {\n /**\n * Optional relayer configuration for handling gasless transactions.\n * Can be a URL string for convenience, or a callback for full control.\n *\n * @example\n * ```typescript\n * // Simple URL (SDK handles transport)\n * relayer: '/api/relay'\n *\n * // Full control with callback\n * relayer: async (request) => {\n * const response = await fetch('/api/relay', {\n * method: 'POST',\n * body: JSON.stringify(request)\n * });\n * return response.json();\n * }\n * ```\n */\n relayer?: RelayerConfig;\n\n /**\n * Optional download relayer for proxying CORS-restricted downloads.\n * Provides a proxy mechanism for files stored on servers with CORS restrictions.\n */\n downloadRelayer?: DownloadRelayerCallbacks;\n\n /** Required storage providers configuration for file upload/download */\n storage: StorageConfig;\n /**\n * Optional subgraph URL for querying user files and permissions.\n * If not provided, defaults to the built-in subgraph URL for the current chain.\n * Can be overridden per method call if needed.\n */\n subgraphUrl?: string;\n /**\n * Optional default IPFS gateways to use for fetching files.\n * These gateways will be used by default in fetchFromIPFS unless overridden per-call.\n * If not provided, the SDK will use public gateways.\n *\n * @example ['https://gateway.pinata.cloud', 'https://ipfs.io']\n */\n ipfsGateways?: string[];\n /**\n * Default personal server base URL for server operations.\n * Required for ServerController methods like getIdentity(), createOperation(), etc.\n *\n * @example 'https://my-personal-server.example.com'\n */\n defaultPersonalServerUrl?: string;\n\n /**\n * Optional operation store for tracking async relayed transactions.\n * When provided with a relayer, enables resilient transaction management\n * with polling support for pending operations.\n */\n operationStore?: IOperationStore;\n}\n\n/**\n * Configuration with wallet client\n *\n * @category Configuration\n */\nexport interface WalletConfig extends BaseConfig {\n /** The viem WalletClient instance used for signing transactions */\n walletClient: WalletClient & {\n chain: VanaChain;\n };\n}\n\n/**\n * Configuration with wallet client that requires storage\n *\n * @category Configuration\n */\nexport interface WalletConfigWithStorage extends BaseConfigWithStorage {\n /** The viem WalletClient instance used for signing transactions */\n walletClient: WalletClient & {\n chain: VanaChain;\n };\n}\n\n/**\n * Configuration with chain and account details\n *\n * @category Configuration\n */\nexport interface ChainConfig extends BaseConfig {\n /**\n * The chain ID for Vana network.\n * Supported: 14800 (Vana Mainnet), 14801 (Moksha Testnet), 31337 (Local Development).\n * Use chain constants from '@vana/sdk' for type safety.\n */\n chainId: VanaChainId;\n /**\n * RPC URL for the chain (optional, will use default for the chain if not provided).\n * Default URLs: mainnet (https://rpc.vana.org), testnet (https://rpc.moksha.vana.org).\n * Override for custom nodes or local development.\n */\n rpcUrl?: string;\n /**\n * Optional account for signing transactions.\n * Can be: privateKeyToAccount(), mnemonicToAccount(), or custom Account implementation.\n * Required for write operations; read-only operations work without account.\n */\n account?: Account;\n}\n\n/**\n * Configuration with chain and account details that requires storage\n *\n * @category Configuration\n */\nexport interface ChainConfigWithStorage extends BaseConfigWithStorage {\n /** The chain ID for Vana network */\n chainId: VanaChainId;\n /** RPC URL for the chain (optional, will use default for the chain if not provided) */\n rpcUrl?: string;\n /** Optional account for signing transactions */\n account?: Account;\n}\n\n/**\n * Configuration with wallet client and optional public client\n *\n * @category Configuration\n */\nexport interface VanaConfigWithWallet extends BaseConfig {\n /** The viem WalletClient instance used for signing transactions */\n walletClient: WalletClient;\n /** Optional PublicClient for read operations (derived from wallet if not provided) */\n publicClient?: PublicClient;\n}\n\n/**\n * Configuration for read-only operations with public client and address\n *\n * @category Configuration\n */\nexport interface VanaConfigReadOnly extends BaseConfig {\n /** The viem PublicClient instance for read operations */\n publicClient: PublicClient;\n /** The user's address for read operations */\n address: Address;\n}\n\n/**\n * Configuration for minimal read-only operations with just an address\n *\n * @category Configuration\n */\nexport interface VanaConfigAddressOnly extends BaseConfig {\n /** The user's address for read operations */\n address: Address;\n /** Optional chain configuration (will use default if not provided) */\n chain?: Chain;\n}\n\n/**\n * Configuration with wallet client and optional public client that requires storage\n *\n * @category Configuration\n */\nexport interface VanaConfigWithWalletWithStorage extends BaseConfigWithStorage {\n /** The viem WalletClient instance used for signing transactions */\n walletClient: WalletClient;\n /** Optional PublicClient for read operations (derived from wallet if not provided) */\n publicClient?: PublicClient;\n}\n\n/**\n * Configuration for read-only operations with public client and address that requires storage\n *\n * @category Configuration\n */\nexport interface VanaConfigReadOnlyWithStorage extends BaseConfigWithStorage {\n /** The viem PublicClient instance for read operations */\n publicClient: PublicClient;\n /** The user's address for read operations */\n address: Address;\n}\n\n/**\n * Configuration for minimal read-only operations with just an address that requires storage\n *\n * @category Configuration\n */\nexport interface VanaConfigAddressOnlyWithStorage\n extends BaseConfigWithStorage {\n /** The user's address for read operations */\n address: Address;\n /** Optional chain configuration (will use default if not provided) */\n chain?: Chain;\n}\n\n/**\n * Main configuration interface for initializing the Vana SDK.\n *\n * The SDK supports three initialization modes:\n * 1. Full mode with wallet client for signing transactions\n * 2. Read-only mode with public client and address for read operations\n * 3. Minimal mode with just an address and optional chain\n *\n * @category Configuration\n * @example\n * ```typescript\n * // Mode 1: Full configuration with wallet client\n * const configWithWallet: VanaConfig = {\n * walletClient: createWalletClient({\n * account: privateKeyToAccount('0x...'),\n * chain: moksha,\n * transport: http()\n * }),\n * publicClient: createPublicClient({\n * chain: moksha,\n * transport: http()\n * })\n * };\n *\n * // Mode 2: Read-only with public client and address\n * const configReadOnly: VanaConfig = {\n * publicClient: createPublicClient({\n * chain: moksha,\n * transport: http()\n * }),\n * address: '0x1234...'\n * };\n *\n * // Mode 3: Minimal with just address\n * const configMinimal: VanaConfig = {\n * address: '0x1234...',\n * chain: moksha // optional\n * };\n * ```\n */\nexport type VanaConfig =\n | VanaConfigWithWallet\n | VanaConfigReadOnly\n | VanaConfigAddressOnly\n | WalletConfig\n | ChainConfig;\n\n/**\n * Configuration interface for Vana SDK that requires storage providers.\n *\n * Use this type when you need to ensure storage is configured for operations\n * like file uploads, permission grants without pre-stored URLs, or schema creation.\n * Supports all three initialization modes with required storage.\n *\n * @category Configuration\n * @example\n * ```typescript\n * // Full configuration with wallet client and storage\n * const configWithWallet: VanaConfigWithStorage = {\n * walletClient: createWalletClient({\n * account: privateKeyToAccount('0x...'),\n * chain: moksha,\n * transport: http()\n * }),\n * storage: {\n * providers: {\n * ipfs: new IPFSStorage({ gateway: 'https://gateway.pinata.cloud' })\n * },\n * defaultProvider: 'ipfs'\n * }\n * };\n *\n * // Read-only configuration with storage\n * const configReadOnly: VanaConfigWithStorage = {\n * publicClient: createPublicClient({\n * chain: moksha,\n * transport: http()\n * }),\n * address: '0x1234...',\n * storage: {\n * providers: {\n * ipfs: new IPFSStorage({ gateway: 'https://gateway.pinata.cloud' })\n * },\n * defaultProvider: 'ipfs'\n * }\n * };\n * ```\n */\nexport type VanaConfigWithStorage =\n | VanaConfigWithWalletWithStorage\n | VanaConfigReadOnlyWithStorage\n | VanaConfigAddressOnlyWithStorage\n | WalletConfigWithStorage\n | ChainConfigWithStorage;\n\n/**\n * Runtime configuration information\n *\n * @category Configuration\n */\nexport interface RuntimeConfig {\n /** Current chain ID */\n chainId: VanaChainId;\n /** Current chain name */\n chainName: string;\n /** Available storage providers */\n storageProviders: string[];\n /** Default storage provider */\n defaultStorageProvider?: string;\n /** Current relayer configuration */\n relayerConfig?: RelayerConfig;\n}\n\n/**\n * Validates whether a configuration object has a wallet client (any wallet-based config).\n *\n * @param config - The configuration object to check\n * @returns True if the config contains a walletClient\n * @example\n * ```typescript\n * if (isWalletConfig(config)) {\n * console.log('Using wallet client:', config.walletClient.account?.address);\n * } else {\n * console.log('Read-only or chain config');\n * }\n * ```\n */\nexport function isWalletConfig(\n config: VanaConfig,\n): config is VanaConfigWithWallet | WalletConfig {\n return \"walletClient\" in config;\n}\n\n/**\n * Validates whether a configuration object is a read-only config with public client.\n *\n * @param config - The configuration object to check\n * @returns True if the config has publicClient and address but no walletClient\n * @example\n * ```typescript\n * if (isReadOnlyConfig(config)) {\n * console.log('Read-only mode with address:', config.address);\n * }\n * ```\n */\nexport function isReadOnlyConfig(\n config: VanaConfig,\n): config is VanaConfigReadOnly {\n return (\n \"publicClient\" in config &&\n \"address\" in config &&\n !(\"walletClient\" in config)\n );\n}\n\n/**\n * Validates whether a configuration object is an address-only config.\n *\n * @param config - The configuration object to check\n * @returns True if the config has only address (and optionally chain) but no clients\n * @example\n * ```typescript\n * if (isAddressOnlyConfig(config)) {\n * console.log('Address-only mode:', config.address);\n * }\n * ```\n */\nexport function isAddressOnlyConfig(\n config: VanaConfig,\n): config is VanaConfigAddressOnly {\n return (\n \"address\" in config &&\n !(\"publicClient\" in config) &&\n !(\"walletClient\" in config) &&\n !(\"chainId\" in config)\n );\n}\n\n/**\n * Validates whether a configuration object is a ChainConfig.\n *\n * @param config - The configuration object to check\n * @returns True if the config is a ChainConfig (contains chainId but not walletClient)\n * @example\n * ```typescript\n * if (isChainConfig(config)) {\n * console.log('Chain ID:', config.chainId);\n * console.log('RPC URL:', config.rpcUrl);\n * } else {\n * console.log('Using pre-configured wallet client');\n * }\n * ```\n */\nexport function isChainConfig(config: VanaConfig): config is ChainConfig {\n return \"chainId\" in config && !(\"walletClient\" in config);\n}\n\n/**\n * Validates whether a configuration has required storage providers.\n *\n * @param config - The configuration object to check\n * @returns True if the config has storage providers configured\n * @example\n * ```typescript\n * if (hasStorageConfig(config)) {\n * // Safe to use storage-dependent operations\n * await vana.data.uploadFile(file);\n * } else {\n * console.log('Storage not configured - some operations may fail');\n * }\n * ```\n */\nexport function hasStorageConfig(\n config: VanaConfig,\n): config is VanaConfigWithStorage {\n return (\n config.storage?.providers !== undefined &&\n Object.keys(config.storage.providers).length > 0\n );\n}\n\n/**\n * Configuration validation options\n *\n * @category Configuration\n */\nexport interface ConfigValidationOptions {\n /** Whether to validate storage providers */\n validateStorage?: boolean;\n /** Whether to validate relayer URL */\n validateRelayer?: boolean;\n /** Whether to validate chain configuration */\n validateChain?: boolean;\n}\n\n/**\n * Configuration validation result\n *\n * @category Configuration\n */\nexport interface ConfigValidationResult {\n /** Whether the configuration is valid */\n valid: boolean;\n /** List of validation errors */\n errors: string[];\n /** List of validation warnings */\n warnings: string[];\n}\n\n/**\n * Marker interface to enforce the presence of operationStore at compile time.\n * This interface is used to ensure that certain operations requiring a relayer\n * can only be called when the SDK has been properly configured with an operation store.\n *\n * @category Configuration\n */\nexport interface RelayerRequiredMarker {\n readonly __relayerConfigured: true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyqBO,SAAS,eACd,QAC+C;AAC/C,SAAO,kBAAkB;AAC3B;AAcO,SAAS,iBACd,QAC8B;AAC9B,SACE,kBAAkB,UAClB,aAAa,UACb,EAAE,kBAAkB;AAExB;AAcO,SAAS,oBACd,QACiC;AACjC,SACE,aAAa,UACb,EAAE,kBAAkB,WACpB,EAAE,kBAAkB,WACpB,EAAE,aAAa;AAEnB;AAiBO,SAAS,cAAc,QAA2C;AACvE,SAAO,aAAa,UAAU,EAAE,kBAAkB;AACpD;AAiBO,SAAS,iBACd,QACiC;AACjC,SACE,OAAO,SAAS,cAAc,UAC9B,OAAO,KAAK,OAAO,QAAQ,SAAS,EAAE,SAAS;AAEnD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/types/config.ts"],"sourcesContent":["import type { WalletClient, PublicClient, Account, Address, Chain } from \"viem\";\nimport type { VanaChainId, VanaChain } from \"./chains\";\nimport type {\n StorageProvider,\n StorageUploadResult,\n StorageListOptions,\n} from \"./storage\";\n\nimport type { RelayerConfig } from \"./relayer\";\n\n/**\n * Marker interface to indicate that a Vana instance has storage configured.\n * Used for compile-time type safety to ensure storage-dependent methods\n * are only called on properly configured instances.\n *\n * @category Configuration\n */\nexport interface StorageRequiredMarker {\n readonly __storageRequired: true;\n}\n\n/**\n * Configures storage providers for SDK file operations.\n *\n * @remarks\n * Supports multiple backends with automatic fallback.\n * IPFS for decentralization, Pinata for reliability,\n * Google Drive for development, custom for flexibility.\n *\n * **Provider Selection:**\n * - IPFS: Decentralized, permanent storage ideal for production\n * - Pinata: Managed IPFS with guaranteed availability\n * - Google Drive: Centralized, suitable for development/testing\n * - Custom providers: Implement StorageProvider interface\n *\n * @category Configuration\n * @example\n * ```typescript\n * const storage: StorageConfig = {\n * providers: {\n * ipfs: new IPFSStorage({ gateway: 'https://gateway.pinata.cloud' }),\n * pinata: new PinataStorage({ apiKey: 'key', secretKey: 'secret' })\n * },\n * defaultProvider: 'ipfs'\n * };\n * ```\n */\nexport interface StorageConfig {\n /**\n * Map of provider name to storage provider instance.\n * Common provider names: \"ipfs\", \"pinata\", \"googledrive\", \"s3\".\n * Custom names allowed for custom provider implementations.\n */\n providers: Record<string, StorageProvider>;\n /**\n * Default provider name to use when none specified.\n * Must match a key in the providers map. Falls back to first provider if not specified.\n */\n defaultProvider?: string;\n}\n\n/**\n * Download relayer callbacks for proxying CORS-restricted downloads.\n *\n * Provides a callback to proxy download requests through your application server\n * when direct browser access fails due to CORS restrictions (e.g., Google Drive).\n *\n * IMPORTANT SECURITY REQUIREMENTS for your proxy endpoint:\n * 1. MUST block requests to private/internal IPs (SSRF protection)\n * 2. SHOULD NOT restrict domains (files can be hosted anywhere)\n *\n * @category Configuration\n * @example Client-side implementation:\n * ```typescript\n * const downloadRelayer: DownloadRelayerCallbacks = {\n * async proxyDownload(url) {\n * const response = await fetch('/api/proxy', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ url })\n * });\n * return response.blob();\n * }\n * };\n * ```\n *\n * @example Server-side proxy endpoint (Next.js):\n * ```typescript\n * // /api/proxy/route.ts\n * import { promises as dns } from 'dns';\n * import { isIPv4 } from 'net';\n *\n * async function handleProxy(url: string) {\n * const { hostname } = new URL(url);\n *\n * // Resolve hostname to IP (handle localhost specially)\n * const ip = hostname === 'localhost' ? '127.0.0.1' :\n * isIPv4(hostname) ? hostname :\n * await dns.lookup(hostname).then(r => r.address);\n *\n * // SSRF Protection: Block private/internal IPs\n * if (isIPv4(ip)) {\n * const [a, b] = ip.split('.').map(Number);\n * if (a === 10 || a === 127 || a === 0 ||\n * (a === 172 && b >= 16 && b <= 31) ||\n * (a === 192 && b === 168) ||\n * (a === 169 && b === 254) ||\n * a >= 224) { // Also block multicast/reserved\n * return new Response('Private/internal addresses not allowed', { status: 403 });\n * }\n * }\n *\n * // Proxy the request\n * const response = await fetch(url, { redirect: 'manual' });\n *\n * // Handle redirects (with recursion limit)\n * if (response.status >= 301 && response.status <= 308) {\n * const location = response.headers.get('location');\n * if (location) return handleProxy(new URL(location, url).href);\n * }\n *\n * const data = await response.arrayBuffer();\n * return new Response(data, {\n * headers: {\n * 'Content-Type': response.headers.get('content-type') || 'application/octet-stream',\n * 'Access-Control-Allow-Origin': '*'\n * }\n * });\n * }\n * ```\n */\nexport interface DownloadRelayerCallbacks {\n /**\n * Proxy a download request through your application server\n *\n * @param url - The URL to download from\n * @returns Promise resolving to the downloaded content as a Blob\n */\n proxyDownload: (url: string) => Promise<Blob>;\n}\n\n/**\n * Storage callback functions for flexible storage operations.\n *\n * Instead of hardcoding storage behavior (HTTP endpoints, etc.), users can provide\n * custom callback functions to handle storage operations in any way they choose.\n * This pattern matches the relayer callbacks approach, providing maximum flexibility.\n *\n * @category Configuration\n * @example\n * ```typescript\n * const storageCallbacks: StorageCallbacks = {\n * async upload(blob, filename, metadata) {\n * // Custom implementation - could be HTTP, S3, local filesystem, etc.\n * const formData = new FormData();\n * formData.append('file', blob, filename);\n * const response = await fetch('/api/storage/upload', {\n * method: 'POST',\n * body: formData\n * });\n * const data = await response.json();\n * return {\n * url: data.url,\n * size: blob.size,\n * contentType: blob.type,\n * metadata: data.metadata\n * };\n * },\n *\n * async download(identifier) {\n * const response = await fetch(`/api/storage/download/${identifier}`);\n * return response.blob();\n * }\n * };\n * ```\n */\nexport interface StorageCallbacks {\n /**\n * Upload a blob to storage\n *\n * @param blob - The data to upload\n * @param filename - Optional filename hint\n * @param metadata - Optional metadata for the upload\n * @returns Upload result with identifier and metadata\n */\n upload: (\n blob: Blob,\n filename?: string,\n metadata?: Record<string, unknown>,\n ) => Promise<StorageUploadResult>;\n\n /**\n * Download data from storage\n *\n * @param identifier - The storage identifier (could be URL, hash, path, or any unique ID)\n * @param options - Optional download options\n * @returns The downloaded data as a Blob\n */\n download: (\n identifier: string,\n options?: StorageDownloadOptions,\n ) => Promise<Blob>;\n\n /**\n * List stored items (optional)\n *\n * @param prefix - Optional prefix to filter results\n * @param options - Optional listing options\n * @returns Array of storage items with metadata\n */\n list?: (\n prefix?: string,\n options?: StorageListOptions,\n ) => Promise<StorageListResult>;\n\n /**\n * Delete a stored item (optional)\n *\n * @param identifier - The storage identifier to delete\n * @returns Promise that resolves to true if deletion succeeded\n */\n delete?: (identifier: string) => Promise<boolean>;\n\n /**\n * Extract identifier from a URL or return as-is (optional)\n * Used for backward compatibility with URL-based systems\n *\n * @param url - The URL to extract from\n * @returns The extracted identifier\n */\n extractIdentifier?: (url: string) => string;\n}\n\n/**\n * Options for storage download operations\n *\n * @category Configuration\n */\nexport interface StorageDownloadOptions {\n /** Optional HTTP headers */\n headers?: Record<string, string>;\n /** Optional abort signal for cancellation */\n signal?: AbortSignal;\n /** Optional byte range for partial downloads */\n range?: { start?: number; end?: number };\n}\n\n/**\n * Result from storage list operations\n *\n * @category Configuration\n */\nexport interface StorageListResult {\n /** Array of storage items */\n items: Array<{\n /** Item identifier */\n identifier: string;\n /** Item size in bytes */\n size?: number;\n /** Last modified timestamp */\n lastModified?: Date;\n /** Item metadata */\n metadata?: Record<string, unknown>;\n }>;\n /** Continuation token for pagination */\n continuationToken?: string;\n /** Whether more results are available */\n hasMore?: boolean;\n}\n\n/**\n * Base configuration interface without storage requirements\n *\n * @category Configuration\n */\nexport interface BaseConfig {\n /**\n * Optional relayer configuration for handling gasless transactions.\n * Can be a URL string for convenience, or a callback for full control.\n *\n * @example\n * ```typescript\n * // Simple URL (SDK handles transport)\n * relayer: '/api/relay'\n *\n * // Full control with callback\n * relayer: async (request) => {\n * const response = await fetch('/api/relay', {\n * method: 'POST',\n * body: JSON.stringify(request)\n * });\n * return response.json();\n * }\n * ```\n */\n relayer?: RelayerConfig;\n\n /**\n * Optional download relayer for proxying CORS-restricted downloads.\n * Provides a proxy mechanism for files stored on servers with CORS restrictions.\n */\n downloadRelayer?: DownloadRelayerCallbacks;\n\n /**\n * Optional storage providers configuration for file upload/download.\n * Required for: upload(), grant() without pre-stored URLs, schema operations.\n * See StorageConfig for provider selection guidance.\n */\n storage?: StorageConfig;\n /**\n * Optional subgraph URL for querying user files and permissions.\n * If not provided, defaults to the built-in subgraph URL for the current chain.\n * Can be overridden per method call if needed.\n * Obtain chain-specific URLs from Vana documentation or deployment info.\n */\n subgraphUrl?: string;\n /**\n * Optional default IPFS gateways to use for fetching files.\n * These gateways will be used by default in fetchFromIPFS unless overridden per-call.\n * If not provided, the SDK will use public gateways.\n * Order matters: first successful gateway is used.\n *\n * @example ['https://gateway.pinata.cloud', 'https://ipfs.io']\n */\n ipfsGateways?: string[];\n /**\n * Default personal server base URL for server operations.\n * Required for ServerController methods like getIdentity(), createOperation(), etc.\n *\n * @example 'https://my-personal-server.example.com'\n */\n defaultPersonalServerUrl?: string;\n}\n\n/**\n * Base configuration interface that requires storage for storage-dependent operations\n *\n * @category Configuration\n */\nexport interface BaseConfigWithStorage {\n /**\n * Optional relayer configuration for handling gasless transactions.\n * Can be a URL string for convenience, or a callback for full control.\n *\n * @example\n * ```typescript\n * // Simple URL (SDK handles transport)\n * relayer: '/api/relay'\n *\n * // Full control with callback\n * relayer: async (request) => {\n * const response = await fetch('/api/relay', {\n * method: 'POST',\n * body: JSON.stringify(request)\n * });\n * return response.json();\n * }\n * ```\n */\n relayer?: RelayerConfig;\n\n /**\n * Optional download relayer for proxying CORS-restricted downloads.\n * Provides a proxy mechanism for files stored on servers with CORS restrictions.\n */\n downloadRelayer?: DownloadRelayerCallbacks;\n\n /** Required storage providers configuration for file upload/download */\n storage: StorageConfig;\n /**\n * Optional subgraph URL for querying user files and permissions.\n * If not provided, defaults to the built-in subgraph URL for the current chain.\n * Can be overridden per method call if needed.\n */\n subgraphUrl?: string;\n /**\n * Optional default IPFS gateways to use for fetching files.\n * These gateways will be used by default in fetchFromIPFS unless overridden per-call.\n * If not provided, the SDK will use public gateways.\n *\n * @example ['https://gateway.pinata.cloud', 'https://ipfs.io']\n */\n ipfsGateways?: string[];\n /**\n * Default personal server base URL for server operations.\n * Required for ServerController methods like getIdentity(), createOperation(), etc.\n *\n * @example 'https://my-personal-server.example.com'\n */\n defaultPersonalServerUrl?: string;\n}\n\n/**\n * Configuration with wallet client\n *\n * @category Configuration\n */\nexport interface WalletConfig extends BaseConfig {\n /** The viem WalletClient instance used for signing transactions */\n walletClient: WalletClient & {\n chain: VanaChain;\n };\n}\n\n/**\n * Configuration with wallet client that requires storage\n *\n * @category Configuration\n */\nexport interface WalletConfigWithStorage extends BaseConfigWithStorage {\n /** The viem WalletClient instance used for signing transactions */\n walletClient: WalletClient & {\n chain: VanaChain;\n };\n}\n\n/**\n * Configuration with chain and account details\n *\n * @category Configuration\n */\nexport interface ChainConfig extends BaseConfig {\n /**\n * The chain ID for Vana network.\n * Supported: 14800 (Vana Mainnet), 14801 (Moksha Testnet), 31337 (Local Development).\n * Use chain constants from '@vana/sdk' for type safety.\n */\n chainId: VanaChainId;\n /**\n * RPC URL for the chain (optional, will use default for the chain if not provided).\n * Default URLs: mainnet (https://rpc.vana.org), testnet (https://rpc.moksha.vana.org).\n * Override for custom nodes or local development.\n */\n rpcUrl?: string;\n /**\n * Optional account for signing transactions.\n * Can be: privateKeyToAccount(), mnemonicToAccount(), or custom Account implementation.\n * Required for write operations; read-only operations work without account.\n */\n account?: Account;\n}\n\n/**\n * Configuration with chain and account details that requires storage\n *\n * @category Configuration\n */\nexport interface ChainConfigWithStorage extends BaseConfigWithStorage {\n /** The chain ID for Vana network */\n chainId: VanaChainId;\n /** RPC URL for the chain (optional, will use default for the chain if not provided) */\n rpcUrl?: string;\n /** Optional account for signing transactions */\n account?: Account;\n}\n\n/**\n * Configuration with wallet client and optional public client\n *\n * @category Configuration\n */\nexport interface VanaConfigWithWallet extends BaseConfig {\n /** The viem WalletClient instance used for signing transactions */\n walletClient: WalletClient;\n /** Optional PublicClient for read operations (derived from wallet if not provided) */\n publicClient?: PublicClient;\n}\n\n/**\n * Configuration for read-only operations with public client and address\n *\n * @category Configuration\n */\nexport interface VanaConfigReadOnly extends BaseConfig {\n /** The viem PublicClient instance for read operations */\n publicClient: PublicClient;\n /** The user's address for read operations */\n address: Address;\n}\n\n/**\n * Configuration for minimal read-only operations with just an address\n *\n * @category Configuration\n */\nexport interface VanaConfigAddressOnly extends BaseConfig {\n /** The user's address for read operations */\n address: Address;\n /** Optional chain configuration (will use default if not provided) */\n chain?: Chain;\n}\n\n/**\n * Configuration with wallet client and optional public client that requires storage\n *\n * @category Configuration\n */\nexport interface VanaConfigWithWalletWithStorage extends BaseConfigWithStorage {\n /** The viem WalletClient instance used for signing transactions */\n walletClient: WalletClient;\n /** Optional PublicClient for read operations (derived from wallet if not provided) */\n publicClient?: PublicClient;\n}\n\n/**\n * Configuration for read-only operations with public client and address that requires storage\n *\n * @category Configuration\n */\nexport interface VanaConfigReadOnlyWithStorage extends BaseConfigWithStorage {\n /** The viem PublicClient instance for read operations */\n publicClient: PublicClient;\n /** The user's address for read operations */\n address: Address;\n}\n\n/**\n * Configuration for minimal read-only operations with just an address that requires storage\n *\n * @category Configuration\n */\nexport interface VanaConfigAddressOnlyWithStorage\n extends BaseConfigWithStorage {\n /** The user's address for read operations */\n address: Address;\n /** Optional chain configuration (will use default if not provided) */\n chain?: Chain;\n}\n\n/**\n * Main configuration interface for initializing the Vana SDK.\n *\n * The SDK supports three initialization modes:\n * 1. Full mode with wallet client for signing transactions\n * 2. Read-only mode with public client and address for read operations\n * 3. Minimal mode with just an address and optional chain\n *\n * @category Configuration\n * @example\n * ```typescript\n * // Mode 1: Full configuration with wallet client\n * const configWithWallet: VanaConfig = {\n * walletClient: createWalletClient({\n * account: privateKeyToAccount('0x...'),\n * chain: moksha,\n * transport: http()\n * }),\n * publicClient: createPublicClient({\n * chain: moksha,\n * transport: http()\n * })\n * };\n *\n * // Mode 2: Read-only with public client and address\n * const configReadOnly: VanaConfig = {\n * publicClient: createPublicClient({\n * chain: moksha,\n * transport: http()\n * }),\n * address: '0x1234...'\n * };\n *\n * // Mode 3: Minimal with just address\n * const configMinimal: VanaConfig = {\n * address: '0x1234...',\n * chain: moksha // optional\n * };\n * ```\n */\nexport type VanaConfig =\n | VanaConfigWithWallet\n | VanaConfigReadOnly\n | VanaConfigAddressOnly\n | WalletConfig\n | ChainConfig;\n\n/**\n * Configuration interface for Vana SDK that requires storage providers.\n *\n * Use this type when you need to ensure storage is configured for operations\n * like file uploads, permission grants without pre-stored URLs, or schema creation.\n * Supports all three initialization modes with required storage.\n *\n * @category Configuration\n * @example\n * ```typescript\n * // Full configuration with wallet client and storage\n * const configWithWallet: VanaConfigWithStorage = {\n * walletClient: createWalletClient({\n * account: privateKeyToAccount('0x...'),\n * chain: moksha,\n * transport: http()\n * }),\n * storage: {\n * providers: {\n * ipfs: new IPFSStorage({ gateway: 'https://gateway.pinata.cloud' })\n * },\n * defaultProvider: 'ipfs'\n * }\n * };\n *\n * // Read-only configuration with storage\n * const configReadOnly: VanaConfigWithStorage = {\n * publicClient: createPublicClient({\n * chain: moksha,\n * transport: http()\n * }),\n * address: '0x1234...',\n * storage: {\n * providers: {\n * ipfs: new IPFSStorage({ gateway: 'https://gateway.pinata.cloud' })\n * },\n * defaultProvider: 'ipfs'\n * }\n * };\n * ```\n */\nexport type VanaConfigWithStorage =\n | VanaConfigWithWalletWithStorage\n | VanaConfigReadOnlyWithStorage\n | VanaConfigAddressOnlyWithStorage\n | WalletConfigWithStorage\n | ChainConfigWithStorage;\n\n/**\n * Runtime configuration information\n *\n * @category Configuration\n */\nexport interface RuntimeConfig {\n /** Current chain ID */\n chainId: VanaChainId;\n /** Current chain name */\n chainName: string;\n /** Available storage providers */\n storageProviders: string[];\n /** Default storage provider */\n defaultStorageProvider?: string;\n /** Current relayer configuration */\n relayerConfig?: RelayerConfig;\n}\n\n/**\n * Validates whether a configuration object has a wallet client (any wallet-based config).\n *\n * @param config - The configuration object to check\n * @returns True if the config contains a walletClient\n * @example\n * ```typescript\n * if (isWalletConfig(config)) {\n * console.log('Using wallet client:', config.walletClient.account?.address);\n * } else {\n * console.log('Read-only or chain config');\n * }\n * ```\n */\nexport function isWalletConfig(\n config: VanaConfig,\n): config is VanaConfigWithWallet | WalletConfig {\n return \"walletClient\" in config;\n}\n\n/**\n * Validates whether a configuration object is a read-only config with public client.\n *\n * @param config - The configuration object to check\n * @returns True if the config has publicClient and address but no walletClient\n * @example\n * ```typescript\n * if (isReadOnlyConfig(config)) {\n * console.log('Read-only mode with address:', config.address);\n * }\n * ```\n */\nexport function isReadOnlyConfig(\n config: VanaConfig,\n): config is VanaConfigReadOnly {\n return (\n \"publicClient\" in config &&\n \"address\" in config &&\n !(\"walletClient\" in config)\n );\n}\n\n/**\n * Validates whether a configuration object is an address-only config.\n *\n * @param config - The configuration object to check\n * @returns True if the config has only address (and optionally chain) but no clients\n * @example\n * ```typescript\n * if (isAddressOnlyConfig(config)) {\n * console.log('Address-only mode:', config.address);\n * }\n * ```\n */\nexport function isAddressOnlyConfig(\n config: VanaConfig,\n): config is VanaConfigAddressOnly {\n return (\n \"address\" in config &&\n !(\"publicClient\" in config) &&\n !(\"walletClient\" in config) &&\n !(\"chainId\" in config)\n );\n}\n\n/**\n * Validates whether a configuration object is a ChainConfig.\n *\n * @param config - The configuration object to check\n * @returns True if the config is a ChainConfig (contains chainId but not walletClient)\n * @example\n * ```typescript\n * if (isChainConfig(config)) {\n * console.log('Chain ID:', config.chainId);\n * console.log('RPC URL:', config.rpcUrl);\n * } else {\n * console.log('Using pre-configured wallet client');\n * }\n * ```\n */\nexport function isChainConfig(config: VanaConfig): config is ChainConfig {\n return \"chainId\" in config && !(\"walletClient\" in config);\n}\n\n/**\n * Validates whether a configuration has required storage providers.\n *\n * @param config - The configuration object to check\n * @returns True if the config has storage providers configured\n * @example\n * ```typescript\n * if (hasStorageConfig(config)) {\n * // Safe to use storage-dependent operations\n * await vana.data.uploadFile(file);\n * } else {\n * console.log('Storage not configured - some operations may fail');\n * }\n * ```\n */\nexport function hasStorageConfig(\n config: VanaConfig,\n): config is VanaConfigWithStorage {\n return (\n config.storage?.providers !== undefined &&\n Object.keys(config.storage.providers).length > 0\n );\n}\n\n/**\n * Configuration validation options\n *\n * @category Configuration\n */\nexport interface ConfigValidationOptions {\n /** Whether to validate storage providers */\n validateStorage?: boolean;\n /** Whether to validate relayer URL */\n validateRelayer?: boolean;\n /** Whether to validate chain configuration */\n validateChain?: boolean;\n}\n\n/**\n * Configuration validation result\n *\n * @category Configuration\n */\nexport interface ConfigValidationResult {\n /** Whether the configuration is valid */\n valid: boolean;\n /** List of validation errors */\n errors: string[];\n /** List of validation warnings */\n warnings: string[];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgpBO,SAAS,eACd,QAC+C;AAC/C,SAAO,kBAAkB;AAC3B;AAcO,SAAS,iBACd,QAC8B;AAC9B,SACE,kBAAkB,UAClB,aAAa,UACb,EAAE,kBAAkB;AAExB;AAcO,SAAS,oBACd,QACiC;AACjC,SACE,aAAa,UACb,EAAE,kBAAkB,WACpB,EAAE,kBAAkB,WACpB,EAAE,aAAa;AAEnB;AAiBO,SAAS,cAAc,QAA2C;AACvE,SAAO,aAAa,UAAU,EAAE,kBAAkB;AACpD;AAiBO,SAAS,iBACd,QACiC;AACjC,SACE,OAAO,SAAS,cAAc,UAC9B,OAAO,KAAK,OAAO,QAAQ,SAAS,EAAE,SAAS;AAEnD;","names":[]}
|
package/dist/types/config.d.ts
CHANGED
|
@@ -2,7 +2,6 @@ import type { WalletClient, PublicClient, Account, Address, Chain } from "viem";
|
|
|
2
2
|
import type { VanaChainId, VanaChain } from "./chains";
|
|
3
3
|
import type { StorageProvider, StorageUploadResult, StorageListOptions } from "./storage";
|
|
4
4
|
import type { RelayerConfig } from "./relayer";
|
|
5
|
-
import type { IOperationStore } from "./operations";
|
|
6
5
|
/**
|
|
7
6
|
* Marker interface to indicate that a Vana instance has storage configured.
|
|
8
7
|
* Used for compile-time type safety to ensure storage-dependent methods
|
|
@@ -306,21 +305,6 @@ export interface BaseConfig {
|
|
|
306
305
|
* @example 'https://my-personal-server.example.com'
|
|
307
306
|
*/
|
|
308
307
|
defaultPersonalServerUrl?: string;
|
|
309
|
-
/**
|
|
310
|
-
* Optional operation store for tracking async relayed transactions.
|
|
311
|
-
* When provided with a relayer, enables resilient transaction management
|
|
312
|
-
* with polling support for pending operations.
|
|
313
|
-
*
|
|
314
|
-
* @example
|
|
315
|
-
* ```typescript
|
|
316
|
-
* const vana = createVana({
|
|
317
|
-
* walletClient,
|
|
318
|
-
* relayer: '/api/relay',
|
|
319
|
-
* operationStore: myOperationStore
|
|
320
|
-
* });
|
|
321
|
-
* ```
|
|
322
|
-
*/
|
|
323
|
-
operationStore?: IOperationStore;
|
|
324
308
|
}
|
|
325
309
|
/**
|
|
326
310
|
* Base configuration interface that requires storage for storage-dependent operations
|
|
@@ -376,12 +360,6 @@ export interface BaseConfigWithStorage {
|
|
|
376
360
|
* @example 'https://my-personal-server.example.com'
|
|
377
361
|
*/
|
|
378
362
|
defaultPersonalServerUrl?: string;
|
|
379
|
-
/**
|
|
380
|
-
* Optional operation store for tracking async relayed transactions.
|
|
381
|
-
* When provided with a relayer, enables resilient transaction management
|
|
382
|
-
* with polling support for pending operations.
|
|
383
|
-
*/
|
|
384
|
-
operationStore?: IOperationStore;
|
|
385
363
|
}
|
|
386
364
|
/**
|
|
387
365
|
* Configuration with wallet client
|
|
@@ -708,13 +686,3 @@ export interface ConfigValidationResult {
|
|
|
708
686
|
/** List of validation warnings */
|
|
709
687
|
warnings: string[];
|
|
710
688
|
}
|
|
711
|
-
/**
|
|
712
|
-
* Marker interface to enforce the presence of operationStore at compile time.
|
|
713
|
-
* This interface is used to ensure that certain operations requiring a relayer
|
|
714
|
-
* can only be called when the SDK has been properly configured with an operation store.
|
|
715
|
-
*
|
|
716
|
-
* @category Configuration
|
|
717
|
-
*/
|
|
718
|
-
export interface RelayerRequiredMarker {
|
|
719
|
-
readonly __relayerConfigured: true;
|
|
720
|
-
}
|