@opendatalabs/vana-sdk 3.0.1 → 3.2.0-canary.0911ffc

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.
Files changed (116) hide show
  1. package/README.md +2 -1
  2. package/dist/__tests__/interop-personal-server.test.d.ts +1 -0
  3. package/dist/account/personal-server-lite-owner-binding.cjs +81 -0
  4. package/dist/account/personal-server-lite-owner-binding.cjs.map +1 -0
  5. package/dist/account/personal-server-lite-owner-binding.d.ts +30 -0
  6. package/dist/account/personal-server-lite-owner-binding.js +59 -0
  7. package/dist/account/personal-server-lite-owner-binding.js.map +1 -0
  8. package/dist/account/personal-server-lite-owner-binding.test.d.ts +1 -0
  9. package/dist/account/personal-server-registration.cjs +263 -0
  10. package/dist/account/personal-server-registration.cjs.map +1 -0
  11. package/dist/account/personal-server-registration.d.ts +66 -0
  12. package/dist/account/personal-server-registration.js +240 -0
  13. package/dist/account/personal-server-registration.js.map +1 -0
  14. package/dist/account/personal-server-registration.test.d.ts +1 -0
  15. package/dist/auth/errors.js +1 -1
  16. package/dist/auth/oauth-client.cjs +250 -0
  17. package/dist/auth/oauth-client.cjs.map +1 -0
  18. package/dist/auth/oauth-client.d.ts +90 -0
  19. package/dist/auth/oauth-client.js +228 -0
  20. package/dist/auth/oauth-client.js.map +1 -0
  21. package/dist/auth/oauth-client.test.d.ts +1 -0
  22. package/dist/auth/web3-signed-builder.js +1 -1
  23. package/dist/auth/web3-signed.js +3 -3
  24. package/dist/browser.js +1 -1
  25. package/dist/chains/definitions.js +1 -1
  26. package/dist/chains/index.js +1 -1
  27. package/dist/chains.browser.js +1 -1
  28. package/dist/chains.js +1 -1
  29. package/dist/chains.node.js +1 -1
  30. package/dist/contracts/contractController.js +4 -4
  31. package/dist/core/client.js +1 -1
  32. package/dist/crypto/ecies/base.js +3 -3
  33. package/dist/crypto/ecies/browser.js +1 -1
  34. package/dist/crypto/ecies/index.js +1 -1
  35. package/dist/crypto/ecies/interface.js +1 -1
  36. package/dist/crypto/ecies/node.js +1 -1
  37. package/dist/crypto/services/WalletKeyEncryptionService.js +1 -1
  38. package/dist/generated/abi/index.js +26 -26
  39. package/dist/index.browser.d.ts +10 -3
  40. package/dist/index.browser.js +992 -73
  41. package/dist/index.browser.js.map +4 -4
  42. package/dist/index.node.cjs +1023 -74
  43. package/dist/index.node.cjs.map +4 -4
  44. package/dist/index.node.d.ts +10 -3
  45. package/dist/index.node.js +992 -73
  46. package/dist/index.node.js.map +4 -4
  47. package/dist/node.js +1 -1
  48. package/dist/platform/browser-only.js +1 -1
  49. package/dist/platform/browser-safe.js +1 -1
  50. package/dist/platform/browser.js +6 -6
  51. package/dist/platform/index.js +4 -4
  52. package/dist/platform/node.js +8 -8
  53. package/dist/platform/utils.js +2 -2
  54. package/dist/platform.browser.js +3 -3
  55. package/dist/platform.js +4 -4
  56. package/dist/platform.node.js +4 -4
  57. package/dist/protocol/eip712.cjs +58 -3
  58. package/dist/protocol/eip712.cjs.map +1 -1
  59. package/dist/protocol/eip712.d.ts +99 -7
  60. package/dist/protocol/eip712.js +52 -3
  61. package/dist/protocol/eip712.js.map +1 -1
  62. package/dist/protocol/escrow-deposit.cjs +89 -0
  63. package/dist/protocol/escrow-deposit.cjs.map +1 -0
  64. package/dist/protocol/escrow-deposit.d.ts +47 -0
  65. package/dist/protocol/escrow-deposit.js +60 -0
  66. package/dist/protocol/escrow-deposit.js.map +1 -0
  67. package/dist/protocol/escrow-deposit.test.d.ts +1 -0
  68. package/dist/protocol/escrow-flow.test.d.ts +21 -0
  69. package/dist/protocol/fee-registry.cjs +89 -0
  70. package/dist/protocol/fee-registry.cjs.map +1 -0
  71. package/dist/protocol/fee-registry.d.ts +105 -0
  72. package/dist/protocol/fee-registry.js +63 -0
  73. package/dist/protocol/fee-registry.js.map +1 -0
  74. package/dist/protocol/fee-registry.test.d.ts +1 -0
  75. package/dist/protocol/gateway.cjs +124 -3
  76. package/dist/protocol/gateway.cjs.map +1 -1
  77. package/dist/protocol/gateway.d.ts +196 -16
  78. package/dist/protocol/gateway.js +124 -3
  79. package/dist/protocol/gateway.js.map +1 -1
  80. package/dist/protocol/grants.cjs +24 -64
  81. package/dist/protocol/grants.cjs.map +1 -1
  82. package/dist/protocol/grants.d.ts +6 -13
  83. package/dist/protocol/grants.js +25 -64
  84. package/dist/protocol/grants.js.map +1 -1
  85. package/dist/protocol/personal-server-lite-owner-binding.cjs +93 -0
  86. package/dist/protocol/personal-server-lite-owner-binding.cjs.map +1 -0
  87. package/dist/protocol/personal-server-lite-owner-binding.d.ts +44 -0
  88. package/dist/protocol/personal-server-lite-owner-binding.js +65 -0
  89. package/dist/protocol/personal-server-lite-owner-binding.js.map +1 -0
  90. package/dist/protocol/personal-server-lite-owner-binding.test.d.ts +1 -0
  91. package/dist/protocol/personal-server-registration.cjs +122 -0
  92. package/dist/protocol/personal-server-registration.cjs.map +1 -0
  93. package/dist/protocol/personal-server-registration.d.ts +62 -0
  94. package/dist/protocol/personal-server-registration.js +97 -0
  95. package/dist/protocol/personal-server-registration.js.map +1 -0
  96. package/dist/protocol/personal-server-registration.test.d.ts +1 -0
  97. package/dist/storage/default.js +1 -1
  98. package/dist/storage/index.cjs.map +1 -1
  99. package/dist/storage/index.d.ts +1 -1
  100. package/dist/storage/index.js +10 -10
  101. package/dist/storage/index.js.map +1 -1
  102. package/dist/storage/manager.js +1 -1
  103. package/dist/storage/providers/callback-storage.js +1 -1
  104. package/dist/storage/providers/dropbox.js +1 -1
  105. package/dist/storage/providers/google-drive.js +1 -1
  106. package/dist/storage/providers/ipfs.js +2 -2
  107. package/dist/storage/providers/pinata.js +1 -1
  108. package/dist/storage/providers/r2.js +1 -1
  109. package/dist/storage/providers/vana-storage.cjs +1 -1
  110. package/dist/storage/providers/vana-storage.cjs.map +1 -1
  111. package/dist/storage/providers/vana-storage.d.ts +2 -2
  112. package/dist/storage/providers/vana-storage.js +3 -3
  113. package/dist/storage/providers/vana-storage.js.map +1 -1
  114. package/dist/types/index.js +2 -2
  115. package/dist/types.js +1 -1
  116. package/package.json +7 -3
@@ -1173,6 +1173,10 @@ var init_browser2 = __esm({
1173
1173
  // src/index.node.ts
1174
1174
  var index_node_exports = {};
1175
1175
  __export(index_node_exports, {
1176
+ ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT: () => ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT,
1177
+ ADD_DATA_TYPES: () => ADD_DATA_TYPES,
1178
+ AccountPersonalServerLiteOwnerBindingError: () => AccountPersonalServerLiteOwnerBindingError,
1179
+ AccountPersonalServerRegistrationError: () => AccountPersonalServerRegistrationError,
1176
1180
  BUILDER_REGISTRATION_TYPES: () => BUILDER_REGISTRATION_TYPES,
1177
1181
  BlockchainError: () => BlockchainError,
1178
1182
  BrowserPlatformAdapter: () => BrowserPlatformAdapter,
@@ -1183,8 +1187,11 @@ __export(index_node_exports, {
1183
1187
  DataFileEnvelopeSchema: () => DataFileEnvelopeSchema,
1184
1188
  DropboxStorage: () => DropboxStorage,
1185
1189
  ECIESError: () => ECIESError,
1190
+ ESCROW_DEPOSIT_ABI: () => ESCROW_DEPOSIT_ABI,
1186
1191
  ExpiredTokenError: () => ExpiredTokenError,
1192
+ FEE_REGISTRY_ABI: () => FEE_REGISTRY_ABI,
1187
1193
  FILE_REGISTRATION_TYPES: () => FILE_REGISTRATION_TYPES,
1194
+ GENERIC_PAYMENT_TYPES: () => GENERIC_PAYMENT_TYPES,
1188
1195
  GRANT_REGISTRATION_TYPES: () => GRANT_REGISTRATION_TYPES,
1189
1196
  GRANT_REVOCATION_TYPES: () => GRANT_REVOCATION_TYPES,
1190
1197
  GoogleDriveStorage: () => GoogleDriveStorage,
@@ -1195,10 +1202,17 @@ __export(index_node_exports, {
1195
1202
  IpfsStorage: () => IpfsStorage,
1196
1203
  MASTER_KEY_MESSAGE: () => MASTER_KEY_MESSAGE,
1197
1204
  MissingAuthError: () => MissingAuthError,
1205
+ NATIVE_VANA_ASSET: () => NATIVE_VANA_ASSET,
1198
1206
  NetworkError: () => NetworkError,
1199
1207
  NodeECIESProvider: () => NodeECIESUint8Provider,
1200
1208
  NodePlatformAdapter: () => NodePlatformAdapter,
1201
1209
  NonceError: () => NonceError,
1210
+ OAuthClient: () => OAuthClient,
1211
+ PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX: () => PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX,
1212
+ PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE: () => PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE,
1213
+ PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION: () => PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION,
1214
+ PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID: () => PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID,
1215
+ PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT: () => PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT,
1202
1216
  PKCE_CHALLENGE_PATTERN: () => PKCE_CHALLENGE_PATTERN,
1203
1217
  PKCE_VERIFIER_PATTERN: () => PKCE_VERIFIER_PATTERN,
1204
1218
  PSError: () => PSError,
@@ -1206,6 +1220,7 @@ __export(index_node_exports, {
1206
1220
  PersonalServerError: () => PersonalServerError,
1207
1221
  PinataStorage: () => PinataStorage,
1208
1222
  R2Storage: () => R2Storage,
1223
+ RECORD_DATA_ACCESS_TYPES: () => RECORD_DATA_ACCESS_TYPES,
1209
1224
  ReadOnlyError: () => ReadOnlyError,
1210
1225
  RelayerError: () => RelayerError,
1211
1226
  SERVER_REGISTRATION_TYPES: () => SERVER_REGISTRATION_TYPES,
@@ -1220,6 +1235,12 @@ __export(index_node_exports, {
1220
1235
  VanaError: () => VanaError,
1221
1236
  VanaStorage: () => VanaStorage,
1222
1237
  assertValidPkceVerifier: () => assertValidPkceVerifier,
1238
+ buildDepositNativeRequest: () => buildDepositNativeRequest,
1239
+ buildDepositTokenRequest: () => buildDepositTokenRequest,
1240
+ buildPersonalServerLiteOwnerBindingMessage: () => buildPersonalServerLiteOwnerBindingMessage,
1241
+ buildPersonalServerLiteOwnerBindingSignature: () => buildPersonalServerLiteOwnerBindingSignature,
1242
+ buildPersonalServerRegistrationSignature: () => buildPersonalServerRegistrationSignature,
1243
+ buildPersonalServerRegistrationTypedData: () => buildPersonalServerRegistrationTypedData,
1223
1244
  buildWeb3SignedHeader: () => buildWeb3SignedHeader,
1224
1245
  builderRegistrationDomain: () => builderRegistrationDomain,
1225
1246
  chains: () => chains,
@@ -1235,12 +1256,19 @@ __export(index_node_exports, {
1235
1256
  createPlatformAdapterFor: () => createPlatformAdapterFor,
1236
1257
  createPlatformAdapterSafe: () => createPlatformAdapterSafe,
1237
1258
  createVanaStorageProvider: () => createVanaStorageProvider,
1259
+ createViemPersonalServerLiteOwnerBindingSigner: () => createViemPersonalServerLiteOwnerBindingSigner,
1260
+ createViemPersonalServerRegistrationSigner: () => createViemPersonalServerRegistrationSigner,
1261
+ dataRegistryDomain: () => dataRegistryDomain,
1238
1262
  decryptWithPassword: () => decryptWithPassword,
1239
1263
  deriveMasterKey: () => deriveMasterKey,
1240
1264
  deriveScopeKey: () => deriveScopeKey,
1241
1265
  deserializeECIES: () => deserializeECIES,
1242
1266
  detectPlatform: () => detectPlatform,
1267
+ encodeDepositNativeData: () => encodeDepositNativeData,
1268
+ encodeDepositTokenData: () => encodeDepositTokenData,
1243
1269
  encryptWithPassword: () => encryptWithPassword,
1270
+ escrowContractAddress: () => escrowContractAddress,
1271
+ escrowPaymentDomain: () => escrowPaymentDomain,
1244
1272
  fileRegistrationDomain: () => fileRegistrationDomain,
1245
1273
  generatePkceVerifier: () => generatePkceVerifier,
1246
1274
  getAbi: () => getAbi,
@@ -1249,6 +1277,8 @@ __export(index_node_exports, {
1249
1277
  getContractAddress: () => getContractAddress,
1250
1278
  getContractController: () => getContractController,
1251
1279
  getContractInfo: () => getContractInfo,
1280
+ getFee: () => getFee,
1281
+ getOpFee: () => getOpFee,
1252
1282
  getPlatformCapabilities: () => getPlatformCapabilities,
1253
1283
  getServiceEndpoints: () => getServiceEndpoints,
1254
1284
  grantRegistrationDomain: () => grantRegistrationDomain,
@@ -1260,16 +1290,20 @@ __export(index_node_exports, {
1260
1290
  moksha: () => moksha,
1261
1291
  mokshaServices: () => mokshaServices,
1262
1292
  mokshaTestnet: () => mokshaTestnet2,
1263
- parseGrantRegistrationPayload: () => parseGrantRegistrationPayload,
1264
1293
  parsePSError: () => parsePSError,
1265
1294
  parseScope: () => parseScope,
1266
1295
  parseWeb3SignedHeader: () => parseWeb3SignedHeader,
1296
+ personalServerRegistrationDomain: () => personalServerRegistrationDomain,
1267
1297
  recoverServerOwner: () => recoverServerOwner,
1298
+ registerPersonalServerSignature: () => registerPersonalServerSignature,
1268
1299
  scopeCoveredByGrant: () => scopeCoveredByGrant,
1269
1300
  scopeMatchesPattern: () => scopeMatchesPattern,
1270
1301
  scopeToPathSegments: () => scopeToPathSegments,
1271
1302
  serializeECIES: () => serializeECIES,
1272
1303
  serverRegistrationDomain: () => serverRegistrationDomain,
1304
+ signPersonalServerLiteOwnerBinding: () => signPersonalServerLiteOwnerBinding,
1305
+ signPersonalServerLiteOwnerBindingWithAccountClient: () => signPersonalServerLiteOwnerBindingWithAccountClient,
1306
+ signPersonalServerRegistrationWithAccount: () => signPersonalServerRegistrationWithAccount,
1273
1307
  vanaMainnet: () => vanaMainnet2,
1274
1308
  verifyGrantRegistration: () => verifyGrantRegistration,
1275
1309
  verifyPkceChallenge: () => verifyPkceChallenge,
@@ -29139,7 +29173,7 @@ async function buildWeb3SignedHeader(params) {
29139
29173
  }
29140
29174
 
29141
29175
  // src/storage/providers/vana-storage.ts
29142
- var DEFAULT_ENDPOINT = "https://storage.vana.com";
29176
+ var DEFAULT_ENDPOINT = "https://storage.vana.org";
29143
29177
  var BLOB_PATH_PREFIX = "/v1/blobs";
29144
29178
  var DEFAULT_TOKEN_TTL_SECONDS = 300;
29145
29179
  var VanaStorage = class {
@@ -32402,9 +32436,232 @@ var InMemoryTokenStore = class {
32402
32436
  }
32403
32437
  };
32404
32438
 
32439
+ // src/auth/oauth-client.ts
32440
+ var VERIFIER_TTL_SECONDS = 600;
32441
+ var RESERVED_AUTHORIZE_PARAMS = /* @__PURE__ */ new Set([
32442
+ "response_type",
32443
+ "client_id",
32444
+ "redirect_uri",
32445
+ "scope",
32446
+ "state",
32447
+ "code_challenge",
32448
+ "code_challenge_method"
32449
+ ]);
32450
+ var OAuthClient = class {
32451
+ #config;
32452
+ constructor(config) {
32453
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch;
32454
+ if (typeof fetchImpl !== "function") {
32455
+ throw new TypeError(
32456
+ "OAuthClient requires a global `fetch` or an explicit `fetchImpl`"
32457
+ );
32458
+ }
32459
+ this.#config = {
32460
+ authorizationEndpoint: config.authorizationEndpoint,
32461
+ tokenEndpoint: config.tokenEndpoint,
32462
+ clientId: config.clientId,
32463
+ redirectUri: config.redirectUri,
32464
+ scope: config.scope,
32465
+ tokenStore: config.tokenStore ?? new InMemoryTokenStore(),
32466
+ fetchImpl,
32467
+ generateState: config.generateState ?? defaultGenerateState
32468
+ };
32469
+ }
32470
+ /** Build the authorize URL and persist the PKCE verifier keyed by `state`. */
32471
+ async buildAuthorizationUrl(opts = {}) {
32472
+ const state = opts.state ?? this.#config.generateState();
32473
+ const scope = opts.scope ?? this.#config.scope;
32474
+ const verifier = generatePkceVerifier();
32475
+ const challenge = await computePkceChallenge(verifier);
32476
+ await this.#config.tokenStore.set(this.#verifierKey(state), {
32477
+ token: verifier,
32478
+ expiresAt: Math.floor(Date.now() / 1e3) + VERIFIER_TTL_SECONDS
32479
+ });
32480
+ const params = new URLSearchParams();
32481
+ params.set("response_type", "code");
32482
+ params.set("client_id", this.#config.clientId);
32483
+ params.set("redirect_uri", this.#config.redirectUri);
32484
+ if (scope !== void 0 && scope.length > 0) {
32485
+ params.set("scope", scope);
32486
+ }
32487
+ params.set("state", state);
32488
+ params.set("code_challenge", challenge);
32489
+ params.set("code_challenge_method", "S256");
32490
+ if (opts.extraParams !== void 0) {
32491
+ for (const k of Object.keys(opts.extraParams)) {
32492
+ if (RESERVED_AUTHORIZE_PARAMS.has(k)) {
32493
+ throw new Error(
32494
+ `extraParams may not override the reserved OAuth/PKCE parameter "${k}"`
32495
+ );
32496
+ }
32497
+ }
32498
+ for (const [k, v] of Object.entries(opts.extraParams)) {
32499
+ params.set(k, v);
32500
+ }
32501
+ }
32502
+ const sep = this.#config.authorizationEndpoint.includes("?") ? "&" : "?";
32503
+ const url = `${this.#config.authorizationEndpoint}${sep}${params.toString()}`;
32504
+ return { url, state };
32505
+ }
32506
+ /**
32507
+ * Handle the redirect-callback URL. Validates `state`, retrieves the saved
32508
+ * verifier, exchanges the authorization code + verifier for tokens, and
32509
+ * persists them. Returns the access {@link TokenRecord}.
32510
+ */
32511
+ async handleCallback(callbackUrl) {
32512
+ const parsed = new URL(callbackUrl);
32513
+ const params = parsed.searchParams;
32514
+ const errorCode = params.get("error");
32515
+ if (errorCode !== null) {
32516
+ throw new Error(
32517
+ formatOAuthError({
32518
+ error: errorCode,
32519
+ error_description: params.get("error_description") ?? void 0
32520
+ })
32521
+ );
32522
+ }
32523
+ const code = params.get("code");
32524
+ const state = params.get("state");
32525
+ if (code === null || state === null) {
32526
+ throw new Error("OAuth callback is missing `code` or `state`");
32527
+ }
32528
+ const verifierRecord = await this.#config.tokenStore.get(
32529
+ this.#verifierKey(state)
32530
+ );
32531
+ if (verifierRecord === null) {
32532
+ throw new Error(
32533
+ "OAuth callback state does not match any in-flight verifier (possible CSRF or expired flow)"
32534
+ );
32535
+ }
32536
+ const body = new URLSearchParams();
32537
+ body.set("grant_type", "authorization_code");
32538
+ body.set("code", code);
32539
+ body.set("redirect_uri", this.#config.redirectUri);
32540
+ body.set("client_id", this.#config.clientId);
32541
+ body.set("code_verifier", verifierRecord.token);
32542
+ let tokens;
32543
+ try {
32544
+ tokens = await this.#tokenRequest(body);
32545
+ } finally {
32546
+ await this.#config.tokenStore.delete(this.#verifierKey(state));
32547
+ }
32548
+ return this.#persistTokens(tokens);
32549
+ }
32550
+ /**
32551
+ * Exchange a stored refresh token for a fresh access token. Throws if no
32552
+ * refresh token is available.
32553
+ */
32554
+ async refresh() {
32555
+ const refreshRecord = await this.#config.tokenStore.get(this.#refreshKey());
32556
+ if (refreshRecord === null) {
32557
+ throw new Error("OAuth refresh failed: no refresh token stored");
32558
+ }
32559
+ const body = new URLSearchParams();
32560
+ body.set("grant_type", "refresh_token");
32561
+ body.set("refresh_token", refreshRecord.token);
32562
+ body.set("client_id", this.#config.clientId);
32563
+ const tokens = await this.#tokenRequest(body);
32564
+ return this.#persistTokens(tokens, refreshRecord.token);
32565
+ }
32566
+ /**
32567
+ * Get the current access token if valid (refreshing first if expired and a
32568
+ * refresh token is available). Returns `null` when no usable token exists.
32569
+ */
32570
+ async getAccessToken() {
32571
+ const stored = await this.#config.tokenStore.get(this.#accessKey());
32572
+ if (stored !== null) return stored.token;
32573
+ const refresh = await this.#config.tokenStore.get(this.#refreshKey());
32574
+ if (refresh === null) return null;
32575
+ try {
32576
+ const refreshed = await this.refresh();
32577
+ return refreshed.token;
32578
+ } catch {
32579
+ return null;
32580
+ }
32581
+ }
32582
+ /** Forget tokens (logout). Does NOT call any remote revocation endpoint. */
32583
+ async signOut() {
32584
+ await this.#config.tokenStore.delete(this.#accessKey());
32585
+ await this.#config.tokenStore.delete(this.#refreshKey());
32586
+ }
32587
+ #accessKey() {
32588
+ return `oauth:tokens:${this.#config.clientId}`;
32589
+ }
32590
+ #refreshKey() {
32591
+ return `oauth:refresh:${this.#config.clientId}`;
32592
+ }
32593
+ #verifierKey(state) {
32594
+ return `oauth:verifier:${state}`;
32595
+ }
32596
+ async #tokenRequest(body) {
32597
+ const response = await this.#config.fetchImpl(this.#config.tokenEndpoint, {
32598
+ method: "POST",
32599
+ headers: {
32600
+ "Content-Type": "application/x-www-form-urlencoded",
32601
+ Accept: "application/json"
32602
+ },
32603
+ body: body.toString()
32604
+ });
32605
+ const text = await response.text();
32606
+ const parsed = parseJsonBody(text);
32607
+ if (!response.ok) {
32608
+ throw new Error(formatOAuthError(parsed ?? {}, response.status));
32609
+ }
32610
+ if (parsed === null || typeof parsed !== "object" || typeof parsed.access_token !== "string") {
32611
+ throw new Error(
32612
+ "OAuth token endpoint returned a response without an `access_token` string"
32613
+ );
32614
+ }
32615
+ return parsed;
32616
+ }
32617
+ async #persistTokens(tokens, previousRefreshToken) {
32618
+ const record = { token: tokens.access_token };
32619
+ if (typeof tokens.expires_in === "number" && tokens.expires_in > 0) {
32620
+ record.expiresAt = Math.floor(Date.now() / 1e3) + tokens.expires_in;
32621
+ }
32622
+ await this.#config.tokenStore.set(this.#accessKey(), record);
32623
+ const newRefresh = tokens.refresh_token ?? previousRefreshToken;
32624
+ if (newRefresh !== void 0) {
32625
+ await this.#config.tokenStore.set(this.#refreshKey(), {
32626
+ token: newRefresh
32627
+ });
32628
+ }
32629
+ return record;
32630
+ }
32631
+ };
32632
+ function defaultGenerateState() {
32633
+ const bytes = new Uint8Array(24);
32634
+ crypto.getRandomValues(bytes);
32635
+ let binary = "";
32636
+ for (let i = 0; i < bytes.length; i++) {
32637
+ binary += String.fromCharCode(bytes[i]);
32638
+ }
32639
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
32640
+ }
32641
+ function parseJsonBody(text) {
32642
+ if (text.length === 0) return null;
32643
+ try {
32644
+ return JSON.parse(text);
32645
+ } catch {
32646
+ return null;
32647
+ }
32648
+ }
32649
+ function formatOAuthError(body, status) {
32650
+ const parts = ["OAuth token request failed"];
32651
+ if (status !== void 0) parts.push(`(HTTP ${String(status)})`);
32652
+ if (body.error !== void 0 && body.error.length > 0) {
32653
+ parts.push(`: ${body.error}`);
32654
+ if (body.error_description !== void 0 && body.error_description.length > 0) {
32655
+ parts.push(`- ${body.error_description}`);
32656
+ }
32657
+ }
32658
+ return parts.join(" ").replace(" : ", ": ").replace(" - ", " - ");
32659
+ }
32660
+
32405
32661
  // src/protocol/eip712.ts
32406
32662
  var DOMAIN_NAME = "Vana Data Portability";
32407
32663
  var DOMAIN_VERSION = "1";
32664
+ var NATIVE_VANA_ASSET = "0x0000000000000000000000000000000000000000";
32408
32665
  function buildDomain(chainId, verifyingContract) {
32409
32666
  return {
32410
32667
  name: DOMAIN_NAME,
@@ -32419,6 +32676,12 @@ function fileRegistrationDomain(config) {
32419
32676
  config.contracts.dataRegistry
32420
32677
  );
32421
32678
  }
32679
+ function dataRegistryDomain(config) {
32680
+ return buildDomain(
32681
+ config.chainId,
32682
+ config.contracts.dataRegistry
32683
+ );
32684
+ }
32422
32685
  function grantRegistrationDomain(config) {
32423
32686
  return buildDomain(
32424
32687
  config.chainId,
@@ -32443,6 +32706,12 @@ function builderRegistrationDomain(config) {
32443
32706
  config.contracts.dataPortabilityGrantees
32444
32707
  );
32445
32708
  }
32709
+ function escrowPaymentDomain(config) {
32710
+ return buildDomain(
32711
+ config.chainId,
32712
+ config.contracts.dataPortabilityEscrow
32713
+ );
32714
+ }
32446
32715
  var FILE_REGISTRATION_TYPES = {
32447
32716
  FileRegistration: [
32448
32717
  { name: "ownerAddress", type: "address" },
@@ -32454,14 +32723,16 @@ var GRANT_REGISTRATION_TYPES = {
32454
32723
  GrantRegistration: [
32455
32724
  { name: "grantorAddress", type: "address" },
32456
32725
  { name: "granteeId", type: "bytes32" },
32457
- { name: "grant", type: "string" },
32458
- { name: "fileIds", type: "uint256[]" }
32726
+ { name: "scopes", type: "string[]" },
32727
+ { name: "grantVersion", type: "uint256" },
32728
+ { name: "expiresAt", type: "uint256" }
32459
32729
  ]
32460
32730
  };
32461
32731
  var GRANT_REVOCATION_TYPES = {
32462
32732
  GrantRevocation: [
32463
32733
  { name: "grantorAddress", type: "address" },
32464
- { name: "grantId", type: "bytes32" }
32734
+ { name: "grantId", type: "bytes32" },
32735
+ { name: "grantVersion", type: "uint256" }
32465
32736
  ]
32466
32737
  };
32467
32738
  var SERVER_REGISTRATION_TYPES = {
@@ -32480,87 +32751,500 @@ var BUILDER_REGISTRATION_TYPES = {
32480
32751
  { name: "appUrl", type: "string" }
32481
32752
  ]
32482
32753
  };
32754
+ var GENERIC_PAYMENT_TYPES = {
32755
+ GenericPayment: [
32756
+ { name: "payerAddress", type: "address" },
32757
+ { name: "opType", type: "string" },
32758
+ { name: "opId", type: "bytes32" },
32759
+ { name: "asset", type: "address" },
32760
+ { name: "amount", type: "uint256" },
32761
+ { name: "paymentNonce", type: "uint256" }
32762
+ ]
32763
+ };
32764
+ var ADD_DATA_TYPES = {
32765
+ AddData: [
32766
+ { name: "ownerAddress", type: "address" },
32767
+ { name: "scope", type: "string" },
32768
+ { name: "dataHash", type: "bytes32" },
32769
+ { name: "metadataHash", type: "bytes32" },
32770
+ { name: "expectedVersion", type: "uint256" }
32771
+ ]
32772
+ };
32773
+ var RECORD_DATA_ACCESS_TYPES = {
32774
+ RecordDataAccess: [
32775
+ { name: "ownerAddress", type: "address" },
32776
+ { name: "scope", type: "string" },
32777
+ { name: "version", type: "uint256" },
32778
+ { name: "accessor", type: "address" },
32779
+ { name: "recordId", type: "bytes32" }
32780
+ ]
32781
+ };
32483
32782
 
32484
- // src/protocol/grants.ts
32783
+ // src/protocol/personal-server-registration.ts
32485
32784
  var import_viem14 = require("viem");
32486
- function isHexString(value) {
32487
- return typeof value === "string" && value.startsWith("0x");
32785
+ var PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID = 1480;
32786
+ var PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT = "0x1483B1F634DBA75AeaE60da7f01A679aabd5ee2c";
32787
+ function assertAddress(value, name) {
32788
+ if (!(0, import_viem14.isAddress)(value)) {
32789
+ throw new Error(`${name} must be a valid EVM address`);
32790
+ }
32488
32791
  }
32489
- function isDataPortabilityGatewayConfig(value) {
32490
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
32491
- return false;
32792
+ function getAccountAddress(account) {
32793
+ if (!account) {
32794
+ return void 0;
32492
32795
  }
32493
- const config = value;
32494
- const contracts = config["contracts"];
32495
- if (typeof config["chainId"] !== "number" || !Number.isInteger(config["chainId"]) || config["chainId"] <= 0 || contracts === null || typeof contracts !== "object" || Array.isArray(contracts)) {
32496
- return false;
32796
+ return typeof account === "string" ? account : account.address;
32797
+ }
32798
+ function isPersonalServerRegistrationSigner(source) {
32799
+ return "address" in source && typeof source.signTypedData === "function";
32800
+ }
32801
+ function createViemPersonalServerRegistrationSigner(source, options = {}) {
32802
+ if (isPersonalServerRegistrationSigner(source)) {
32803
+ return source;
32497
32804
  }
32498
- const c = contracts;
32499
- return isHexString(c["dataRegistry"]) && isHexString(c["dataPortabilityPermissions"]) && isHexString(c["dataPortabilityServer"]) && isHexString(c["dataPortabilityGrantees"]);
32805
+ const accountAddress = getAccountAddress(options.account) ?? getAccountAddress(source.account);
32806
+ if (accountAddress) {
32807
+ return {
32808
+ address: accountAddress,
32809
+ signTypedData: (typedData) => source.signTypedData({
32810
+ ...typedData,
32811
+ account: options.account ?? source.account ?? accountAddress
32812
+ })
32813
+ };
32814
+ }
32815
+ throw new Error(
32816
+ "Viem wallet client requires an account option or account property"
32817
+ );
32500
32818
  }
32501
- function parseGrantRegistrationPayload(grant) {
32502
- let parsed;
32503
- try {
32504
- parsed = JSON.parse(grant);
32505
- } catch {
32506
- return null;
32819
+ function personalServerRegistrationDomain(input = {}) {
32820
+ if (input.config) {
32821
+ return serverRegistrationDomain(input.config);
32507
32822
  }
32508
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
32509
- return null;
32823
+ const verifyingContract = input.verifyingContract ?? PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT;
32824
+ assertAddress(verifyingContract, "verifyingContract");
32825
+ return {
32826
+ name: "Vana Data Portability",
32827
+ version: "1",
32828
+ chainId: input.chainId ?? PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID,
32829
+ verifyingContract
32830
+ };
32831
+ }
32832
+ function buildPersonalServerRegistrationTypedData(input) {
32833
+ assertAddress(input.ownerAddress, "ownerAddress");
32834
+ assertAddress(input.serverAddress, "serverAddress");
32835
+ return {
32836
+ domain: personalServerRegistrationDomain(input),
32837
+ types: SERVER_REGISTRATION_TYPES,
32838
+ primaryType: "ServerRegistration",
32839
+ message: {
32840
+ ownerAddress: input.ownerAddress,
32841
+ serverAddress: input.serverAddress,
32842
+ publicKey: input.serverPublicKey,
32843
+ serverUrl: input.serverUrl
32844
+ }
32845
+ };
32846
+ }
32847
+ async function buildPersonalServerRegistrationSignature(input) {
32848
+ const typedData = buildPersonalServerRegistrationTypedData({
32849
+ ownerAddress: input.signer.address,
32850
+ serverAddress: input.serverAddress,
32851
+ serverPublicKey: input.serverPublicKey,
32852
+ serverUrl: input.serverUrl,
32853
+ config: input.config,
32854
+ chainId: input.chainId,
32855
+ verifyingContract: input.verifyingContract
32856
+ });
32857
+ const signature = await input.signer.signTypedData(typedData);
32858
+ return {
32859
+ signature,
32860
+ signerAddress: input.signer.address,
32861
+ typedData
32862
+ };
32863
+ }
32864
+ var registerPersonalServerSignature = buildPersonalServerRegistrationSignature;
32865
+
32866
+ // src/protocol/personal-server-lite-owner-binding.ts
32867
+ var import_viem15 = require("viem");
32868
+ var PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION = "vana.account.v1";
32869
+ var PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE = "ps-lite-owner";
32870
+ var PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX = `${PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION}:${PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE}:`;
32871
+ function assertAddress2(value, name) {
32872
+ if (!(0, import_viem15.isAddress)(value)) {
32873
+ throw new Error(`${name} must be a valid EVM address`);
32510
32874
  }
32511
- const value = parsed;
32512
- if (!Array.isArray(value["scopes"]) || value["scopes"].length === 0) {
32513
- return null;
32875
+ }
32876
+ function getAccountAddress2(account) {
32877
+ if (!account) {
32878
+ return void 0;
32514
32879
  }
32515
- if (!value["scopes"].every((scope) => typeof scope === "string")) {
32516
- return null;
32880
+ return typeof account === "string" ? account : account.address;
32881
+ }
32882
+ function isPersonalServerLiteOwnerBindingSigner(source) {
32883
+ return "address" in source && typeof source.signMessage === "function";
32884
+ }
32885
+ function buildPersonalServerLiteOwnerBindingMessage(ownerAddress) {
32886
+ assertAddress2(ownerAddress, "ownerAddress");
32887
+ return `${PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX}${ownerAddress.toLowerCase()}`;
32888
+ }
32889
+ function createViemPersonalServerLiteOwnerBindingSigner(source, options = {}) {
32890
+ if (isPersonalServerLiteOwnerBindingSigner(source)) {
32891
+ return source;
32517
32892
  }
32518
- if (typeof value["expiresAt"] !== "number" || !Number.isFinite(value["expiresAt"])) {
32519
- return null;
32893
+ const accountAddress = getAccountAddress2(options.account) ?? getAccountAddress2(source.account);
32894
+ if (accountAddress) {
32895
+ return {
32896
+ address: accountAddress,
32897
+ signMessage: ({ message }) => source.signMessage({
32898
+ account: options.account ?? source.account ?? accountAddress,
32899
+ message
32900
+ })
32901
+ };
32520
32902
  }
32521
- if (value["user"] !== void 0 && !isHexString(value["user"])) {
32522
- return null;
32903
+ throw new Error(
32904
+ "Viem wallet client requires an account option or account property"
32905
+ );
32906
+ }
32907
+ async function buildPersonalServerLiteOwnerBindingSignature(input) {
32908
+ const message = buildPersonalServerLiteOwnerBindingMessage(
32909
+ input.signer.address
32910
+ );
32911
+ const signature = await input.signer.signMessage({ message });
32912
+ return {
32913
+ signature,
32914
+ signerAddress: input.signer.address,
32915
+ message,
32916
+ purpose: PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE
32917
+ };
32918
+ }
32919
+ var signPersonalServerLiteOwnerBinding = buildPersonalServerLiteOwnerBindingSignature;
32920
+
32921
+ // src/account/personal-server-registration.ts
32922
+ var import_viem16 = require("viem");
32923
+ var ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT = "personal_server.server_registration.v1";
32924
+ var AccountPersonalServerRegistrationError = class extends Error {
32925
+ status;
32926
+ code;
32927
+ details;
32928
+ constructor(input) {
32929
+ super(input.message);
32930
+ this.name = "AccountPersonalServerRegistrationError";
32931
+ this.status = input.status;
32932
+ this.code = input.code;
32933
+ this.details = input.details;
32523
32934
  }
32524
- if (value["builder"] !== void 0 && !isHexString(value["builder"])) {
32525
- return null;
32935
+ };
32936
+ var DEFAULT_ACCOUNT_PS_REGISTRATION_PATH = "/api/v1/intents/personal-server-registration/sign";
32937
+ function trimTrailingSlash(value) {
32938
+ return value.replace(/\/+$/, "");
32939
+ }
32940
+ function assertAddress3(value, name) {
32941
+ if (!(0, import_viem16.isAddress)(value)) {
32942
+ throw new Error(`${name} must be a valid EVM address`);
32526
32943
  }
32527
- if (value["nonce"] !== void 0 && (typeof value["nonce"] !== "number" || !Number.isFinite(value["nonce"]))) {
32528
- return null;
32944
+ }
32945
+ async function parseAccountResponse(response) {
32946
+ const body = await response.json().catch(() => void 0);
32947
+ if (!response.ok) {
32948
+ throw new AccountPersonalServerRegistrationError({
32949
+ status: response.status,
32950
+ code: accountErrorCode(body),
32951
+ message: accountErrorMessage(response.status, body),
32952
+ details: body
32953
+ });
32954
+ }
32955
+ return body;
32956
+ }
32957
+ function accountErrorMessage(status, body) {
32958
+ const nestedMessage = nestedAccountErrorField(body, "message");
32959
+ if (nestedMessage) {
32960
+ return nestedMessage;
32961
+ }
32962
+ if (isRecord(body) && typeof body.message === "string") {
32963
+ return body.message;
32964
+ }
32965
+ const code = accountErrorCode(body);
32966
+ if (code) {
32967
+ return `Account PS registration signing failed: ${code}`;
32968
+ }
32969
+ return `Account PS registration signing failed: ${status}`;
32970
+ }
32971
+ function accountErrorCode(body) {
32972
+ const nestedCode = nestedAccountErrorField(body, "code");
32973
+ if (nestedCode) {
32974
+ return nestedCode;
32975
+ }
32976
+ if (isRecord(body)) {
32977
+ if (typeof body.code === "string") {
32978
+ return body.code;
32979
+ }
32980
+ if (typeof body.error === "string") {
32981
+ return body.error;
32982
+ }
32983
+ }
32984
+ return void 0;
32985
+ }
32986
+ function nestedAccountErrorField(body, field) {
32987
+ if (!isRecord(body) || !isRecord(body.error)) {
32988
+ return void 0;
32529
32989
  }
32990
+ const value = body.error[field];
32991
+ return typeof value === "string" ? value : void 0;
32992
+ }
32993
+ function isRecord(value) {
32994
+ return typeof value === "object" && value !== null;
32995
+ }
32996
+ function normalizeAccountResponse(response) {
32530
32997
  return {
32531
- user: value["user"],
32532
- builder: value["builder"],
32533
- scopes: value["scopes"],
32534
- expiresAt: value["expiresAt"],
32535
- nonce: value["nonce"]
32998
+ ...response,
32999
+ status: response.status === "fallback_required" ? "confirmation_required" : response.status,
33000
+ signerAddress: response.signerAddress ?? response.signer?.address,
33001
+ typedData: response.typedData ?? response.typed_data
32536
33002
  };
32537
33003
  }
32538
- function parseFileIds(fileIds) {
32539
- try {
32540
- const values = (fileIds ?? []).map((fileId) => BigInt(fileId));
33004
+ function buildSignedResult(response, request) {
33005
+ assertAddress3(response.signerAddress, "signerAddress");
33006
+ if (response.typedData) {
33007
+ assertTypedDataMatchesRequest(
33008
+ response.typedData,
33009
+ request,
33010
+ response.signerAddress
33011
+ );
33012
+ }
33013
+ return {
33014
+ signature: response.signature,
33015
+ signerAddress: response.signerAddress,
33016
+ typedData: response.typedData ?? buildPersonalServerRegistrationTypedData({
33017
+ ownerAddress: response.signerAddress,
33018
+ ...request
33019
+ }),
33020
+ intent: ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT
33021
+ };
33022
+ }
33023
+ function assertTypedDataMatchesRequest(typedData, request, expectedSignerAddress) {
33024
+ assertAddress3(
33025
+ typedData.message.ownerAddress,
33026
+ "typedData.message.ownerAddress"
33027
+ );
33028
+ assertAddress3(
33029
+ typedData.message.serverAddress,
33030
+ "typedData.message.serverAddress"
33031
+ );
33032
+ if (expectedSignerAddress && !sameAddress(typedData.message.ownerAddress, expectedSignerAddress)) {
33033
+ throw new Error(
33034
+ "Account typedData ownerAddress must match the expected signer address"
33035
+ );
33036
+ }
33037
+ if (!sameAddress(typedData.message.serverAddress, request.serverAddress)) {
33038
+ throw new Error(
33039
+ "Account typedData serverAddress must match the requested serverAddress"
33040
+ );
33041
+ }
33042
+ if (typedData.message.publicKey !== request.serverPublicKey) {
33043
+ throw new Error(
33044
+ "Account typedData publicKey must match the requested serverPublicKey"
33045
+ );
33046
+ }
33047
+ if (typedData.message.serverUrl !== request.serverUrl) {
33048
+ throw new Error(
33049
+ "Account typedData serverUrl must match the requested serverUrl"
33050
+ );
33051
+ }
33052
+ if (typedData.primaryType !== "ServerRegistration") {
33053
+ throw new Error("Account typedData primaryType must be ServerRegistration");
33054
+ }
33055
+ if (JSON.stringify(typedData.types) !== JSON.stringify(SERVER_REGISTRATION_TYPES)) {
33056
+ throw new Error("Account typedData types must be ServerRegistration types");
33057
+ }
33058
+ const expectedDomain = personalServerRegistrationDomain({
33059
+ config: request.config,
33060
+ chainId: request.chainId,
33061
+ verifyingContract: request.verifyingContract
33062
+ });
33063
+ if (!domainsEqual(typedData.domain, expectedDomain)) {
33064
+ throw new Error("Account typedData domain must match the requested domain");
33065
+ }
33066
+ }
33067
+ function sameAddress(a, b) {
33068
+ return a.toLowerCase() === b.toLowerCase();
33069
+ }
33070
+ function domainsEqual(a, b) {
33071
+ if (!a || !b) {
33072
+ return false;
33073
+ }
33074
+ return a.name === b.name && a.version === b.version && Number(a.chainId) === Number(b.chainId) && String(a.verifyingContract ?? "").toLowerCase() === String(b.verifyingContract ?? "").toLowerCase() && a.salt === b.salt;
33075
+ }
33076
+ async function signPersonalServerRegistrationWithAccount(config, request) {
33077
+ assertAddress3(request.serverAddress, "serverAddress");
33078
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
33079
+ const endpoint = new URL(
33080
+ config.endpointPath ?? DEFAULT_ACCOUNT_PS_REGISTRATION_PATH,
33081
+ `${trimTrailingSlash(config.accountOrigin)}/`
33082
+ );
33083
+ const response = await fetchImpl(endpoint, {
33084
+ method: "POST",
33085
+ headers: { "content-type": "application/json" },
33086
+ credentials: "include",
33087
+ body: JSON.stringify({
33088
+ intent: ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT,
33089
+ serverAddress: request.serverAddress,
33090
+ serverPublicKey: request.serverPublicKey,
33091
+ serverUrl: request.serverUrl,
33092
+ config: request.config,
33093
+ chainId: request.chainId,
33094
+ verifyingContract: request.verifyingContract
33095
+ })
33096
+ });
33097
+ const body = normalizeAccountResponse(await parseAccountResponse(response));
33098
+ if (body.status === "signed") {
33099
+ if (!body.signature || !body.signerAddress) {
33100
+ throw new Error(
33101
+ "Account signed response must include signature and signerAddress"
33102
+ );
33103
+ }
32541
33104
  return {
32542
- values,
32543
- display: values.map((fileId) => fileId.toString())
33105
+ status: "signed",
33106
+ result: buildSignedResult(
33107
+ {
33108
+ signature: body.signature,
33109
+ signerAddress: body.signerAddress,
33110
+ typedData: body.typedData
33111
+ },
33112
+ request
33113
+ )
32544
33114
  };
33115
+ }
33116
+ if (body.status === "confirmation_required") {
33117
+ if (!body.typedData) {
33118
+ throw new Error(
33119
+ "Account confirmation_required response must include typedData"
33120
+ );
33121
+ }
33122
+ assertTypedDataMatchesRequest(body.typedData, request, body.signerAddress);
33123
+ if (!config.fallbackSigner) {
33124
+ return {
33125
+ status: "confirmation_required",
33126
+ typedData: body.typedData,
33127
+ signerAddress: body.signerAddress
33128
+ };
33129
+ }
33130
+ assertTypedDataMatchesRequest(
33131
+ body.typedData,
33132
+ request,
33133
+ config.fallbackSigner.address
33134
+ );
33135
+ const signature = await config.fallbackSigner.signTypedData(body.typedData);
33136
+ return {
33137
+ status: "fallback_signed",
33138
+ accountStatus: "confirmation_required",
33139
+ result: {
33140
+ signature,
33141
+ signerAddress: config.fallbackSigner.address,
33142
+ typedData: body.typedData,
33143
+ intent: ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT
33144
+ }
33145
+ };
33146
+ }
33147
+ throw new Error(
33148
+ `Unsupported Account PS registration signing status: ${String(body.status)}`
33149
+ );
33150
+ }
33151
+
33152
+ // src/account/personal-server-lite-owner-binding.ts
33153
+ var AccountPersonalServerLiteOwnerBindingError = class extends Error {
33154
+ code;
33155
+ details;
33156
+ constructor(input) {
33157
+ super(input.message);
33158
+ this.name = "AccountPersonalServerLiteOwnerBindingError";
33159
+ this.code = input.code;
33160
+ this.details = input.details;
33161
+ }
33162
+ };
33163
+ async function signPersonalServerLiteOwnerBindingWithAccountClient(config) {
33164
+ let address;
33165
+ try {
33166
+ address = await config.client.getAddress();
33167
+ } catch (error) {
33168
+ throw accountOwnerBindingError(error);
33169
+ }
33170
+ if (!address) {
33171
+ throw new AccountPersonalServerLiteOwnerBindingError({
33172
+ message: "Account did not return a wallet address",
33173
+ code: "account_address_required"
33174
+ });
33175
+ }
33176
+ const message = buildPersonalServerLiteOwnerBindingMessage(address);
33177
+ let signature;
33178
+ try {
33179
+ signature = await config.client.signMessage({ message });
33180
+ } catch (error) {
33181
+ throw accountOwnerBindingError(error);
33182
+ }
33183
+ return {
33184
+ signature,
33185
+ signerAddress: address,
33186
+ message,
33187
+ purpose: PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE
33188
+ };
33189
+ }
33190
+ function accountOwnerBindingError(error) {
33191
+ if (error instanceof AccountPersonalServerLiteOwnerBindingError) {
33192
+ return error;
33193
+ }
33194
+ const rpcError = error;
33195
+ const code = rpcError?.code;
33196
+ const message = typeof rpcError?.message === "string" && rpcError.message.length > 0 ? rpcError.message : "Account PS Lite owner-binding signature failed";
33197
+ return new AccountPersonalServerLiteOwnerBindingError({
33198
+ message,
33199
+ code,
33200
+ details: error
33201
+ });
33202
+ }
33203
+
33204
+ // src/protocol/grants.ts
33205
+ var import_viem17 = require("viem");
33206
+ function isHexString(value) {
33207
+ return typeof value === "string" && value.startsWith("0x");
33208
+ }
33209
+ function isDataPortabilityGatewayConfig(value) {
33210
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
33211
+ return false;
33212
+ }
33213
+ const config = value;
33214
+ const contracts = config["contracts"];
33215
+ if (typeof config["chainId"] !== "number" || !Number.isInteger(config["chainId"]) || config["chainId"] <= 0 || contracts === null || typeof contracts !== "object" || Array.isArray(contracts)) {
33216
+ return false;
33217
+ }
33218
+ const c = contracts;
33219
+ return isHexString(c["dataRegistry"]) && isHexString(c["dataPortabilityPermissions"]) && isHexString(c["dataPortabilityServer"]) && isHexString(c["dataPortabilityGrantees"]) && isHexString(c["dataPortabilityEscrow"]) && isHexString(c["feeRegistry"]);
33220
+ }
33221
+ function toUint256(value) {
33222
+ try {
33223
+ const big = typeof value === "bigint" ? value : BigInt(value);
33224
+ if (big < 0n) return null;
33225
+ return big;
32545
33226
  } catch {
32546
33227
  return null;
32547
33228
  }
32548
33229
  }
32549
33230
  async function verifyGrantRegistration(input) {
32550
- const payload = parseGrantRegistrationPayload(input.grant);
32551
- if (!payload) {
32552
- return {
32553
- valid: false,
32554
- error: "Grant must be JSON with scopes and expiresAt"
32555
- };
33231
+ if (!Array.isArray(input.scopes) || input.scopes.length === 0) {
33232
+ return { valid: false, error: "scopes must be a non-empty array" };
33233
+ }
33234
+ if (!input.scopes.every((scope) => typeof scope === "string")) {
33235
+ return { valid: false, error: "scopes must contain only strings" };
32556
33236
  }
32557
- const fileIds = parseFileIds(input.fileIds);
32558
- if (!fileIds) {
32559
- return { valid: false, error: "fileIds must contain integer values" };
33237
+ const grantVersion = toUint256(input.grantVersion);
33238
+ if (grantVersion === null || grantVersion < 1n) {
33239
+ return { valid: false, error: "grantVersion must be a uint256 >= 1" };
33240
+ }
33241
+ const expiresAt = toUint256(input.expiresAt);
33242
+ if (expiresAt === null) {
33243
+ return { valid: false, error: "expiresAt must be a non-negative uint256" };
32560
33244
  }
32561
33245
  let valid;
32562
33246
  try {
32563
- valid = await (0, import_viem14.verifyTypedData)({
33247
+ valid = await (0, import_viem17.verifyTypedData)({
32564
33248
  address: input.grantorAddress,
32565
33249
  domain: grantRegistrationDomain(input.gatewayConfig),
32566
33250
  types: GRANT_REGISTRATION_TYPES,
@@ -32568,8 +33252,9 @@ async function verifyGrantRegistration(input) {
32568
33252
  message: {
32569
33253
  grantorAddress: input.grantorAddress,
32570
33254
  granteeId: input.granteeId,
32571
- grant: input.grant,
32572
- fileIds: fileIds.values
33255
+ scopes: input.scopes,
33256
+ grantVersion,
33257
+ expiresAt
32573
33258
  },
32574
33259
  signature: input.signature
32575
33260
  });
@@ -32580,19 +33265,128 @@ async function verifyGrantRegistration(input) {
32580
33265
  return { valid: false, error: "Grant signature does not match grantor" };
32581
33266
  }
32582
33267
  const nowSeconds = input.nowSeconds ?? Math.floor(Date.now() / 1e3);
32583
- if (payload.expiresAt > 0 && payload.expiresAt < nowSeconds) {
33268
+ if (expiresAt > 0n && expiresAt < BigInt(nowSeconds)) {
32584
33269
  return { valid: false, error: "Grant has expired" };
32585
33270
  }
32586
- if (payload.user !== void 0 && payload.user.toLowerCase() !== input.grantorAddress.toLowerCase()) {
32587
- return { valid: false, error: "Grant user does not match grantorAddress" };
32588
- }
32589
33271
  return {
32590
33272
  valid: true,
32591
33273
  grantorAddress: input.grantorAddress,
32592
33274
  granteeId: input.granteeId,
32593
- grant: input.grant,
32594
- payload,
32595
- fileIds: fileIds.display
33275
+ scopes: input.scopes,
33276
+ grantVersion: grantVersion.toString(),
33277
+ expiresAt: expiresAt.toString()
33278
+ };
33279
+ }
33280
+
33281
+ // src/protocol/escrow-deposit.ts
33282
+ var import_viem18 = require("viem");
33283
+ var ESCROW_DEPOSIT_ABI = [
33284
+ {
33285
+ type: "function",
33286
+ name: "depositNative",
33287
+ stateMutability: "payable",
33288
+ inputs: [{ name: "account", type: "address" }],
33289
+ outputs: []
33290
+ },
33291
+ {
33292
+ type: "function",
33293
+ name: "depositToken",
33294
+ stateMutability: "nonpayable",
33295
+ inputs: [
33296
+ { name: "account", type: "address" },
33297
+ { name: "token", type: "address" },
33298
+ { name: "amount", type: "uint256" }
33299
+ ],
33300
+ outputs: []
33301
+ }
33302
+ ];
33303
+ function escrowContractAddress(config) {
33304
+ return config.contracts.dataPortabilityEscrow;
33305
+ }
33306
+ function encodeDepositNativeData(input) {
33307
+ return (0, import_viem18.encodeFunctionData)({
33308
+ abi: ESCROW_DEPOSIT_ABI,
33309
+ functionName: "depositNative",
33310
+ args: [input.account]
33311
+ });
33312
+ }
33313
+ function encodeDepositTokenData(input) {
33314
+ return (0, import_viem18.encodeFunctionData)({
33315
+ abi: ESCROW_DEPOSIT_ABI,
33316
+ functionName: "depositToken",
33317
+ args: [input.account, input.token, input.amount]
33318
+ });
33319
+ }
33320
+ function buildDepositNativeRequest(config, input) {
33321
+ return {
33322
+ to: escrowContractAddress(config),
33323
+ data: encodeDepositNativeData({ account: input.account }),
33324
+ value: input.amount
33325
+ };
33326
+ }
33327
+ function buildDepositTokenRequest(config, input) {
33328
+ return {
33329
+ to: escrowContractAddress(config),
33330
+ data: encodeDepositTokenData(input)
33331
+ };
33332
+ }
33333
+
33334
+ // src/protocol/fee-registry.ts
33335
+ var import_viem19 = require("viem");
33336
+ var FEE_REGISTRY_ABI = (0, import_viem19.parseAbi)([
33337
+ "struct Fee { uint256 amount; address asset; address payee; bool enabled; }",
33338
+ "function fees(bytes32 operation) view returns (Fee)",
33339
+ "function operationKey(string name) pure returns (bytes32)"
33340
+ ]);
33341
+ function operationNameFor(kind, opts) {
33342
+ if (kind === "registration") {
33343
+ return opts?.registrationOpName ?? "registration";
33344
+ }
33345
+ return opts?.dataAccessOpName ?? "data_access";
33346
+ }
33347
+ async function getFee(client, config, kind, opts) {
33348
+ const address = config.contracts.feeRegistry;
33349
+ const opName = operationNameFor(kind, opts);
33350
+ const opKey = await client.readContract({
33351
+ address,
33352
+ abi: FEE_REGISTRY_ABI,
33353
+ functionName: "operationKey",
33354
+ args: [opName]
33355
+ });
33356
+ const fee = await client.readContract({
33357
+ address,
33358
+ abi: FEE_REGISTRY_ABI,
33359
+ functionName: "fees",
33360
+ args: [opKey]
33361
+ });
33362
+ if (!fee.enabled) {
33363
+ throw new Error(
33364
+ `FeeRegistry: operation "${opName}" (kind=${kind}) is not enabled \u2014 operator must call setFeeByName before payments will validate`
33365
+ );
33366
+ }
33367
+ if (fee.payee === "0x0000000000000000000000000000000000000000") {
33368
+ throw new Error(
33369
+ `FeeRegistry: operation "${opName}" has zero-address payee \u2014 contract pre-flight rejects payouts to 0x0`
33370
+ );
33371
+ }
33372
+ return fee;
33373
+ }
33374
+ async function getOpFee(client, config, opts) {
33375
+ const [registration, dataAccess] = await Promise.all([
33376
+ getFee(client, config, "registration", opts),
33377
+ getFee(client, config, "data_access", opts)
33378
+ ]);
33379
+ if (registration.asset.toLowerCase() !== dataAccess.asset.toLowerCase()) {
33380
+ throw new Error(
33381
+ `FeeRegistry asset mismatch: registration=${registration.asset} vs data_access=${dataAccess.asset}. The gateway requires both fees to settle in the same asset.`
33382
+ );
33383
+ }
33384
+ return {
33385
+ asset: registration.asset,
33386
+ registrationFee: registration.amount,
33387
+ dataAccessFee: dataAccess.amount,
33388
+ registrationPayee: registration.payee,
33389
+ dataAccessPayee: dataAccess.payee
32596
33390
  };
32597
33391
  }
32598
33392
 
@@ -32792,6 +33586,68 @@ function createGatewayClient(baseUrl) {
32792
33586
  alreadyRegistered: false
32793
33587
  };
32794
33588
  },
33589
+ async registerBuilder(params) {
33590
+ const res = await fetch(`${base}/v1/builders`, {
33591
+ method: "POST",
33592
+ headers: {
33593
+ "Content-Type": "application/json",
33594
+ Authorization: `Web3Signed ${params.signature}`
33595
+ },
33596
+ body: JSON.stringify({
33597
+ ownerAddress: params.ownerAddress,
33598
+ granteeAddress: params.granteeAddress,
33599
+ publicKey: params.publicKey,
33600
+ appUrl: params.appUrl
33601
+ })
33602
+ });
33603
+ if (res.status === 409) {
33604
+ const body2 = await res.json().catch(() => ({}));
33605
+ return {
33606
+ builderId: getMutationId(
33607
+ body2,
33608
+ "builderId"
33609
+ ),
33610
+ alreadyRegistered: true
33611
+ };
33612
+ }
33613
+ if (!res.ok) {
33614
+ throw new Error(`Gateway error: ${res.status} ${res.statusText}`);
33615
+ }
33616
+ const body = await res.json().catch(() => ({}));
33617
+ return {
33618
+ builderId: getMutationId(body, "builderId"),
33619
+ alreadyRegistered: false
33620
+ };
33621
+ },
33622
+ async registerDataPoint(params) {
33623
+ const res = await fetch(`${base}/v1/data`, {
33624
+ method: "POST",
33625
+ headers: {
33626
+ "Content-Type": "application/json",
33627
+ Authorization: `Web3Signed ${params.signature}`
33628
+ },
33629
+ body: JSON.stringify({
33630
+ ownerAddress: params.ownerAddress,
33631
+ scope: params.scope,
33632
+ dataHash: params.dataHash,
33633
+ metadataHash: params.metadataHash,
33634
+ expectedVersion: params.expectedVersion
33635
+ })
33636
+ });
33637
+ if (!res.ok) {
33638
+ const body2 = await res.json().catch(() => ({}));
33639
+ const detail = body2.error ?? res.statusText;
33640
+ throw new Error(`Gateway error: ${res.status} ${detail}`);
33641
+ }
33642
+ const body = await res.json().catch(() => ({}));
33643
+ return {
33644
+ dataPointId: getMutationId(
33645
+ body,
33646
+ "dataPointId"
33647
+ ),
33648
+ expectedVersion: body.expectedVersion
33649
+ };
33650
+ },
32795
33651
  async registerFile(params) {
32796
33652
  const res = await fetch(`${base}/v1/files`, {
32797
33653
  method: "POST",
@@ -32829,8 +33685,9 @@ function createGatewayClient(baseUrl) {
32829
33685
  body: JSON.stringify({
32830
33686
  grantorAddress: params.grantorAddress,
32831
33687
  granteeId: params.granteeId,
32832
- grant: params.grant,
32833
- fileIds: params.fileIds
33688
+ scopes: params.scopes,
33689
+ grantVersion: params.grantVersion,
33690
+ expiresAt: params.expiresAt
32834
33691
  })
32835
33692
  });
32836
33693
  if (res.status === 409) {
@@ -32855,13 +33712,71 @@ function createGatewayClient(baseUrl) {
32855
33712
  Authorization: `Web3Signed ${params.signature}`
32856
33713
  },
32857
33714
  body: JSON.stringify({
32858
- grantorAddress: params.grantorAddress
33715
+ grantorAddress: params.grantorAddress,
33716
+ grantVersion: params.grantVersion
32859
33717
  })
32860
33718
  });
32861
33719
  if (res.status === 409) return;
32862
33720
  if (!res.ok) {
32863
33721
  throw new Error(`Gateway error: ${res.status} ${res.statusText}`);
32864
33722
  }
33723
+ },
33724
+ async getEscrowBalance(account) {
33725
+ const res = await fetch(`${base}/v1/escrow/balance?account=${account}`);
33726
+ if (!res.ok) {
33727
+ throw new Error(`Gateway error: ${res.status} ${res.statusText}`);
33728
+ }
33729
+ return await res.json();
33730
+ },
33731
+ async submitEscrowDeposit(params) {
33732
+ const res = await fetch(`${base}/v1/escrow/deposit`, {
33733
+ method: "POST",
33734
+ headers: { "Content-Type": "application/json" },
33735
+ body: JSON.stringify({ txHash: params.txHash })
33736
+ });
33737
+ if (res.status !== 200 && res.status !== 202) {
33738
+ throw new Error(`Gateway error: ${res.status} ${res.statusText}`);
33739
+ }
33740
+ return await res.json();
33741
+ },
33742
+ async payForOperation(params) {
33743
+ const body = {
33744
+ payerAddress: params.payerAddress,
33745
+ opType: params.opType,
33746
+ opId: params.opId,
33747
+ asset: params.asset,
33748
+ amount: params.amount,
33749
+ paymentNonce: params.paymentNonce
33750
+ };
33751
+ if (params.accessRecord) {
33752
+ body["accessRecord"] = params.accessRecord;
33753
+ }
33754
+ const res = await fetch(`${base}/v1/escrow/pay`, {
33755
+ method: "POST",
33756
+ headers: {
33757
+ "Content-Type": "application/json",
33758
+ Authorization: `Web3Signed ${params.signature}`
33759
+ },
33760
+ body: JSON.stringify(body)
33761
+ });
33762
+ if (!res.ok) {
33763
+ throw new Error(`Gateway error: ${res.status} ${res.statusText}`);
33764
+ }
33765
+ return await res.json();
33766
+ },
33767
+ async settle(params) {
33768
+ const res = await fetch(`${base}/v1/settle`, {
33769
+ method: "POST",
33770
+ headers: { "Content-Type": "application/json" },
33771
+ // The gateway accepts an empty body; only `limit` is recognised.
33772
+ // Always send a JSON body so the gateway's req.body shape parse
33773
+ // doesn't have to deal with an undefined.
33774
+ body: JSON.stringify(params ?? {})
33775
+ });
33776
+ if (!res.ok) {
33777
+ throw new Error(`Gateway error: ${res.status} ${res.statusText}`);
33778
+ }
33779
+ return await res.json();
32865
33780
  }
32866
33781
  };
32867
33782
  }
@@ -32891,7 +33806,7 @@ var KNOWN_CODES = /* @__PURE__ */ new Set([
32891
33806
  "server_not_configured",
32892
33807
  "content_too_large"
32893
33808
  ]);
32894
- function isRecord(value) {
33809
+ function isRecord2(value) {
32895
33810
  return value !== null && typeof value === "object" && !Array.isArray(value);
32896
33811
  }
32897
33812
  function normalizeCode(value) {
@@ -32902,10 +33817,10 @@ function normalizeCode(value) {
32902
33817
  return KNOWN_CODES.has(code) ? code : null;
32903
33818
  }
32904
33819
  function extractPSErrorBody(body) {
32905
- if (!isRecord(body)) {
33820
+ if (!isRecord2(body)) {
32906
33821
  return null;
32907
33822
  }
32908
- const nested = isRecord(body.error) ? body.error : null;
33823
+ const nested = isRecord2(body.error) ? body.error : null;
32909
33824
  const code = normalizeCode(
32910
33825
  nested?.errorCode ?? nested?.code ?? body.errorCode ?? body.code
32911
33826
  );
@@ -32930,6 +33845,10 @@ async function parsePSError(response) {
32930
33845
  }
32931
33846
  // Annotate the CommonJS export names for ESM import in node:
32932
33847
  0 && (module.exports = {
33848
+ ACCOUNT_PERSONAL_SERVER_REGISTRATION_INTENT,
33849
+ ADD_DATA_TYPES,
33850
+ AccountPersonalServerLiteOwnerBindingError,
33851
+ AccountPersonalServerRegistrationError,
32933
33852
  BUILDER_REGISTRATION_TYPES,
32934
33853
  BlockchainError,
32935
33854
  BrowserPlatformAdapter,
@@ -32940,8 +33859,11 @@ async function parsePSError(response) {
32940
33859
  DataFileEnvelopeSchema,
32941
33860
  DropboxStorage,
32942
33861
  ECIESError,
33862
+ ESCROW_DEPOSIT_ABI,
32943
33863
  ExpiredTokenError,
33864
+ FEE_REGISTRY_ABI,
32944
33865
  FILE_REGISTRATION_TYPES,
33866
+ GENERIC_PAYMENT_TYPES,
32945
33867
  GRANT_REGISTRATION_TYPES,
32946
33868
  GRANT_REVOCATION_TYPES,
32947
33869
  GoogleDriveStorage,
@@ -32952,10 +33874,17 @@ async function parsePSError(response) {
32952
33874
  IpfsStorage,
32953
33875
  MASTER_KEY_MESSAGE,
32954
33876
  MissingAuthError,
33877
+ NATIVE_VANA_ASSET,
32955
33878
  NetworkError,
32956
33879
  NodeECIESProvider,
32957
33880
  NodePlatformAdapter,
32958
33881
  NonceError,
33882
+ OAuthClient,
33883
+ PERSONAL_SERVER_LITE_OWNER_BINDING_PREFIX,
33884
+ PERSONAL_SERVER_LITE_OWNER_BINDING_PURPOSE,
33885
+ PERSONAL_SERVER_LITE_OWNER_BINDING_VERSION,
33886
+ PERSONAL_SERVER_REGISTRATION_DEFAULT_CHAIN_ID,
33887
+ PERSONAL_SERVER_REGISTRATION_DEFAULT_VERIFYING_CONTRACT,
32959
33888
  PKCE_CHALLENGE_PATTERN,
32960
33889
  PKCE_VERIFIER_PATTERN,
32961
33890
  PSError,
@@ -32963,6 +33892,7 @@ async function parsePSError(response) {
32963
33892
  PersonalServerError,
32964
33893
  PinataStorage,
32965
33894
  R2Storage,
33895
+ RECORD_DATA_ACCESS_TYPES,
32966
33896
  ReadOnlyError,
32967
33897
  RelayerError,
32968
33898
  SERVER_REGISTRATION_TYPES,
@@ -32977,6 +33907,12 @@ async function parsePSError(response) {
32977
33907
  VanaError,
32978
33908
  VanaStorage,
32979
33909
  assertValidPkceVerifier,
33910
+ buildDepositNativeRequest,
33911
+ buildDepositTokenRequest,
33912
+ buildPersonalServerLiteOwnerBindingMessage,
33913
+ buildPersonalServerLiteOwnerBindingSignature,
33914
+ buildPersonalServerRegistrationSignature,
33915
+ buildPersonalServerRegistrationTypedData,
32980
33916
  buildWeb3SignedHeader,
32981
33917
  builderRegistrationDomain,
32982
33918
  chains,
@@ -32992,12 +33928,19 @@ async function parsePSError(response) {
32992
33928
  createPlatformAdapterFor,
32993
33929
  createPlatformAdapterSafe,
32994
33930
  createVanaStorageProvider,
33931
+ createViemPersonalServerLiteOwnerBindingSigner,
33932
+ createViemPersonalServerRegistrationSigner,
33933
+ dataRegistryDomain,
32995
33934
  decryptWithPassword,
32996
33935
  deriveMasterKey,
32997
33936
  deriveScopeKey,
32998
33937
  deserializeECIES,
32999
33938
  detectPlatform,
33939
+ encodeDepositNativeData,
33940
+ encodeDepositTokenData,
33000
33941
  encryptWithPassword,
33942
+ escrowContractAddress,
33943
+ escrowPaymentDomain,
33001
33944
  fileRegistrationDomain,
33002
33945
  generatePkceVerifier,
33003
33946
  getAbi,
@@ -33006,6 +33949,8 @@ async function parsePSError(response) {
33006
33949
  getContractAddress,
33007
33950
  getContractController,
33008
33951
  getContractInfo,
33952
+ getFee,
33953
+ getOpFee,
33009
33954
  getPlatformCapabilities,
33010
33955
  getServiceEndpoints,
33011
33956
  grantRegistrationDomain,
@@ -33017,16 +33962,20 @@ async function parsePSError(response) {
33017
33962
  moksha,
33018
33963
  mokshaServices,
33019
33964
  mokshaTestnet,
33020
- parseGrantRegistrationPayload,
33021
33965
  parsePSError,
33022
33966
  parseScope,
33023
33967
  parseWeb3SignedHeader,
33968
+ personalServerRegistrationDomain,
33024
33969
  recoverServerOwner,
33970
+ registerPersonalServerSignature,
33025
33971
  scopeCoveredByGrant,
33026
33972
  scopeMatchesPattern,
33027
33973
  scopeToPathSegments,
33028
33974
  serializeECIES,
33029
33975
  serverRegistrationDomain,
33976
+ signPersonalServerLiteOwnerBinding,
33977
+ signPersonalServerLiteOwnerBindingWithAccountClient,
33978
+ signPersonalServerRegistrationWithAccount,
33030
33979
  vanaMainnet,
33031
33980
  verifyGrantRegistration,
33032
33981
  verifyPkceChallenge,