@canton-network/core-wallet-store-sql 1.13.1 → 1.13.2-backport.3

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/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
2
+ // \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -20,7 +20,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
- //#endregion
24
23
  let _canton_network_core_wallet_auth = require("@canton-network/core-wallet-auth");
25
24
  let kysely = require("kysely");
26
25
  let better_sqlite3 = require("better-sqlite3");
@@ -31,7 +30,7 @@ pg = __toESM(pg, 1);
31
30
  let umzug = require("umzug");
32
31
  let commander = require("commander");
33
32
  let pino = require("pino");
34
- //#region src/schema.ts
33
+ // src/schema.ts
35
34
  const toIdp = (table) => {
36
35
  switch (table.type) {
37
36
  case "oauth":
@@ -240,8 +239,7 @@ const toApiKey = (apiKey) => {
240
239
  lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null
241
240
  };
242
241
  };
243
- //#endregion
244
- //#region \0@oxc-project+runtime@0.142.0/helpers/esm/typeof.js
242
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/typeof.js
245
243
  function _typeof(o) {
246
244
  "@babel/helpers - typeof";
247
245
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -250,8 +248,7 @@ function _typeof(o) {
250
248
  return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
251
249
  }, _typeof(o);
252
250
  }
253
- //#endregion
254
- //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPrimitive.js
251
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/toPrimitive.js
255
252
  function toPrimitive(t, r) {
256
253
  if ("object" != _typeof(t) || !t) return t;
257
254
  var e = t[Symbol.toPrimitive];
@@ -262,14 +259,12 @@ function toPrimitive(t, r) {
262
259
  }
263
260
  return ("string" === r ? String : Number)(t);
264
261
  }
265
- //#endregion
266
- //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPropertyKey.js
262
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/toPropertyKey.js
267
263
  function toPropertyKey(t) {
268
264
  var i = toPrimitive(t, "string");
269
265
  return "symbol" == _typeof(i) ? i : i + "";
270
266
  }
271
- //#endregion
272
- //#region \0@oxc-project+runtime@0.142.0/helpers/esm/defineProperty.js
267
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/defineProperty.js
273
268
  function _defineProperty(e, r, t) {
274
269
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
275
270
  value: t,
@@ -278,8 +273,7 @@ function _defineProperty(e, r, t) {
278
273
  writable: !0
279
274
  }) : e[r] = t, e;
280
275
  }
281
- //#endregion
282
- //#region src/store-sql.ts
276
+ // src/store-sql.ts
283
277
  var StoreSql = class StoreSql {
284
278
  constructor(db, logger, authContext) {
285
279
  this.db = db;
@@ -775,8 +769,7 @@ const connection = (config) => {
775
769
  });
776
770
  }
777
771
  };
778
- //#endregion
779
- //#region src/migrator.ts
772
+ // src/migrator.ts
780
773
  var KyselyStorage = class {
781
774
  constructor(db) {
782
775
  this.db = db;
@@ -826,15 +819,13 @@ const migrator = (db) => {
826
819
  logger: console
827
820
  });
828
821
  };
829
- //#endregion
830
- //#region src/bootstrap.ts
822
+ // src/bootstrap.ts
831
823
  async function bootstrap(db, config, logger) {
832
824
  const store = new StoreSql(db, logger);
833
825
  await Promise.all(config.idps.map((idp) => store.addIdp(idp)));
834
826
  await Promise.all(config.networks.map((network) => store.addNetwork(network)));
835
827
  }
836
- //#endregion
837
- //#region src/cli.ts
828
+ // src/cli.ts
838
829
  const logger = (0, pino.pino)({
839
830
  name: "main",
840
831
  level: "debug"
@@ -876,7 +867,6 @@ function createCLI(config, bootstrapConfig) {
876
867
  });
877
868
  return program;
878
869
  }
879
- //#endregion
880
870
  exports.StoreSql = StoreSql;
881
871
  exports.bootstrap = bootstrap;
882
872
  exports.connection = connection;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["authSchema","PartyLevelRight","UserLevelRight","assertConnected","sql","Database","Kysely","SqliteDialect","CamelCasePlugin","PostgresDialect","Umzug","Command"],"sources":["../src/schema.ts","../src/store-sql.ts","../src/migrator.ts","../src/bootstrap.ts","../src/cli.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { authSchema, Idp, UserId } from '@canton-network/core-wallet-auth'\nimport {\n Wallet,\n Transaction,\n Session,\n Network,\n WalletStatus,\n UpdateWallet,\n PartyLevelRight,\n UserLevelRight,\n MessageRaw,\n ApiKey,\n} from '@canton-network/core-wallet-store'\n\ninterface MigrationTable {\n name: string\n executedAt: string\n}\n\ninterface IdpTable {\n id: string\n type: 'oauth' | 'self_signed'\n issuer: string\n configUrl: string | undefined\n}\n\ninterface NetworkTable {\n id: string\n name: string\n synchronizerId: string | null // retrieved at runtime if null\n description: string\n ledgerApiBaseUrl: string\n identityProviderId: string\n userId: UserId | undefined // global if undefined\n\n auth: string // json stringified\n adminAuth: string | undefined // json stringified\n serviceAccountAuth: string | undefined // json stringified\n}\n\n/**\n * Wallet table schema\n * Primary key on (partyId, networkId, userId)\n * Unique constraint on (networkId, userId) for primary wallet per network per user\n */\ninterface WalletTable {\n primary: number\n partyId: string\n hint: string\n publicKey: string\n namespace: string\n networkId: string\n signingProviderId: string\n userId: UserId\n externalTxId: string | null\n topologyTransactions: string | null\n status: string | null\n disabled: number\n reason: string | null\n}\ninterface UpdateWalletProperties {\n primary?: number\n externalTxId?: string | null\n topologyTransactions?: string | null\n status?: string | null\n disabled?: number\n reason?: string | null\n}\n\ninterface UserPartyRightTable {\n userId: UserId\n networkId: string\n partyId: string\n right: PartyLevelRight\n}\n\ninterface UserRightTable {\n userId: UserId\n networkId: string\n right: UserLevelRight\n}\n\ninterface TransactionTable {\n id: string\n status: string\n commandId: string\n networkId: string\n preparedTransaction: string\n preparedTransactionHash: string\n payload: string | undefined\n origin: string | null\n userId: UserId\n createdAt: string | null\n signedAt: string | null\n externalTxId: string | null\n}\n\ninterface MessageRawTable {\n id: string\n status: string\n partyId: string\n publicKey: string\n message: string\n origin: string | null\n userId: UserId\n networkId: string\n createdAt: string\n signedAt: string | null\n signature: string | null\n}\n\ninterface SessionTable {\n id: string\n origin: string\n network: string\n accessToken: string\n userId: UserId\n}\n\ninterface ApiKeysTable {\n id: string\n digest: string\n name: string\n userId: UserId\n email: string | null\n networkId: string\n createdAt: string\n lastUsedAt: string | null\n}\n\nexport interface DB {\n migrations: MigrationTable\n idps: IdpTable\n networks: NetworkTable\n wallets: WalletTable\n userPartyRights: UserPartyRightTable\n userRights: UserRightTable\n transactions: TransactionTable\n messagesRaw: MessageRawTable\n sessions: SessionTable\n apiKeys: ApiKeysTable\n}\n\nexport const toIdp = (table: IdpTable): Idp => {\n switch (table.type) {\n case 'oauth': {\n if (!table.configUrl) {\n throw new Error(`Missing configUrl for oauth IdP: ${table.id}`)\n }\n\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n configUrl: table.configUrl,\n }\n }\n case 'self_signed':\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n }\n }\n}\n\nexport const fromIdp = (idp: Idp): IdpTable => {\n switch (idp.type) {\n case 'oauth':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: idp.configUrl,\n }\n case 'self_signed':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: undefined,\n }\n }\n}\n\nexport const toNetwork = (table: NetworkTable): Network => {\n return {\n name: table.name,\n id: table.id,\n synchronizerId: table.synchronizerId ?? undefined,\n identityProviderId: table.identityProviderId,\n description: table.description,\n ledgerApi: {\n baseUrl: table.ledgerApiBaseUrl,\n },\n auth: authSchema.parse(\n typeof table.auth === 'string' ? JSON.parse(table.auth) : table.auth\n ),\n adminAuth: table.adminAuth\n ? authSchema.parse(\n typeof table.adminAuth === 'string'\n ? JSON.parse(table.adminAuth)\n : table.adminAuth\n )\n : undefined,\n serviceAccountAuth: table.serviceAccountAuth\n ? authSchema.parse(\n typeof table.serviceAccountAuth === 'string'\n ? JSON.parse(table.serviceAccountAuth)\n : table.serviceAccountAuth\n )\n : undefined,\n }\n}\n\nexport const fromNetwork = (\n network: Network,\n userId?: UserId\n): NetworkTable => {\n return {\n name: network.name,\n id: network.id,\n synchronizerId: network.synchronizerId ?? null,\n description: network.description,\n ledgerApiBaseUrl: network.ledgerApi.baseUrl,\n userId: userId,\n identityProviderId: network.identityProviderId,\n auth: JSON.stringify(network.auth),\n adminAuth: network.adminAuth\n ? JSON.stringify(network.adminAuth)\n : undefined,\n serviceAccountAuth: network.serviceAccountAuth\n ? JSON.stringify(network.serviceAccountAuth)\n : undefined,\n }\n}\n\nexport const toSession = (table: SessionTable): Session => {\n return {\n id: table.id,\n network: table.network,\n origin: table.origin,\n accessToken: table.accessToken,\n userId: table.userId,\n }\n}\n\nexport const fromWallet = (wallet: Wallet, userId: UserId): WalletTable => {\n const { externalTxId, topologyTransactions, rights, ...rest } = wallet\n void rights\n return {\n ...rest,\n primary: wallet.primary ? 1 : 0,\n userId: userId,\n disabled: wallet.disabled !== undefined && wallet.disabled ? 1 : 0,\n reason: wallet.reason ?? null,\n externalTxId: externalTxId && externalTxId !== '' ? externalTxId : null,\n topologyTransactions:\n topologyTransactions && topologyTransactions !== ''\n ? topologyTransactions\n : null,\n }\n}\n\n// only update fields that are explicitly provided to prevent data loss\nexport const toWalletUpdateProperties = (\n params: UpdateWallet\n): UpdateWalletProperties => {\n const {\n status,\n externalTxId,\n topologyTransactions,\n disabled,\n reason,\n primary,\n signingProviderId,\n publicKey,\n namespace,\n } = params\n return {\n ...(status !== undefined && { status }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(topologyTransactions !== undefined && { topologyTransactions }),\n ...(primary !== undefined && { primary: primary ? 1 : 0 }),\n ...(disabled !== undefined && { disabled: disabled ? 1 : 0 }),\n ...(reason !== undefined && { reason }),\n ...(signingProviderId !== undefined && { signingProviderId }),\n ...(publicKey !== undefined && { publicKey }),\n ...(namespace !== undefined && { namespace }),\n }\n}\n\nexport const toWalletStatus = (status?: string | null): WalletStatus => {\n if (status === 'allocated') return 'allocated'\n if (status === 'removed') return 'removed'\n return 'initialized'\n}\n\nexport const toWallet = (table: WalletTable): Wallet => {\n return {\n primary: Boolean(table.primary),\n status: toWalletStatus(table.status),\n partyId: table.partyId,\n hint: table.hint,\n publicKey: table.publicKey,\n namespace: table.namespace,\n networkId: table.networkId,\n signingProviderId: table.signingProviderId,\n disabled: table.disabled === 1,\n userId: table.userId,\n ...(table.externalTxId !== null && {\n externalTxId: table.externalTxId,\n }),\n ...(table.topologyTransactions !== null && {\n topologyTransactions: table.topologyTransactions,\n }),\n ...(table.reason !== null && {\n reason: table.reason,\n }),\n rights: [],\n }\n}\n\nexport const fromPartyRight = (right: string): PartyLevelRight | undefined => {\n if (Object.values(PartyLevelRight).includes(right as PartyLevelRight)) {\n return right as PartyLevelRight\n }\n return undefined\n}\n\nexport const fromUserRight = (right: string): UserLevelRight | undefined => {\n if (Object.values(UserLevelRight).includes(right as UserLevelRight)) {\n return right as UserLevelRight\n }\n return undefined\n}\n\nexport const fromTransaction = (\n transaction: Transaction,\n userId: UserId,\n networkId: string\n): TransactionTable => {\n return {\n ...transaction,\n networkId,\n payload: transaction.payload\n ? JSON.stringify(transaction.payload)\n : undefined,\n origin: transaction.origin || null,\n userId: userId,\n createdAt: transaction.createdAt?.toISOString() || null,\n signedAt: transaction.signedAt?.toISOString() || null,\n externalTxId: transaction.externalTxId ?? null,\n }\n}\n\nexport const toTransaction = (table: TransactionTable): Transaction => {\n const result: Transaction = {\n id: table.id,\n commandId: table.commandId,\n status: table.status as 'pending' | 'signed' | 'executed' | 'failed',\n preparedTransaction: table.preparedTransaction,\n preparedTransactionHash: table.preparedTransactionHash,\n payload: table.payload ? JSON.parse(table.payload) : undefined,\n origin: table.origin || null,\n userId: table.userId,\n networkId: table.networkId,\n }\n\n if (table.createdAt) {\n result.createdAt = new Date(table.createdAt)\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n\n if (table.externalTxId) {\n result.externalTxId = table.externalTxId\n }\n\n return result\n}\n\nexport const fromMessageRaw = (\n message: MessageRaw,\n userId: UserId,\n networkId: string\n): MessageRawTable => {\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n return {\n id: message.id,\n status: message.status,\n userId: message.userId,\n partyId: message.partyId,\n publicKey: message.publicKey,\n message: message.message,\n origin: message.origin || null,\n networkId,\n createdAt: message.createdAt.toISOString(),\n signedAt: message.signedAt?.toISOString() || null,\n signature: message.signature ?? null,\n }\n}\n\nexport const toMessageRaw = (table: MessageRawTable): MessageRaw => {\n const result: MessageRaw = {\n id: table.id,\n status: table.status as MessageRaw['status'],\n userId: table.userId,\n partyId: table.partyId,\n publicKey: table.publicKey,\n message: table.message,\n origin: table.origin || null,\n createdAt: new Date(table.createdAt),\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n if (table.signature) {\n result.signature = table.signature\n }\n\n return result\n}\n\nexport const fromApiKey = (table: ApiKeysTable): ApiKey => {\n return {\n id: table.id,\n digest: table.digest,\n name: table.name,\n userId: table.userId,\n email: table.email,\n networkId: table.networkId,\n createdAt: new Date(table.createdAt),\n lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : undefined,\n }\n}\n\nexport const toApiKey = (apiKey: ApiKey): ApiKeysTable => {\n return {\n id: apiKey.id,\n digest: apiKey.digest,\n name: apiKey.name,\n userId: apiKey.userId,\n email: apiKey.email,\n networkId: apiKey.networkId,\n createdAt: apiKey.createdAt.toISOString(),\n lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null,\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Logger } from 'pino'\nimport {\n AuthContext,\n UserId,\n AuthAware,\n assertConnected,\n Idp,\n} from '@canton-network/core-wallet-auth'\nimport {\n Store as BaseStore,\n Wallet,\n PartyId,\n Session,\n WalletFilter,\n Transaction,\n MessageRaw,\n MessageRawStatusUpdate,\n Network,\n StoreConfig,\n UpdateWallet,\n CurrentNetworkWalletFilter,\n PartyLevelRight,\n TransactionStatusUpdate,\n UserLevelRight,\n ApiKey,\n ListTransactionsOptions,\n WalletUniqueConstraint,\n} from '@canton-network/core-wallet-store'\nimport { CamelCasePlugin, Kysely, PostgresDialect, SqliteDialect } from 'kysely'\nimport Database from 'better-sqlite3'\nimport {\n DB,\n fromIdp,\n fromNetwork,\n fromTransaction,\n fromMessageRaw,\n fromWallet,\n fromPartyRight,\n fromUserRight,\n toWalletUpdateProperties,\n toIdp,\n toNetwork,\n toTransaction,\n toMessageRaw,\n toWallet,\n fromApiKey,\n toApiKey,\n toSession,\n} from './schema.js'\nimport pg from 'pg'\nimport { sql } from 'kysely'\nimport { AccessToken } from '@canton-network/core-types'\n\nexport class StoreSql implements BaseStore, AuthAware<StoreSql> {\n authContext: AuthContext | undefined\n\n constructor(\n private db: Kysely<DB>,\n private logger: Logger,\n authContext?: AuthContext\n ) {\n this.logger = logger.child({ component: 'StoreSql' })\n this.authContext = authContext\n }\n\n withAuthContext(context?: AuthContext): StoreSql {\n return new StoreSql(this.db, this.logger, context)\n }\n\n private assertConnected(): UserId {\n return assertConnected(this.authContext).userId\n }\n\n // Wallet methods\n\n async getAllWallets(filter: WalletFilter = {}): Promise<Array<Wallet>> {\n const userId = this.assertConnected()\n const { networkIds, signingProviderIds } = filter\n const networkIdSet = networkIds ? new Set(networkIds) : null\n const signingProviderIdSet = signingProviderIds\n ? new Set(signingProviderIds)\n : null\n\n const wallets = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const userPartyRights = await this.db\n .selectFrom('userPartyRights')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const rightsByWallet = new Map<string, PartyLevelRight[]>()\n for (const row of userPartyRights) {\n const right = fromPartyRight(row.right)\n if (!right) continue\n const key = `${row.partyId}:${row.networkId}`\n const existing = rightsByWallet.get(key) ?? []\n rightsByWallet.set(key, [...existing, right])\n }\n\n return wallets\n .filter((wallet) => {\n const matchedNetworkIds = networkIdSet\n ? networkIdSet.has(wallet.networkId)\n : true\n const matchedSigningProviderIds = signingProviderIdSet\n ? signingProviderIdSet.has(wallet.signingProviderId)\n : true\n return matchedNetworkIds && matchedSigningProviderIds\n })\n .map((table) => {\n const wallet = toWallet(table)\n const rights = rightsByWallet.get(\n `${table.partyId}:${table.networkId}`\n )\n return {\n ...wallet,\n rights: rights ?? [],\n }\n })\n }\n\n async getWallets(\n filter: CurrentNetworkWalletFilter = {}\n ): Promise<Array<Wallet>> {\n const network = await this.getCurrentNetwork()\n return this.getAllWallets({\n ...filter,\n networkIds: [network.id],\n })\n }\n\n async getWallet(partyId: PartyId): Promise<Wallet | null> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const constraint: WalletUniqueConstraint = {\n partyId,\n networkId: network.id,\n userId,\n }\n\n const row = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where((eb) => eb.and(constraint))\n .executeTakeFirst()\n\n if (!row) return null\n\n const rightRows = await this.db\n .selectFrom('userPartyRights')\n .select('right')\n .where((eb) => eb.and(constraint))\n .execute()\n\n return {\n ...toWallet(row),\n rights: rightRows\n .map(({ right }) => fromPartyRight(right))\n .filter((right) => right !== undefined),\n }\n }\n\n async getPrimaryWallet(): Promise<Wallet | undefined> {\n const wallets = await this.getWallets()\n return wallets.find((w) => w.primary === true)\n }\n\n async setPrimaryWallet(partyId: PartyId): Promise<void> {\n const network = await this.getCurrentNetwork()\n const userId = this.assertConnected()\n const wallets = await this.getWallets()\n\n if (!wallets.some((w) => w.partyId === partyId)) {\n throw new Error(\n `Wallet with partyId \"${partyId}\" not found in network \"${network.id}\"`\n )\n }\n\n const primary = wallets.find((w) => w.primary === true)\n\n await this.db.transaction().execute(async (trx) => {\n if (primary) {\n // Unset primary for current network only\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', primary.partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n // Set new primary for current network\n await trx\n .updateTable('wallets')\n .set({ primary: 1 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async addWallet(wallet: Wallet): Promise<void> {\n this.logger.info('Adding wallet')\n const userId = this.assertConnected()\n\n const wallets = await this.getWallets()\n if (\n wallets.some(\n (w) =>\n w.partyId === wallet.partyId &&\n w.networkId === wallet.networkId\n )\n ) {\n throw new Error(\n `Wallet with partyId \"${wallet.partyId}\" networkId \"${wallet.networkId}\" userId \"${userId}\" already exists`\n )\n }\n\n if (\n !wallet.disabled &&\n wallet.status === 'allocated' &&\n !wallets.some((wallet) => wallet.primary)\n ) {\n // If there is no primary wallet yet, set current one as primary (unless disabled or not allocated).\n // In regular case it would be the first added wallet.\n wallet.primary = true\n }\n\n await this.db.transaction().execute(async (trx) => {\n if (wallet.primary) {\n // If the new wallet is primary, set all others in the same network and for this user to non-primary\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('primary', '=', 1),\n eb('networkId', '=', wallet.networkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n await trx\n .insertInto('wallets')\n .values(fromWallet(wallet, userId))\n .execute()\n\n if (wallet.rights && wallet.rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n wallet.rights.map((right) => ({\n userId,\n networkId: wallet.networkId,\n partyId: wallet.partyId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n async updateWallet(params: UpdateWallet): Promise<void> {\n const { partyId, networkId, rights } = params\n this.logger.info('Updating wallet')\n const userId = this.assertConnected()\n\n const updates = toWalletUpdateProperties(params)\n\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n if (Object.keys(updates).length === 0 && rights === undefined) return\n\n await this.db.transaction().execute(async (trx) => {\n if (Object.keys(updates).length > 0) {\n await trx\n .updateTable('wallets')\n .set(updates)\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n\n if (rights !== undefined) {\n await trx\n .deleteFrom('userPartyRights')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId: targetNetworkId,\n partyId,\n right,\n }))\n )\n .execute()\n }\n }\n })\n }\n\n async removeWallet(partyId: PartyId): Promise<void> {\n this.logger.info('Removing wallet')\n const userId = this.assertConnected()\n\n // Remove wallet from current network only\n const network = await this.getCurrentNetwork()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('wallets')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async getUserRights(networkId?: string): Promise<Array<UserLevelRight>> {\n const userId = this.assertConnected()\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n const rows = await this.db\n .selectFrom('userRights')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', targetNetworkId),\n ])\n )\n .execute()\n\n return rows\n .map((row) => fromUserRight(row.right))\n .filter((right): right is UserLevelRight => right !== undefined)\n }\n\n async setUserRights(\n networkId: string,\n rights: Array<UserLevelRight>\n ): Promise<void> {\n const userId = this.assertConnected()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('userRights')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', networkId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n // Session methods\n async getSession(accessToken: AccessToken): Promise<Session | undefined> {\n const userId = this.assertConnected()\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async listSessions(): Promise<Array<Session>> {\n const userId = this.assertConnected()\n const rows = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n return rows.map((row) => toSession(row))\n }\n\n async setSession(session: Session): Promise<void> {\n const userId = this.assertConnected()\n\n if (!session.origin) {\n throw new Error('Session origin is required')\n }\n\n await this.db.transaction().execute(async (trx) => {\n const deleted = await trx\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('origin', '=', session.origin),\n ])\n )\n .execute()\n this.logger.debug(deleted, 'Deleted old session')\n\n const inserted = await trx\n .insertInto('sessions')\n .values({ ...session, userId })\n .execute()\n\n this.logger.debug(inserted, 'Inserted new session')\n })\n }\n\n async removeSession(accessToken: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .execute()\n }\n\n /**\n * Lists all pending transactions across all users.\n */\n async listAllPendingTransactions(): Promise<Array<Transaction>> {\n const rows = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where('status', '=', 'pending')\n .execute()\n\n return rows.map((row) => toTransaction(row))\n }\n\n // IDP methods\n\n async getIdp(idpId: string): Promise<Idp> {\n const idps = await this.listIdps()\n if (!idps) throw new Error('No IDPs available')\n\n const idp = idps.find((n) => n.id === idpId)\n if (!idp) throw new Error(`IDP \"${idpId}\" not found`)\n return idp\n }\n\n async listIdps(): Promise<Array<Idp>> {\n // All IDPs are global for now -- TO-DO: user-specific IDPs\n const query = this.db.selectFrom('idps').selectAll()\n\n const idps = await query.execute()\n return idps.map((table) => toIdp(table))\n }\n\n async updateIdp(idp: Idp): Promise<void> {\n // todo: check and compare userid of existing idp\n await this.db.transaction().execute(async (trx) => {\n const idpEntry = fromIdp(idp)\n this.logger.info(idpEntry, 'Updating idp table')\n await trx\n .updateTable('idps')\n .set(idpEntry)\n .where('id', '=', idp.id)\n .execute()\n })\n }\n\n async addIdp(idp: Idp): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n const idpAlreadyExists = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idp.id)\n .executeTakeFirst()\n if (idpAlreadyExists) {\n throw new Error(`IDP ${idp.id} already exists`)\n } else {\n await trx.insertInto('idps').values(fromIdp(idp)).execute()\n }\n })\n }\n\n async removeIdp(idpId: string): Promise<void> {\n const networks = await this.listNetworks()\n if (networks.some((n) => n.identityProviderId === idpId)) {\n throw new Error(\n `Cannot delete IDP ${idpId} as it is in use by existing networks`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const idp = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idpId)\n .executeTakeFirst()\n if (!idp) {\n throw new Error(`IDP ${idpId} does not exists`)\n }\n await trx.deleteFrom('idps').where('id', '=', idpId).execute()\n })\n }\n\n // Network methods\n async getNetwork(networkId: string): Promise<Network> {\n const networks = await this.listNetworks()\n if (!networks) throw new Error('No networks available')\n\n const network = networks.find((n) => n.id === networkId)\n if (!network) throw new Error(`Network \"${networkId}\" not found`)\n return network\n }\n\n async getCurrentNetwork(): Promise<Network> {\n const token = this.authContext?.accessToken as AccessToken\n\n if (!token) {\n throw new Error('No access token found in auth context')\n }\n\n const session = await this.getSession(token)\n if (!session) {\n throw new Error('No session found')\n }\n const networkId = session.network\n if (!networkId) {\n throw new Error('No current network set in session')\n }\n\n const networks = await this.listNetworks()\n const network = networks.find((n) => n.id === networkId)\n if (!network) {\n throw new Error(`Network \"${networkId}\" not found`)\n }\n return network\n }\n\n async listNetworks(): Promise<Array<Network>> {\n let query = this.db.selectFrom('networks').selectAll()\n\n if (this.authContext) {\n const userId = this.assertConnected()\n query = query.where((eb) =>\n eb.or([\n eb('userId', 'is', null), // Global networks\n eb('userId', '=', userId), // User-specific networks\n ])\n )\n } else {\n query = query.where('userId', 'is', null) // Only global networks\n }\n\n const networks = await query.execute()\n return networks.map((table) => toNetwork(table))\n }\n\n async updateNetwork(network: Network): Promise<void> {\n // todo: check and compare idpId of existing network\n this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n // we do not set a userId for now and leave all networks global when updating\n const networkEntry = fromNetwork(network, undefined)\n this.logger.info(networkEntry, 'Updating network table')\n await trx\n .updateTable('networks')\n .set(networkEntry)\n .where('id', '=', network.id)\n .execute()\n })\n }\n\n async addNetwork(network: Network): Promise<void> {\n const userId = this.authContext?.userId\n const idps = await this.listIdps()\n const networkIdp = idps.find(\n (idp) => idp.id === network.identityProviderId\n )\n\n if (!networkIdp) {\n throw new Error(\n `Identity provider \"${network.identityProviderId}\" not found`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const networkAlreadyExists = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', network.id)\n .executeTakeFirst()\n if (networkAlreadyExists) {\n throw new Error(`Network ${network.id} already exists`)\n } else {\n await trx\n .insertInto('networks')\n .values(fromNetwork(network, userId))\n .execute()\n }\n })\n }\n\n async removeNetwork(networkId: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n const network = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!network) {\n throw new Error(`Network ${networkId} does not exists`)\n }\n if (network.userId !== userId) {\n throw new Error(\n `Network ${networkId} is not owned by user ${userId}`\n )\n }\n await trx\n .deleteFrom('networks')\n .where('id', '=', networkId)\n .execute()\n })\n }\n\n private mergeTransactionStatusUpdate(\n existing: Transaction,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {}\n ): Transaction {\n const payload = updates.payload ?? existing.payload\n const signedAt = updates.signedAt ?? existing.signedAt\n const externalTxId = updates.externalTxId ?? existing.externalTxId\n\n return {\n id: existing.id,\n commandId: existing.commandId,\n status,\n preparedTransaction: existing.preparedTransaction,\n preparedTransactionHash: existing.preparedTransactionHash,\n origin: existing.origin,\n ...(payload !== undefined && { payload }),\n ...(existing.createdAt !== undefined && {\n createdAt: existing.createdAt,\n }),\n ...(signedAt !== undefined && { signedAt }),\n ...(externalTxId !== undefined && { externalTxId }),\n }\n }\n\n // Transaction methods\n async setTransaction(transaction: Transaction): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n await this.db\n .insertInto('transactions')\n .values(fromTransaction(transaction, userId, network.id))\n .execute()\n }\n\n async setTransactionSigned(\n transactionId: string,\n signedAt: Date,\n externalTxId?: string\n ): Promise<void> {\n await this.setTransactionStatus(transactionId, 'signed', {\n signedAt,\n ...(externalTxId !== undefined && { externalTxId }),\n })\n }\n\n async setTransactionStatus(\n transactionId: string,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {}\n ): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getTransaction(transactionId)\n if (!existing) {\n throw new Error(`Transaction not found with id: ${transactionId}`)\n }\n\n const updated = this.mergeTransactionStatusUpdate(\n existing,\n status,\n updates\n )\n\n await this.db\n .updateTable('transactions')\n .set(fromTransaction(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n async getTransaction(\n transactionId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async getLatestTransactionByCommandId(\n commandId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('commandId', '=', commandId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .executeTakeFirst()\n\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async transactionsCount(): Promise<number> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n const result = await this.db\n .selectFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .select((eb) => eb.fn.count<number>('id').as('count'))\n .executeTakeFirstOrThrow()\n\n return Number(result.count)\n }\n\n async listTransactions(options?: ListTransactionsOptions) {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const { cursor, limit } = options ?? {}\n const lim = limit ? Math.min(limit, 100) : 100\n\n let query = this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .orderBy('id', 'desc')\n .limit(lim + 1)\n\n if (cursor) {\n const split = cursor.split('::')\n const dateString = split[0] === 'null' ? null : split[0]\n const cursorId = split[1]\n\n query = query.where((eb) => {\n if (dateString === null) {\n return eb.and([\n eb('createdAt', 'is', null),\n eb('id', '<', cursorId),\n ])\n }\n\n return eb.or([\n eb('createdAt', '<', dateString),\n eb.and([\n eb('createdAt', '=', dateString),\n eb('id', '<', split[1]),\n ]),\n eb('createdAt', 'is', null),\n ])\n })\n }\n\n const rows = await query.execute()\n const txs = rows.map((r) => toTransaction(r))\n\n const hasNextPage = txs.length > lim\n if (hasNextPage) {\n txs.pop()\n }\n\n if (txs.length === 0) {\n return {\n transactions: [],\n nextCursor: null,\n }\n }\n\n const lastTx = txs[txs.length - 1]\n if (lastTx === undefined) {\n return {\n transactions: txs,\n nextCursor: null,\n }\n }\n\n //handle case for if timestamp is null\n if (lastTx.createdAt) {\n const d = new Date(lastTx.createdAt).toISOString()\n const nextCursor = hasNextPage ? `${d}::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n } else {\n const nextCursor = hasNextPage ? `null::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n }\n }\n\n async removeTransaction(transactionId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n private mergeMessageRawStatusUpdate(\n existing: MessageRaw,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): MessageRaw {\n const signedAt = updates.signedAt ?? existing.signedAt\n const signature = updates.signature ?? existing.signature\n\n return {\n ...existing,\n status,\n ...(signedAt !== undefined && { signedAt }),\n ...(signature !== undefined && { signature }),\n }\n }\n\n // Message signing request methods\n async setMessageRaw(message: MessageRaw): Promise<void> {\n const userId = this.assertConnected()\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n const network = await this.getCurrentNetwork()\n await this.db\n .insertInto('messagesRaw')\n .values(fromMessageRaw(message, userId, network.id))\n .execute()\n }\n\n async setMessageRawStatus(\n messageId: string,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getMessageRaw(messageId)\n if (!existing) {\n throw new Error(`MessageRaw not found with id: ${messageId}`)\n }\n\n const updated = this.mergeMessageRawStatusUpdate(\n existing,\n status,\n updates\n )\n\n await this.db\n .updateTable('messagesRaw')\n .set(fromMessageRaw(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n async getMessageRaw(messageId: string): Promise<MessageRaw | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const message = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return message ? toMessageRaw(message) : undefined\n }\n\n async listMessageRaws(): Promise<Array<MessageRaw>> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const messages = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .execute()\n return messages.map((m) => toMessageRaw(m))\n }\n\n async removeMessageRaw(messageId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('messagesRaw')\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n // API keys\n async addApiKey(apiKey: ApiKey): Promise<void> {\n const userId = this.assertConnected()\n if (apiKey.userId !== userId) {\n throw new Error(\n `ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`\n )\n }\n\n const network = await this.getCurrentNetwork()\n if (apiKey.networkId !== network.id) {\n throw new Error(\n `ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`\n )\n }\n\n await this.db.insertInto('apiKeys').values(toApiKey(apiKey)).execute()\n }\n\n async listApiKeys(): Promise<Array<ApiKey>> {\n const query = this.db\n .selectFrom('apiKeys')\n .selectAll()\n .orderBy('createdAt', 'desc')\n\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const apiKeys = await query\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n\n return apiKeys.map(fromApiKey)\n }\n\n async getApiKey(digest: string): Promise<ApiKey | undefined> {\n const apiKey = await this.db\n .selectFrom('apiKeys')\n .selectAll()\n .where((eb) => eb('digest', '=', digest))\n .executeTakeFirst()\n\n return apiKey ? fromApiKey(apiKey) : undefined\n }\n\n async removeApiKey(apiKeyId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('apiKeys')\n .where((eb) =>\n eb.and([\n eb('id', '=', apiKeyId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n}\n\nexport const connection = (config: StoreConfig) => {\n let database\n switch (config.connection.type) {\n case 'sqlite':\n database = new Database(config.connection.database)\n // normally sqlite3 has foreign_keys = OFF for each connection,\n // but better-sqlite3 uses custom build with compile flag SQLITE_DEFAULT_FOREIGN_KEYS=1,\n // making it ON by default.\n // Set explicitly ON anyway as redundancy\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'postgres':\n return new Kysely<DB>({\n dialect: new PostgresDialect({\n pool: new pg.Pool(config.connection),\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'memory':\n database = new Database(':memory:')\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Umzug, MigrationMeta, UmzugStorage } from 'umzug'\nimport { Kysely } from 'kysely'\nimport { DB } from './schema'\n\nclass KyselyStorage implements UmzugStorage {\n constructor(private db: Kysely<DB>) {}\n\n private async ensureTable() {\n await this.db.schema\n .createTable('migrations')\n .ifNotExists()\n .addColumn('name', 'text', (col) => col.primaryKey())\n .addColumn('executedAt', 'text', (col) => col.notNull())\n .execute()\n }\n\n async executed(): Promise<string[]> {\n await this.ensureTable()\n const rows = await this.db\n .selectFrom('migrations')\n .select('name')\n .execute()\n return rows.map((r) => r.name)\n }\n\n async logMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .insertInto('migrations')\n .values({ name, executedAt: new Date().toISOString() })\n .execute()\n }\n\n async unlogMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .deleteFrom('migrations')\n .where('name', '=', name)\n .execute()\n }\n}\n\nexport const migrator = (db: Kysely<DB>) => {\n const ext = import.meta.url.endsWith('.ts') ? 'ts' : 'js'\n const glob = new URL(`./migrations/*.${ext}`, import.meta.url).pathname\n return new Umzug({\n migrations: {\n glob: glob,\n resolve: ({ name, path, context }) => {\n // Dynamic import for ESM\n return {\n name,\n up: async () => {\n console.log(path)\n const { up } = await import(path!)\n return up(context)\n },\n down: async () => {\n const { down } = await import(path!)\n return down(context)\n },\n }\n },\n },\n context: db,\n storage: new KyselyStorage(db),\n logger: console,\n })\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Kysely } from 'kysely'\nimport { StoreSql } from './store-sql.js'\nimport { BootstrapConfig } from '@canton-network/core-wallet-store'\nimport { Logger } from 'pino'\nimport { DB } from './schema'\n\nexport async function bootstrap(\n db: Kysely<DB>,\n config: BootstrapConfig,\n logger: Logger\n): Promise<void> {\n const store = new StoreSql(db, logger)\n\n // Load all IDPs from config into the store\n await Promise.all(config.idps.map((idp) => store.addIdp(idp)))\n\n // Load all networks from config into the store\n await Promise.all(\n config.networks.map((network) => store.addNetwork(network))\n )\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Command } from 'commander'\nimport { connection } from './store-sql.js'\nimport { migrator } from './migrator.js'\nimport type {\n StoreConfig,\n BootstrapConfig,\n} from '@canton-network/core-wallet-store'\nimport { pino } from 'pino'\nimport { bootstrap } from './bootstrap.js'\n\nconst logger = pino({ name: 'main', level: 'debug' })\n\nexport function createCLI(\n config: StoreConfig,\n bootstrapConfig?: BootstrapConfig\n): Command {\n const program = new Command()\n\n program\n .command('up')\n .description('Run all pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('down')\n .description('Rollback last migration')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.down()\n await db.destroy()\n })\n\n program\n .command('status')\n .description('Show executed and pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n const pending = await umzug.pending()\n\n console.log('Executed migrations:', executed)\n console.log('Pending migrations:', pending)\n\n await db.destroy()\n })\n\n program\n .command('reset')\n .description('Rollback all migrations and reapply them')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n\n // Rollback all executed migrations in reverse order\n for (const migration of executed.reverse()) {\n await umzug.down({ to: migration.name })\n }\n\n // Reapply all migrations\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('bootstrap')\n .description('Bootstrap DB from config')\n .action(async () => {\n if (!bootstrapConfig) {\n throw new Error(\n 'Bootstrap config (idps/networks) is required for the bootstrap command'\n )\n }\n const db = connection(config)\n await bootstrap(db, bootstrapConfig, logger)\n await db.destroy()\n })\n\n return program\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,MAAa,SAAS,UAAyB;CAC3C,QAAQ,MAAM,MAAd;EACI,KAAK;GACD,IAAI,CAAC,MAAM,WACP,MAAM,IAAI,MAAM,oCAAoC,MAAM,IAAI;GAGlE,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;IACd,WAAW,MAAM;GACrB;EAEJ,KAAK,eACD,OAAO;GACH,IAAI,MAAM;GACV,MAAM,MAAM;GACZ,QAAQ,MAAM;EAClB;CACR;AACJ;AAEA,MAAa,WAAW,QAAuB;CAC3C,QAAQ,IAAI,MAAZ;EACI,KAAK,SACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ,IAAI;GACZ,WAAW,IAAI;EACnB;EACJ,KAAK,eACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ,IAAI;GACZ,WAAW,KAAA;EACf;CACR;AACJ;AAEA,MAAa,aAAa,UAAiC;CACvD,OAAO;EACH,MAAM,MAAM;EACZ,IAAI,MAAM;EACV,gBAAgB,MAAM,kBAAkB,KAAA;EACxC,oBAAoB,MAAM;EAC1B,aAAa,MAAM;EACnB,WAAW,EACP,SAAS,MAAM,iBACnB;EACA,MAAMA,iCAAAA,WAAW,MACb,OAAO,MAAM,SAAS,WAAW,KAAK,MAAM,MAAM,IAAI,IAAI,MAAM,IACpE;EACA,WAAW,MAAM,YACXA,iCAAAA,WAAW,MACP,OAAO,MAAM,cAAc,WACrB,KAAK,MAAM,MAAM,SAAS,IAC1B,MAAM,SAChB,IACA,KAAA;EACN,oBAAoB,MAAM,qBACpBA,iCAAAA,WA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MAAM,QAAQ,SAAS,EAAE;EACzB,MAAM,WAAW,MAAM,MAAM,SAAS;EACtC,MAAM,UAAU,MAAM,MAAM,QAAQ;EAEpC,QAAQ,IAAI,wBAAwB,QAAQ;EAC5C,QAAQ,IAAI,uBAAuB,OAAO;EAE1C,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,QACK,QAAQ,OAAO,CAAC,CAChB,YAAY,0CAA0C,CAAC,CACvD,OAAO,YAAY;EAChB,MAAM,KAAK,WAAW,MAAM;EAC5B,MAAM,QAAQ,SAAS,EAAE;EACzB,MAAM,WAAW,MAAM,MAAM,SAAS;EAGtC,KAAK,MAAM,aAAa,SAAS,QAAQ,GACrC,MAAM,MAAM,KAAK,EAAE,IAAI,UAAU,KAAK,CAAC;EAI3C,MAAM,MAAM,GAAG;EACf,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,QACK,QAAQ,WAAW,CAAC,CACpB,YAAY,0BAA0B,CAAC,CACvC,OAAO,YAAY;EAChB,IAAI,CAAC,iBACD,MAAM,IAAI,MACN,wEACJ;EAEJ,MAAM,KAAK,WAAW,MAAM;EAC5B,MAAM,UAAU,IAAI,iBAAiB,MAAM;EAC3C,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,OAAO;AACX"}
1
+ {"version":3,"file":"index.cjs","names":["authSchema","PartyLevelRight","UserLevelRight","assertConnected","sql","Database","Kysely","SqliteDialect","CamelCasePlugin","PostgresDialect","Umzug","Command"],"sources":["../src/schema.ts","../src/store-sql.ts","../src/migrator.ts","../src/bootstrap.ts","../src/cli.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { authSchema, Idp, UserId } from '@canton-network/core-wallet-auth'\nimport {\n Wallet,\n Transaction,\n Session,\n Network,\n WalletStatus,\n UpdateWallet,\n PartyLevelRight,\n UserLevelRight,\n MessageRaw,\n ApiKey,\n} from '@canton-network/core-wallet-store'\n\ninterface MigrationTable {\n name: string\n executedAt: string\n}\n\ninterface IdpTable {\n id: string\n type: 'oauth' | 'self_signed'\n issuer: string\n configUrl: string | undefined\n}\n\ninterface NetworkTable {\n id: string\n name: string\n synchronizerId: string | null // retrieved at runtime if null\n description: string\n ledgerApiBaseUrl: string\n identityProviderId: string\n userId: UserId | undefined // global if undefined\n\n auth: string // json stringified\n adminAuth: string | undefined // json stringified\n serviceAccountAuth: string | undefined // json stringified\n}\n\n/**\n * Wallet table schema\n * Primary key on (partyId, networkId, userId)\n * Unique constraint on (networkId, userId) for primary wallet per network per user\n */\ninterface WalletTable {\n primary: number\n partyId: string\n hint: string\n publicKey: string\n namespace: string\n networkId: string\n signingProviderId: string\n userId: UserId\n externalTxId: string | null\n topologyTransactions: string | null\n status: string | null\n disabled: number\n reason: string | null\n}\ninterface UpdateWalletProperties {\n primary?: number\n externalTxId?: string | null\n topologyTransactions?: string | null\n status?: string | null\n disabled?: number\n reason?: string | null\n}\n\ninterface UserPartyRightTable {\n userId: UserId\n networkId: string\n partyId: string\n right: PartyLevelRight\n}\n\ninterface UserRightTable {\n userId: UserId\n networkId: string\n right: UserLevelRight\n}\n\ninterface TransactionTable {\n id: string\n status: string\n commandId: string\n networkId: string\n preparedTransaction: string\n preparedTransactionHash: string\n payload: string | undefined\n origin: string | null\n userId: UserId\n createdAt: string | null\n signedAt: string | null\n externalTxId: string | null\n}\n\ninterface MessageRawTable {\n id: string\n status: string\n partyId: string\n publicKey: string\n message: string\n origin: string | null\n userId: UserId\n networkId: string\n createdAt: string\n signedAt: string | null\n signature: string | null\n}\n\ninterface SessionTable {\n id: string\n origin: string\n network: string\n accessToken: string\n userId: UserId\n}\n\ninterface ApiKeysTable {\n id: string\n digest: string\n name: string\n userId: UserId\n email: string | null\n networkId: string\n createdAt: string\n lastUsedAt: string | null\n}\n\nexport interface DB {\n migrations: MigrationTable\n idps: IdpTable\n networks: NetworkTable\n wallets: WalletTable\n userPartyRights: UserPartyRightTable\n userRights: UserRightTable\n transactions: TransactionTable\n messagesRaw: MessageRawTable\n sessions: SessionTable\n apiKeys: ApiKeysTable\n}\n\nexport const toIdp = (table: IdpTable): Idp => {\n switch (table.type) {\n case 'oauth': {\n if (!table.configUrl) {\n throw new Error(`Missing configUrl for oauth IdP: ${table.id}`)\n }\n\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n configUrl: table.configUrl,\n }\n }\n case 'self_signed':\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n }\n }\n}\n\nexport const fromIdp = (idp: Idp): IdpTable => {\n switch (idp.type) {\n case 'oauth':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: idp.configUrl,\n }\n case 'self_signed':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: undefined,\n }\n }\n}\n\nexport const toNetwork = (table: NetworkTable): Network => {\n return {\n name: table.name,\n id: table.id,\n synchronizerId: table.synchronizerId ?? undefined,\n identityProviderId: table.identityProviderId,\n description: table.description,\n ledgerApi: {\n baseUrl: table.ledgerApiBaseUrl,\n },\n auth: authSchema.parse(\n typeof table.auth === 'string' ? JSON.parse(table.auth) : table.auth\n ),\n adminAuth: table.adminAuth\n ? authSchema.parse(\n typeof table.adminAuth === 'string'\n ? JSON.parse(table.adminAuth)\n : table.adminAuth\n )\n : undefined,\n serviceAccountAuth: table.serviceAccountAuth\n ? authSchema.parse(\n typeof table.serviceAccountAuth === 'string'\n ? JSON.parse(table.serviceAccountAuth)\n : table.serviceAccountAuth\n )\n : undefined,\n }\n}\n\nexport const fromNetwork = (\n network: Network,\n userId?: UserId\n): NetworkTable => {\n return {\n name: network.name,\n id: network.id,\n synchronizerId: network.synchronizerId ?? null,\n description: network.description,\n ledgerApiBaseUrl: network.ledgerApi.baseUrl,\n userId: userId,\n identityProviderId: network.identityProviderId,\n auth: JSON.stringify(network.auth),\n adminAuth: network.adminAuth\n ? JSON.stringify(network.adminAuth)\n : undefined,\n serviceAccountAuth: network.serviceAccountAuth\n ? JSON.stringify(network.serviceAccountAuth)\n : undefined,\n }\n}\n\nexport const toSession = (table: SessionTable): Session => {\n return {\n id: table.id,\n network: table.network,\n origin: table.origin,\n accessToken: table.accessToken,\n userId: table.userId,\n }\n}\n\nexport const fromWallet = (wallet: Wallet, userId: UserId): WalletTable => {\n const { externalTxId, topologyTransactions, rights, ...rest } = wallet\n void rights\n return {\n ...rest,\n primary: wallet.primary ? 1 : 0,\n userId: userId,\n disabled: wallet.disabled !== undefined && wallet.disabled ? 1 : 0,\n reason: wallet.reason ?? null,\n externalTxId: externalTxId && externalTxId !== '' ? externalTxId : null,\n topologyTransactions:\n topologyTransactions && topologyTransactions !== ''\n ? topologyTransactions\n : null,\n }\n}\n\n// only update fields that are explicitly provided to prevent data loss\nexport const toWalletUpdateProperties = (\n params: UpdateWallet\n): UpdateWalletProperties => {\n const {\n status,\n externalTxId,\n topologyTransactions,\n disabled,\n reason,\n primary,\n signingProviderId,\n publicKey,\n namespace,\n } = params\n return {\n ...(status !== undefined && { status }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(topologyTransactions !== undefined && { topologyTransactions }),\n ...(primary !== undefined && { primary: primary ? 1 : 0 }),\n ...(disabled !== undefined && { disabled: disabled ? 1 : 0 }),\n ...(reason !== undefined && { reason }),\n ...(signingProviderId !== undefined && { signingProviderId }),\n ...(publicKey !== undefined && { publicKey }),\n ...(namespace !== undefined && { namespace }),\n }\n}\n\nexport const toWalletStatus = (status?: string | null): WalletStatus => {\n if (status === 'allocated') return 'allocated'\n if (status === 'removed') return 'removed'\n return 'initialized'\n}\n\nexport const toWallet = (table: WalletTable): Wallet => {\n return {\n primary: Boolean(table.primary),\n status: toWalletStatus(table.status),\n partyId: table.partyId,\n hint: table.hint,\n publicKey: table.publicKey,\n namespace: table.namespace,\n networkId: table.networkId,\n signingProviderId: table.signingProviderId,\n disabled: table.disabled === 1,\n userId: table.userId,\n ...(table.externalTxId !== null && {\n externalTxId: table.externalTxId,\n }),\n ...(table.topologyTransactions !== null && {\n topologyTransactions: table.topologyTransactions,\n }),\n ...(table.reason !== null && {\n reason: table.reason,\n }),\n rights: [],\n }\n}\n\nexport const fromPartyRight = (right: string): PartyLevelRight | undefined => {\n if (Object.values(PartyLevelRight).includes(right as PartyLevelRight)) {\n return right as PartyLevelRight\n }\n return undefined\n}\n\nexport const fromUserRight = (right: string): UserLevelRight | undefined => {\n if (Object.values(UserLevelRight).includes(right as UserLevelRight)) {\n return right as UserLevelRight\n }\n return undefined\n}\n\nexport const fromTransaction = (\n transaction: Transaction,\n userId: UserId,\n networkId: string\n): TransactionTable => {\n return {\n ...transaction,\n networkId,\n payload: transaction.payload\n ? JSON.stringify(transaction.payload)\n : undefined,\n origin: transaction.origin || null,\n userId: userId,\n createdAt: transaction.createdAt?.toISOString() || null,\n signedAt: transaction.signedAt?.toISOString() || null,\n externalTxId: transaction.externalTxId ?? null,\n }\n}\n\nexport const toTransaction = (table: TransactionTable): Transaction => {\n const result: Transaction = {\n id: table.id,\n commandId: table.commandId,\n status: table.status as 'pending' | 'signed' | 'executed' | 'failed',\n preparedTransaction: table.preparedTransaction,\n preparedTransactionHash: table.preparedTransactionHash,\n payload: table.payload ? JSON.parse(table.payload) : undefined,\n origin: table.origin || null,\n userId: table.userId,\n networkId: table.networkId,\n }\n\n if (table.createdAt) {\n result.createdAt = new Date(table.createdAt)\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n\n if (table.externalTxId) {\n result.externalTxId = table.externalTxId\n }\n\n return result\n}\n\nexport const fromMessageRaw = (\n message: MessageRaw,\n userId: UserId,\n networkId: string\n): MessageRawTable => {\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n return {\n id: message.id,\n status: message.status,\n userId: message.userId,\n partyId: message.partyId,\n publicKey: message.publicKey,\n message: message.message,\n origin: message.origin || null,\n networkId,\n createdAt: message.createdAt.toISOString(),\n signedAt: message.signedAt?.toISOString() || null,\n signature: message.signature ?? null,\n }\n}\n\nexport const toMessageRaw = (table: MessageRawTable): MessageRaw => {\n const result: MessageRaw = {\n id: table.id,\n status: table.status as MessageRaw['status'],\n userId: table.userId,\n partyId: table.partyId,\n publicKey: table.publicKey,\n message: table.message,\n origin: table.origin || null,\n createdAt: new Date(table.createdAt),\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n if (table.signature) {\n result.signature = table.signature\n }\n\n return result\n}\n\nexport const fromApiKey = (table: ApiKeysTable): ApiKey => {\n return {\n id: table.id,\n digest: table.digest,\n name: table.name,\n userId: table.userId,\n email: table.email,\n networkId: table.networkId,\n createdAt: new Date(table.createdAt),\n lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : undefined,\n }\n}\n\nexport const toApiKey = (apiKey: ApiKey): ApiKeysTable => {\n return {\n id: apiKey.id,\n digest: apiKey.digest,\n name: apiKey.name,\n userId: apiKey.userId,\n email: apiKey.email,\n networkId: apiKey.networkId,\n createdAt: apiKey.createdAt.toISOString(),\n lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null,\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Logger } from 'pino'\nimport {\n AuthContext,\n UserId,\n AuthAware,\n assertConnected,\n Idp,\n} from '@canton-network/core-wallet-auth'\nimport {\n Store as BaseStore,\n Wallet,\n PartyId,\n Session,\n WalletFilter,\n Transaction,\n MessageRaw,\n MessageRawStatusUpdate,\n Network,\n StoreConfig,\n UpdateWallet,\n CurrentNetworkWalletFilter,\n PartyLevelRight,\n TransactionStatusUpdate,\n UserLevelRight,\n ApiKey,\n ListTransactionsOptions,\n WalletUniqueConstraint,\n} from '@canton-network/core-wallet-store'\nimport { CamelCasePlugin, Kysely, PostgresDialect, SqliteDialect } from 'kysely'\nimport Database from 'better-sqlite3'\nimport {\n DB,\n fromIdp,\n fromNetwork,\n fromTransaction,\n fromMessageRaw,\n fromWallet,\n fromPartyRight,\n fromUserRight,\n toWalletUpdateProperties,\n toIdp,\n toNetwork,\n toTransaction,\n toMessageRaw,\n toWallet,\n fromApiKey,\n toApiKey,\n toSession,\n} from './schema.js'\nimport pg from 'pg'\nimport { sql } from 'kysely'\nimport { AccessToken } from '@canton-network/core-types'\n\nexport class StoreSql implements BaseStore, AuthAware<StoreSql> {\n authContext: AuthContext | undefined\n\n constructor(\n private db: Kysely<DB>,\n private logger: Logger,\n authContext?: AuthContext\n ) {\n this.logger = logger.child({ component: 'StoreSql' })\n this.authContext = authContext\n }\n\n withAuthContext(context?: AuthContext): StoreSql {\n return new StoreSql(this.db, this.logger, context)\n }\n\n private assertConnected(): UserId {\n return assertConnected(this.authContext).userId\n }\n\n // Wallet methods\n\n async getAllWallets(filter: WalletFilter = {}): Promise<Array<Wallet>> {\n const userId = this.assertConnected()\n const { networkIds, signingProviderIds } = filter\n const networkIdSet = networkIds ? new Set(networkIds) : null\n const signingProviderIdSet = signingProviderIds\n ? new Set(signingProviderIds)\n : null\n\n const wallets = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const userPartyRights = await this.db\n .selectFrom('userPartyRights')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const rightsByWallet = new Map<string, PartyLevelRight[]>()\n for (const row of userPartyRights) {\n const right = fromPartyRight(row.right)\n if (!right) continue\n const key = `${row.partyId}:${row.networkId}`\n const existing = rightsByWallet.get(key) ?? []\n rightsByWallet.set(key, [...existing, right])\n }\n\n return wallets\n .filter((wallet) => {\n const matchedNetworkIds = networkIdSet\n ? networkIdSet.has(wallet.networkId)\n : true\n const matchedSigningProviderIds = signingProviderIdSet\n ? signingProviderIdSet.has(wallet.signingProviderId)\n : true\n return matchedNetworkIds && matchedSigningProviderIds\n })\n .map((table) => {\n const wallet = toWallet(table)\n const rights = rightsByWallet.get(\n `${table.partyId}:${table.networkId}`\n )\n return {\n ...wallet,\n rights: rights ?? [],\n }\n })\n }\n\n async getWallets(\n filter: CurrentNetworkWalletFilter = {}\n ): Promise<Array<Wallet>> {\n const network = await this.getCurrentNetwork()\n return this.getAllWallets({\n ...filter,\n networkIds: [network.id],\n })\n }\n\n async getWallet(partyId: PartyId): Promise<Wallet | null> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const constraint: WalletUniqueConstraint = {\n partyId,\n networkId: network.id,\n userId,\n }\n\n const row = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where((eb) => eb.and(constraint))\n .executeTakeFirst()\n\n if (!row) return null\n\n const rightRows = await this.db\n .selectFrom('userPartyRights')\n .select('right')\n .where((eb) => eb.and(constraint))\n .execute()\n\n return {\n ...toWallet(row),\n rights: rightRows\n .map(({ right }) => fromPartyRight(right))\n .filter((right) => right !== undefined),\n }\n }\n\n async getPrimaryWallet(): Promise<Wallet | undefined> {\n const wallets = await this.getWallets()\n return wallets.find((w) => w.primary === true)\n }\n\n async setPrimaryWallet(partyId: PartyId): Promise<void> {\n const network = await this.getCurrentNetwork()\n const userId = this.assertConnected()\n const wallets = await this.getWallets()\n\n if (!wallets.some((w) => w.partyId === partyId)) {\n throw new Error(\n `Wallet with partyId \"${partyId}\" not found in network \"${network.id}\"`\n )\n }\n\n const primary = wallets.find((w) => w.primary === true)\n\n await this.db.transaction().execute(async (trx) => {\n if (primary) {\n // Unset primary for current network only\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', primary.partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n // Set new primary for current network\n await trx\n .updateTable('wallets')\n .set({ primary: 1 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async addWallet(wallet: Wallet): Promise<void> {\n this.logger.info('Adding wallet')\n const userId = this.assertConnected()\n\n const wallets = await this.getWallets()\n if (\n wallets.some(\n (w) =>\n w.partyId === wallet.partyId &&\n w.networkId === wallet.networkId\n )\n ) {\n throw new Error(\n `Wallet with partyId \"${wallet.partyId}\" networkId \"${wallet.networkId}\" userId \"${userId}\" already exists`\n )\n }\n\n if (\n !wallet.disabled &&\n wallet.status === 'allocated' &&\n !wallets.some((wallet) => wallet.primary)\n ) {\n // If there is no primary wallet yet, set current one as primary (unless disabled or not allocated).\n // In regular case it would be the first added wallet.\n wallet.primary = true\n }\n\n await this.db.transaction().execute(async (trx) => {\n if (wallet.primary) {\n // If the new wallet is primary, set all others in the same network and for this user to non-primary\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('primary', '=', 1),\n eb('networkId', '=', wallet.networkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n await trx\n .insertInto('wallets')\n .values(fromWallet(wallet, userId))\n .execute()\n\n if (wallet.rights && wallet.rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n wallet.rights.map((right) => ({\n userId,\n networkId: wallet.networkId,\n partyId: wallet.partyId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n async updateWallet(params: UpdateWallet): Promise<void> {\n const { partyId, networkId, rights } = params\n this.logger.info('Updating wallet')\n const userId = this.assertConnected()\n\n const updates = toWalletUpdateProperties(params)\n\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n if (Object.keys(updates).length === 0 && rights === undefined) return\n\n await this.db.transaction().execute(async (trx) => {\n if (Object.keys(updates).length > 0) {\n await trx\n .updateTable('wallets')\n .set(updates)\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n\n if (rights !== undefined) {\n await trx\n .deleteFrom('userPartyRights')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId: targetNetworkId,\n partyId,\n right,\n }))\n )\n .execute()\n }\n }\n })\n }\n\n async removeWallet(partyId: PartyId): Promise<void> {\n this.logger.info('Removing wallet')\n const userId = this.assertConnected()\n\n // Remove wallet from current network only\n const network = await this.getCurrentNetwork()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('wallets')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async getUserRights(networkId?: string): Promise<Array<UserLevelRight>> {\n const userId = this.assertConnected()\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n const rows = await this.db\n .selectFrom('userRights')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', targetNetworkId),\n ])\n )\n .execute()\n\n return rows\n .map((row) => fromUserRight(row.right))\n .filter((right): right is UserLevelRight => right !== undefined)\n }\n\n async setUserRights(\n networkId: string,\n rights: Array<UserLevelRight>\n ): Promise<void> {\n const userId = this.assertConnected()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('userRights')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', networkId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n // Session methods\n async getSession(accessToken: AccessToken): Promise<Session | undefined> {\n const userId = this.assertConnected()\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async listSessions(): Promise<Array<Session>> {\n const userId = this.assertConnected()\n const rows = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n return rows.map((row) => toSession(row))\n }\n\n async setSession(session: Session): Promise<void> {\n const userId = this.assertConnected()\n\n if (!session.origin) {\n throw new Error('Session origin is required')\n }\n\n await this.db.transaction().execute(async (trx) => {\n const deleted = await trx\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('origin', '=', session.origin),\n ])\n )\n .execute()\n this.logger.debug(deleted, 'Deleted old session')\n\n const inserted = await trx\n .insertInto('sessions')\n .values({ ...session, userId })\n .execute()\n\n this.logger.debug(inserted, 'Inserted new session')\n })\n }\n\n async removeSession(accessToken: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .execute()\n }\n\n /**\n * Lists all pending transactions across all users.\n */\n async listAllPendingTransactions(): Promise<Array<Transaction>> {\n const rows = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where('status', '=', 'pending')\n .execute()\n\n return rows.map((row) => toTransaction(row))\n }\n\n // IDP methods\n\n async getIdp(idpId: string): Promise<Idp> {\n const idps = await this.listIdps()\n if (!idps) throw new Error('No IDPs available')\n\n const idp = idps.find((n) => n.id === idpId)\n if (!idp) throw new Error(`IDP \"${idpId}\" not found`)\n return idp\n }\n\n async listIdps(): Promise<Array<Idp>> {\n // All IDPs are global for now -- TO-DO: user-specific IDPs\n const query = this.db.selectFrom('idps').selectAll()\n\n const idps = await query.execute()\n return idps.map((table) => toIdp(table))\n }\n\n async updateIdp(idp: Idp): Promise<void> {\n // todo: check and compare userid of existing idp\n await this.db.transaction().execute(async (trx) => {\n const idpEntry = fromIdp(idp)\n this.logger.info(idpEntry, 'Updating idp table')\n await trx\n .updateTable('idps')\n .set(idpEntry)\n .where('id', '=', idp.id)\n .execute()\n })\n }\n\n async addIdp(idp: Idp): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n const idpAlreadyExists = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idp.id)\n .executeTakeFirst()\n if (idpAlreadyExists) {\n throw new Error(`IDP ${idp.id} already exists`)\n } else {\n await trx.insertInto('idps').values(fromIdp(idp)).execute()\n }\n })\n }\n\n async removeIdp(idpId: string): Promise<void> {\n const networks = await this.listNetworks()\n if (networks.some((n) => n.identityProviderId === idpId)) {\n throw new Error(\n `Cannot delete IDP ${idpId} as it is in use by existing networks`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const idp = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idpId)\n .executeTakeFirst()\n if (!idp) {\n throw new Error(`IDP ${idpId} does not exists`)\n }\n await trx.deleteFrom('idps').where('id', '=', idpId).execute()\n })\n }\n\n // Network methods\n async getNetwork(networkId: string): Promise<Network> {\n const networks = await this.listNetworks()\n if (!networks) throw new Error('No networks available')\n\n const network = networks.find((n) => n.id === networkId)\n if (!network) throw new Error(`Network \"${networkId}\" not found`)\n return network\n }\n\n async getCurrentNetwork(): Promise<Network> {\n const token = this.authContext?.accessToken as AccessToken\n\n if (!token) {\n throw new Error('No access token found in auth context')\n }\n\n const session = await this.getSession(token)\n if (!session) {\n throw new Error('No session found')\n }\n const networkId = session.network\n if (!networkId) {\n throw new Error('No current network set in session')\n }\n\n const networks = await this.listNetworks()\n const network = networks.find((n) => n.id === networkId)\n if (!network) {\n throw new Error(`Network \"${networkId}\" not found`)\n }\n return network\n }\n\n async listNetworks(): Promise<Array<Network>> {\n let query = this.db.selectFrom('networks').selectAll()\n\n if (this.authContext) {\n const userId = this.assertConnected()\n query = query.where((eb) =>\n eb.or([\n eb('userId', 'is', null), // Global networks\n eb('userId', '=', userId), // User-specific networks\n ])\n )\n } else {\n query = query.where('userId', 'is', null) // Only global networks\n }\n\n const networks = await query.execute()\n return networks.map((table) => toNetwork(table))\n }\n\n async updateNetwork(network: Network): Promise<void> {\n // todo: check and compare idpId of existing network\n this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n // we do not set a userId for now and leave all networks global when updating\n const networkEntry = fromNetwork(network, undefined)\n this.logger.info(networkEntry, 'Updating network table')\n await trx\n .updateTable('networks')\n .set(networkEntry)\n .where('id', '=', network.id)\n .execute()\n })\n }\n\n async addNetwork(network: Network): Promise<void> {\n const userId = this.authContext?.userId\n const idps = await this.listIdps()\n const networkIdp = idps.find(\n (idp) => idp.id === network.identityProviderId\n )\n\n if (!networkIdp) {\n throw new Error(\n `Identity provider \"${network.identityProviderId}\" not found`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const networkAlreadyExists = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', network.id)\n .executeTakeFirst()\n if (networkAlreadyExists) {\n throw new Error(`Network ${network.id} already exists`)\n } else {\n await trx\n .insertInto('networks')\n .values(fromNetwork(network, userId))\n .execute()\n }\n })\n }\n\n async removeNetwork(networkId: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n const network = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!network) {\n throw new Error(`Network ${networkId} does not exists`)\n }\n if (network.userId !== userId) {\n throw new Error(\n `Network ${networkId} is not owned by user ${userId}`\n )\n }\n await trx\n .deleteFrom('networks')\n .where('id', '=', networkId)\n .execute()\n })\n }\n\n private mergeTransactionStatusUpdate(\n existing: Transaction,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {}\n ): Transaction {\n const payload = updates.payload ?? existing.payload\n const signedAt = updates.signedAt ?? existing.signedAt\n const externalTxId = updates.externalTxId ?? existing.externalTxId\n\n return {\n id: existing.id,\n commandId: existing.commandId,\n status,\n preparedTransaction: existing.preparedTransaction,\n preparedTransactionHash: existing.preparedTransactionHash,\n origin: existing.origin,\n ...(payload !== undefined && { payload }),\n ...(existing.createdAt !== undefined && {\n createdAt: existing.createdAt,\n }),\n ...(signedAt !== undefined && { signedAt }),\n ...(externalTxId !== undefined && { externalTxId }),\n }\n }\n\n // Transaction methods\n async setTransaction(transaction: Transaction): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n await this.db\n .insertInto('transactions')\n .values(fromTransaction(transaction, userId, network.id))\n .execute()\n }\n\n async setTransactionSigned(\n transactionId: string,\n signedAt: Date,\n externalTxId?: string\n ): Promise<void> {\n await this.setTransactionStatus(transactionId, 'signed', {\n signedAt,\n ...(externalTxId !== undefined && { externalTxId }),\n })\n }\n\n async setTransactionStatus(\n transactionId: string,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {}\n ): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getTransaction(transactionId)\n if (!existing) {\n throw new Error(`Transaction not found with id: ${transactionId}`)\n }\n\n const updated = this.mergeTransactionStatusUpdate(\n existing,\n status,\n updates\n )\n\n await this.db\n .updateTable('transactions')\n .set(fromTransaction(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n async getTransaction(\n transactionId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async getLatestTransactionByCommandId(\n commandId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('commandId', '=', commandId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .executeTakeFirst()\n\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async transactionsCount(): Promise<number> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n const result = await this.db\n .selectFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .select((eb) => eb.fn.count<number>('id').as('count'))\n .executeTakeFirstOrThrow()\n\n return Number(result.count)\n }\n\n async listTransactions(options?: ListTransactionsOptions) {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const { cursor, limit } = options ?? {}\n const lim = limit ? Math.min(limit, 100) : 100\n\n let query = this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .orderBy('id', 'desc')\n .limit(lim + 1)\n\n if (cursor) {\n const split = cursor.split('::')\n const dateString = split[0] === 'null' ? null : split[0]\n const cursorId = split[1]\n\n query = query.where((eb) => {\n if (dateString === null) {\n return eb.and([\n eb('createdAt', 'is', null),\n eb('id', '<', cursorId),\n ])\n }\n\n return eb.or([\n eb('createdAt', '<', dateString),\n eb.and([\n eb('createdAt', '=', dateString),\n eb('id', '<', split[1]),\n ]),\n eb('createdAt', 'is', null),\n ])\n })\n }\n\n const rows = await query.execute()\n const txs = rows.map((r) => toTransaction(r))\n\n const hasNextPage = txs.length > lim\n if (hasNextPage) {\n txs.pop()\n }\n\n if (txs.length === 0) {\n return {\n transactions: [],\n nextCursor: null,\n }\n }\n\n const lastTx = txs[txs.length - 1]\n if (lastTx === undefined) {\n return {\n transactions: txs,\n nextCursor: null,\n }\n }\n\n //handle case for if timestamp is null\n if (lastTx.createdAt) {\n const d = new Date(lastTx.createdAt).toISOString()\n const nextCursor = hasNextPage ? `${d}::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n } else {\n const nextCursor = hasNextPage ? `null::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n }\n }\n\n async removeTransaction(transactionId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n private mergeMessageRawStatusUpdate(\n existing: MessageRaw,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): MessageRaw {\n const signedAt = updates.signedAt ?? existing.signedAt\n const signature = updates.signature ?? existing.signature\n\n return {\n ...existing,\n status,\n ...(signedAt !== undefined && { signedAt }),\n ...(signature !== undefined && { signature }),\n }\n }\n\n // Message signing request methods\n async setMessageRaw(message: MessageRaw): Promise<void> {\n const userId = this.assertConnected()\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n const network = await this.getCurrentNetwork()\n await this.db\n .insertInto('messagesRaw')\n .values(fromMessageRaw(message, userId, network.id))\n .execute()\n }\n\n async setMessageRawStatus(\n messageId: string,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getMessageRaw(messageId)\n if (!existing) {\n throw new Error(`MessageRaw not found with id: ${messageId}`)\n }\n\n const updated = this.mergeMessageRawStatusUpdate(\n existing,\n status,\n updates\n )\n\n await this.db\n .updateTable('messagesRaw')\n .set(fromMessageRaw(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n async getMessageRaw(messageId: string): Promise<MessageRaw | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const message = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return message ? toMessageRaw(message) : undefined\n }\n\n async listMessageRaws(): Promise<Array<MessageRaw>> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const messages = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .execute()\n return messages.map((m) => toMessageRaw(m))\n }\n\n async removeMessageRaw(messageId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('messagesRaw')\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n // API keys\n async addApiKey(apiKey: ApiKey): Promise<void> {\n const userId = this.assertConnected()\n if (apiKey.userId !== userId) {\n throw new Error(\n `ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`\n )\n }\n\n const network = await this.getCurrentNetwork()\n if (apiKey.networkId !== network.id) {\n throw new Error(\n `ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`\n )\n }\n\n await this.db.insertInto('apiKeys').values(toApiKey(apiKey)).execute()\n }\n\n async listApiKeys(): Promise<Array<ApiKey>> {\n const query = this.db\n .selectFrom('apiKeys')\n .selectAll()\n .orderBy('createdAt', 'desc')\n\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const apiKeys = await query\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n\n return apiKeys.map(fromApiKey)\n }\n\n async getApiKey(digest: string): Promise<ApiKey | undefined> {\n const apiKey = await this.db\n .selectFrom('apiKeys')\n .selectAll()\n .where((eb) => eb('digest', '=', digest))\n .executeTakeFirst()\n\n return apiKey ? fromApiKey(apiKey) : undefined\n }\n\n async removeApiKey(apiKeyId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('apiKeys')\n .where((eb) =>\n eb.and([\n eb('id', '=', apiKeyId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n}\n\nexport const connection = (config: StoreConfig) => {\n let database\n switch (config.connection.type) {\n case 'sqlite':\n database = new Database(config.connection.database)\n // normally sqlite3 has foreign_keys = OFF for each connection,\n // but better-sqlite3 uses custom build with compile flag SQLITE_DEFAULT_FOREIGN_KEYS=1,\n // making it ON by default.\n // Set explicitly ON anyway as redundancy\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'postgres':\n return new Kysely<DB>({\n dialect: new PostgresDialect({\n pool: new pg.Pool(config.connection),\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'memory':\n database = new Database(':memory:')\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Umzug, MigrationMeta, UmzugStorage } from 'umzug'\nimport { Kysely } from 'kysely'\nimport { DB } from './schema'\n\nclass KyselyStorage implements UmzugStorage {\n constructor(private db: Kysely<DB>) {}\n\n private async ensureTable() {\n await this.db.schema\n .createTable('migrations')\n .ifNotExists()\n .addColumn('name', 'text', (col) => col.primaryKey())\n .addColumn('executedAt', 'text', (col) => col.notNull())\n .execute()\n }\n\n async executed(): Promise<string[]> {\n await this.ensureTable()\n const rows = await this.db\n .selectFrom('migrations')\n .select('name')\n .execute()\n return rows.map((r) => r.name)\n }\n\n async logMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .insertInto('migrations')\n .values({ name, executedAt: new Date().toISOString() })\n .execute()\n }\n\n async unlogMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .deleteFrom('migrations')\n .where('name', '=', name)\n .execute()\n }\n}\n\nexport const migrator = (db: Kysely<DB>) => {\n const ext = import.meta.url.endsWith('.ts') ? 'ts' : 'js'\n const glob = new URL(`./migrations/*.${ext}`, import.meta.url).pathname\n return new Umzug({\n migrations: {\n glob: glob,\n resolve: ({ name, path, context }) => {\n // Dynamic import for ESM\n return {\n name,\n up: async () => {\n console.log(path)\n const { up } = await import(path!)\n return up(context)\n },\n down: async () => {\n const { down } = await import(path!)\n return down(context)\n },\n }\n },\n },\n context: db,\n storage: new KyselyStorage(db),\n logger: console,\n })\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Kysely } from 'kysely'\nimport { StoreSql } from './store-sql.js'\nimport { BootstrapConfig } from '@canton-network/core-wallet-store'\nimport { Logger } from 'pino'\nimport { DB } from './schema'\n\nexport async function bootstrap(\n db: Kysely<DB>,\n config: BootstrapConfig,\n logger: Logger\n): Promise<void> {\n const store = new StoreSql(db, logger)\n\n // Load all IDPs from config into the store\n await Promise.all(config.idps.map((idp) => store.addIdp(idp)))\n\n // Load all networks from config into the store\n await Promise.all(\n config.networks.map((network) => store.addNetwork(network))\n )\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Command } from 'commander'\nimport { connection } from './store-sql.js'\nimport { migrator } from './migrator.js'\nimport type {\n StoreConfig,\n BootstrapConfig,\n} from '@canton-network/core-wallet-store'\nimport { pino } from 'pino'\nimport { bootstrap } from './bootstrap.js'\n\nconst logger = pino({ name: 'main', level: 'debug' })\n\nexport function createCLI(\n config: StoreConfig,\n bootstrapConfig?: BootstrapConfig\n): Command {\n const program = new Command()\n\n program\n .command('up')\n .description('Run all pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('down')\n .description('Rollback last migration')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.down()\n await db.destroy()\n })\n\n program\n .command('status')\n .description('Show executed and pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n const pending = await umzug.pending()\n\n console.log('Executed migrations:', executed)\n console.log('Pending migrations:', pending)\n\n await db.destroy()\n })\n\n program\n .command('reset')\n .description('Rollback all migrations and reapply them')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n\n // Rollback all executed migrations in reverse order\n for (const migration of executed.reverse()) {\n await umzug.down({ to: migration.name })\n }\n\n // Reapply all migrations\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('bootstrap')\n .description('Bootstrap DB from config')\n .action(async () => {\n if (!bootstrapConfig) {\n throw new Error(\n 'Bootstrap config (idps/networks) is required for the bootstrap command'\n )\n }\n const db = connection(config)\n await bootstrap(db, bootstrapConfig, logger)\n await db.destroy()\n })\n\n return program\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,MAAa,SAAS,UAAyB;CAC3C,QAAQ,MAAM,MAAd;EACI,KAAK;GACD,IAAI,CAAC,MAAM,WACP,MAAM,IAAI,MAAM,oCAAoC,MAAM,IAAI;GAGlE,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;IACd,WAAW,MAAM;GACrB;EAEJ,KAAK,eACD,OAAO;GACH,IAAI,MAAM;GACV,MAAM,MAAM;GACZ,QAAQ,MAAM;EAClB;CACR;AACJ;AAEA,MAAa,WAAW,QAAuB;CAC3C,QAAQ,IAAI,MAAZ;EACI,KAAK,SACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ,IAAI;GACZ,WAAW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,MAAM;EAC5B,MAAM,UAAU,IAAI,iBAAiB,MAAM;EAC3C,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,OAAO;AACX"}
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import pg from "pg";
6
6
  import { Umzug } from "umzug";
7
7
  import { Command } from "commander";
8
8
  import { pino } from "pino";
9
- //#region src/schema.ts
9
+ // src/schema.ts
10
10
  const toIdp = (table) => {
11
11
  switch (table.type) {
12
12
  case "oauth":
@@ -215,8 +215,7 @@ const toApiKey = (apiKey) => {
215
215
  lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null
216
216
  };
217
217
  };
218
- //#endregion
219
- //#region \0@oxc-project+runtime@0.142.0/helpers/esm/typeof.js
218
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/typeof.js
220
219
  function _typeof(o) {
221
220
  "@babel/helpers - typeof";
222
221
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -225,8 +224,7 @@ function _typeof(o) {
225
224
  return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
226
225
  }, _typeof(o);
227
226
  }
228
- //#endregion
229
- //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPrimitive.js
227
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/toPrimitive.js
230
228
  function toPrimitive(t, r) {
231
229
  if ("object" != _typeof(t) || !t) return t;
232
230
  var e = t[Symbol.toPrimitive];
@@ -237,14 +235,12 @@ function toPrimitive(t, r) {
237
235
  }
238
236
  return ("string" === r ? String : Number)(t);
239
237
  }
240
- //#endregion
241
- //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPropertyKey.js
238
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/toPropertyKey.js
242
239
  function toPropertyKey(t) {
243
240
  var i = toPrimitive(t, "string");
244
241
  return "symbol" == _typeof(i) ? i : i + "";
245
242
  }
246
- //#endregion
247
- //#region \0@oxc-project+runtime@0.142.0/helpers/esm/defineProperty.js
243
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/defineProperty.js
248
244
  function _defineProperty(e, r, t) {
249
245
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
250
246
  value: t,
@@ -253,8 +249,7 @@ function _defineProperty(e, r, t) {
253
249
  writable: !0
254
250
  }) : e[r] = t, e;
255
251
  }
256
- //#endregion
257
- //#region src/store-sql.ts
252
+ // src/store-sql.ts
258
253
  var StoreSql = class StoreSql {
259
254
  constructor(db, logger, authContext) {
260
255
  this.db = db;
@@ -750,8 +745,7 @@ const connection = (config) => {
750
745
  });
751
746
  }
752
747
  };
753
- //#endregion
754
- //#region src/migrator.ts
748
+ // src/migrator.ts
755
749
  var KyselyStorage = class {
756
750
  constructor(db) {
757
751
  this.db = db;
@@ -801,15 +795,13 @@ const migrator = (db) => {
801
795
  logger: console
802
796
  });
803
797
  };
804
- //#endregion
805
- //#region src/bootstrap.ts
798
+ // src/bootstrap.ts
806
799
  async function bootstrap(db, config, logger) {
807
800
  const store = new StoreSql(db, logger);
808
801
  await Promise.all(config.idps.map((idp) => store.addIdp(idp)));
809
802
  await Promise.all(config.networks.map((network) => store.addNetwork(network)));
810
803
  }
811
- //#endregion
812
- //#region src/cli.ts
804
+ // src/cli.ts
813
805
  const logger = pino({
814
806
  name: "main",
815
807
  level: "debug"
@@ -851,7 +843,6 @@ function createCLI(config, bootstrapConfig) {
851
843
  });
852
844
  return program;
853
845
  }
854
- //#endregion
855
846
  export { StoreSql, bootstrap, connection, createCLI, migrator };
856
847
 
857
848
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/schema.ts","../src/store-sql.ts","../src/migrator.ts","../src/bootstrap.ts","../src/cli.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { authSchema, Idp, UserId } from '@canton-network/core-wallet-auth'\nimport {\n Wallet,\n Transaction,\n Session,\n Network,\n WalletStatus,\n UpdateWallet,\n PartyLevelRight,\n UserLevelRight,\n MessageRaw,\n ApiKey,\n} from '@canton-network/core-wallet-store'\n\ninterface MigrationTable {\n name: string\n executedAt: string\n}\n\ninterface IdpTable {\n id: string\n type: 'oauth' | 'self_signed'\n issuer: string\n configUrl: string | undefined\n}\n\ninterface NetworkTable {\n id: string\n name: string\n synchronizerId: string | null // retrieved at runtime if null\n description: string\n ledgerApiBaseUrl: string\n identityProviderId: string\n userId: UserId | undefined // global if undefined\n\n auth: string // json stringified\n adminAuth: string | undefined // json stringified\n serviceAccountAuth: string | undefined // json stringified\n}\n\n/**\n * Wallet table schema\n * Primary key on (partyId, networkId, userId)\n * Unique constraint on (networkId, userId) for primary wallet per network per user\n */\ninterface WalletTable {\n primary: number\n partyId: string\n hint: string\n publicKey: string\n namespace: string\n networkId: string\n signingProviderId: string\n userId: UserId\n externalTxId: string | null\n topologyTransactions: string | null\n status: string | null\n disabled: number\n reason: string | null\n}\ninterface UpdateWalletProperties {\n primary?: number\n externalTxId?: string | null\n topologyTransactions?: string | null\n status?: string | null\n disabled?: number\n reason?: string | null\n}\n\ninterface UserPartyRightTable {\n userId: UserId\n networkId: string\n partyId: string\n right: PartyLevelRight\n}\n\ninterface UserRightTable {\n userId: UserId\n networkId: string\n right: UserLevelRight\n}\n\ninterface TransactionTable {\n id: string\n status: string\n commandId: string\n networkId: string\n preparedTransaction: string\n preparedTransactionHash: string\n payload: string | undefined\n origin: string | null\n userId: UserId\n createdAt: string | null\n signedAt: string | null\n externalTxId: string | null\n}\n\ninterface MessageRawTable {\n id: string\n status: string\n partyId: string\n publicKey: string\n message: string\n origin: string | null\n userId: UserId\n networkId: string\n createdAt: string\n signedAt: string | null\n signature: string | null\n}\n\ninterface SessionTable {\n id: string\n origin: string\n network: string\n accessToken: string\n userId: UserId\n}\n\ninterface ApiKeysTable {\n id: string\n digest: string\n name: string\n userId: UserId\n email: string | null\n networkId: string\n createdAt: string\n lastUsedAt: string | null\n}\n\nexport interface DB {\n migrations: MigrationTable\n idps: IdpTable\n networks: NetworkTable\n wallets: WalletTable\n userPartyRights: UserPartyRightTable\n userRights: UserRightTable\n transactions: TransactionTable\n messagesRaw: MessageRawTable\n sessions: SessionTable\n apiKeys: ApiKeysTable\n}\n\nexport const toIdp = (table: IdpTable): Idp => {\n switch (table.type) {\n case 'oauth': {\n if (!table.configUrl) {\n throw new Error(`Missing configUrl for oauth IdP: ${table.id}`)\n }\n\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n configUrl: table.configUrl,\n }\n }\n case 'self_signed':\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n }\n }\n}\n\nexport const fromIdp = (idp: Idp): IdpTable => {\n switch (idp.type) {\n case 'oauth':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: idp.configUrl,\n }\n case 'self_signed':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: undefined,\n }\n }\n}\n\nexport const toNetwork = (table: NetworkTable): Network => {\n return {\n name: table.name,\n id: table.id,\n synchronizerId: table.synchronizerId ?? undefined,\n identityProviderId: table.identityProviderId,\n description: table.description,\n ledgerApi: {\n baseUrl: table.ledgerApiBaseUrl,\n },\n auth: authSchema.parse(\n typeof table.auth === 'string' ? JSON.parse(table.auth) : table.auth\n ),\n adminAuth: table.adminAuth\n ? authSchema.parse(\n typeof table.adminAuth === 'string'\n ? JSON.parse(table.adminAuth)\n : table.adminAuth\n )\n : undefined,\n serviceAccountAuth: table.serviceAccountAuth\n ? authSchema.parse(\n typeof table.serviceAccountAuth === 'string'\n ? JSON.parse(table.serviceAccountAuth)\n : table.serviceAccountAuth\n )\n : undefined,\n }\n}\n\nexport const fromNetwork = (\n network: Network,\n userId?: UserId\n): NetworkTable => {\n return {\n name: network.name,\n id: network.id,\n synchronizerId: network.synchronizerId ?? null,\n description: network.description,\n ledgerApiBaseUrl: network.ledgerApi.baseUrl,\n userId: userId,\n identityProviderId: network.identityProviderId,\n auth: JSON.stringify(network.auth),\n adminAuth: network.adminAuth\n ? JSON.stringify(network.adminAuth)\n : undefined,\n serviceAccountAuth: network.serviceAccountAuth\n ? JSON.stringify(network.serviceAccountAuth)\n : undefined,\n }\n}\n\nexport const toSession = (table: SessionTable): Session => {\n return {\n id: table.id,\n network: table.network,\n origin: table.origin,\n accessToken: table.accessToken,\n userId: table.userId,\n }\n}\n\nexport const fromWallet = (wallet: Wallet, userId: UserId): WalletTable => {\n const { externalTxId, topologyTransactions, rights, ...rest } = wallet\n void rights\n return {\n ...rest,\n primary: wallet.primary ? 1 : 0,\n userId: userId,\n disabled: wallet.disabled !== undefined && wallet.disabled ? 1 : 0,\n reason: wallet.reason ?? null,\n externalTxId: externalTxId && externalTxId !== '' ? externalTxId : null,\n topologyTransactions:\n topologyTransactions && topologyTransactions !== ''\n ? topologyTransactions\n : null,\n }\n}\n\n// only update fields that are explicitly provided to prevent data loss\nexport const toWalletUpdateProperties = (\n params: UpdateWallet\n): UpdateWalletProperties => {\n const {\n status,\n externalTxId,\n topologyTransactions,\n disabled,\n reason,\n primary,\n signingProviderId,\n publicKey,\n namespace,\n } = params\n return {\n ...(status !== undefined && { status }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(topologyTransactions !== undefined && { topologyTransactions }),\n ...(primary !== undefined && { primary: primary ? 1 : 0 }),\n ...(disabled !== undefined && { disabled: disabled ? 1 : 0 }),\n ...(reason !== undefined && { reason }),\n ...(signingProviderId !== undefined && { signingProviderId }),\n ...(publicKey !== undefined && { publicKey }),\n ...(namespace !== undefined && { namespace }),\n }\n}\n\nexport const toWalletStatus = (status?: string | null): WalletStatus => {\n if (status === 'allocated') return 'allocated'\n if (status === 'removed') return 'removed'\n return 'initialized'\n}\n\nexport const toWallet = (table: WalletTable): Wallet => {\n return {\n primary: Boolean(table.primary),\n status: toWalletStatus(table.status),\n partyId: table.partyId,\n hint: table.hint,\n publicKey: table.publicKey,\n namespace: table.namespace,\n networkId: table.networkId,\n signingProviderId: table.signingProviderId,\n disabled: table.disabled === 1,\n userId: table.userId,\n ...(table.externalTxId !== null && {\n externalTxId: table.externalTxId,\n }),\n ...(table.topologyTransactions !== null && {\n topologyTransactions: table.topologyTransactions,\n }),\n ...(table.reason !== null && {\n reason: table.reason,\n }),\n rights: [],\n }\n}\n\nexport const fromPartyRight = (right: string): PartyLevelRight | undefined => {\n if (Object.values(PartyLevelRight).includes(right as PartyLevelRight)) {\n return right as PartyLevelRight\n }\n return undefined\n}\n\nexport const fromUserRight = (right: string): UserLevelRight | undefined => {\n if (Object.values(UserLevelRight).includes(right as UserLevelRight)) {\n return right as UserLevelRight\n }\n return undefined\n}\n\nexport const fromTransaction = (\n transaction: Transaction,\n userId: UserId,\n networkId: string\n): TransactionTable => {\n return {\n ...transaction,\n networkId,\n payload: transaction.payload\n ? JSON.stringify(transaction.payload)\n : undefined,\n origin: transaction.origin || null,\n userId: userId,\n createdAt: transaction.createdAt?.toISOString() || null,\n signedAt: transaction.signedAt?.toISOString() || null,\n externalTxId: transaction.externalTxId ?? null,\n }\n}\n\nexport const toTransaction = (table: TransactionTable): Transaction => {\n const result: Transaction = {\n id: table.id,\n commandId: table.commandId,\n status: table.status as 'pending' | 'signed' | 'executed' | 'failed',\n preparedTransaction: table.preparedTransaction,\n preparedTransactionHash: table.preparedTransactionHash,\n payload: table.payload ? JSON.parse(table.payload) : undefined,\n origin: table.origin || null,\n userId: table.userId,\n networkId: table.networkId,\n }\n\n if (table.createdAt) {\n result.createdAt = new Date(table.createdAt)\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n\n if (table.externalTxId) {\n result.externalTxId = table.externalTxId\n }\n\n return result\n}\n\nexport const fromMessageRaw = (\n message: MessageRaw,\n userId: UserId,\n networkId: string\n): MessageRawTable => {\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n return {\n id: message.id,\n status: message.status,\n userId: message.userId,\n partyId: message.partyId,\n publicKey: message.publicKey,\n message: message.message,\n origin: message.origin || null,\n networkId,\n createdAt: message.createdAt.toISOString(),\n signedAt: message.signedAt?.toISOString() || null,\n signature: message.signature ?? null,\n }\n}\n\nexport const toMessageRaw = (table: MessageRawTable): MessageRaw => {\n const result: MessageRaw = {\n id: table.id,\n status: table.status as MessageRaw['status'],\n userId: table.userId,\n partyId: table.partyId,\n publicKey: table.publicKey,\n message: table.message,\n origin: table.origin || null,\n createdAt: new Date(table.createdAt),\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n if (table.signature) {\n result.signature = table.signature\n }\n\n return result\n}\n\nexport const fromApiKey = (table: ApiKeysTable): ApiKey => {\n return {\n id: table.id,\n digest: table.digest,\n name: table.name,\n userId: table.userId,\n email: table.email,\n networkId: table.networkId,\n createdAt: new Date(table.createdAt),\n lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : undefined,\n }\n}\n\nexport const toApiKey = (apiKey: ApiKey): ApiKeysTable => {\n return {\n id: apiKey.id,\n digest: apiKey.digest,\n name: apiKey.name,\n userId: apiKey.userId,\n email: apiKey.email,\n networkId: apiKey.networkId,\n createdAt: apiKey.createdAt.toISOString(),\n lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null,\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Logger } from 'pino'\nimport {\n AuthContext,\n UserId,\n AuthAware,\n assertConnected,\n Idp,\n} from '@canton-network/core-wallet-auth'\nimport {\n Store as BaseStore,\n Wallet,\n PartyId,\n Session,\n WalletFilter,\n Transaction,\n MessageRaw,\n MessageRawStatusUpdate,\n Network,\n StoreConfig,\n UpdateWallet,\n CurrentNetworkWalletFilter,\n PartyLevelRight,\n TransactionStatusUpdate,\n UserLevelRight,\n ApiKey,\n ListTransactionsOptions,\n WalletUniqueConstraint,\n} from '@canton-network/core-wallet-store'\nimport { CamelCasePlugin, Kysely, PostgresDialect, SqliteDialect } from 'kysely'\nimport Database from 'better-sqlite3'\nimport {\n DB,\n fromIdp,\n fromNetwork,\n fromTransaction,\n fromMessageRaw,\n fromWallet,\n fromPartyRight,\n fromUserRight,\n toWalletUpdateProperties,\n toIdp,\n toNetwork,\n toTransaction,\n toMessageRaw,\n toWallet,\n fromApiKey,\n toApiKey,\n toSession,\n} from './schema.js'\nimport pg from 'pg'\nimport { sql } from 'kysely'\nimport { AccessToken } from '@canton-network/core-types'\n\nexport class StoreSql implements BaseStore, AuthAware<StoreSql> {\n authContext: AuthContext | undefined\n\n constructor(\n private db: Kysely<DB>,\n private logger: Logger,\n authContext?: AuthContext\n ) {\n this.logger = logger.child({ component: 'StoreSql' })\n this.authContext = authContext\n }\n\n withAuthContext(context?: AuthContext): StoreSql {\n return new StoreSql(this.db, this.logger, context)\n }\n\n private assertConnected(): UserId {\n return assertConnected(this.authContext).userId\n }\n\n // Wallet methods\n\n async getAllWallets(filter: WalletFilter = {}): Promise<Array<Wallet>> {\n const userId = this.assertConnected()\n const { networkIds, signingProviderIds } = filter\n const networkIdSet = networkIds ? new Set(networkIds) : null\n const signingProviderIdSet = signingProviderIds\n ? new Set(signingProviderIds)\n : null\n\n const wallets = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const userPartyRights = await this.db\n .selectFrom('userPartyRights')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const rightsByWallet = new Map<string, PartyLevelRight[]>()\n for (const row of userPartyRights) {\n const right = fromPartyRight(row.right)\n if (!right) continue\n const key = `${row.partyId}:${row.networkId}`\n const existing = rightsByWallet.get(key) ?? []\n rightsByWallet.set(key, [...existing, right])\n }\n\n return wallets\n .filter((wallet) => {\n const matchedNetworkIds = networkIdSet\n ? networkIdSet.has(wallet.networkId)\n : true\n const matchedSigningProviderIds = signingProviderIdSet\n ? signingProviderIdSet.has(wallet.signingProviderId)\n : true\n return matchedNetworkIds && matchedSigningProviderIds\n })\n .map((table) => {\n const wallet = toWallet(table)\n const rights = rightsByWallet.get(\n `${table.partyId}:${table.networkId}`\n )\n return {\n ...wallet,\n rights: rights ?? [],\n }\n })\n }\n\n async getWallets(\n filter: CurrentNetworkWalletFilter = {}\n ): Promise<Array<Wallet>> {\n const network = await this.getCurrentNetwork()\n return this.getAllWallets({\n ...filter,\n networkIds: [network.id],\n })\n }\n\n async getWallet(partyId: PartyId): Promise<Wallet | null> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const constraint: WalletUniqueConstraint = {\n partyId,\n networkId: network.id,\n userId,\n }\n\n const row = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where((eb) => eb.and(constraint))\n .executeTakeFirst()\n\n if (!row) return null\n\n const rightRows = await this.db\n .selectFrom('userPartyRights')\n .select('right')\n .where((eb) => eb.and(constraint))\n .execute()\n\n return {\n ...toWallet(row),\n rights: rightRows\n .map(({ right }) => fromPartyRight(right))\n .filter((right) => right !== undefined),\n }\n }\n\n async getPrimaryWallet(): Promise<Wallet | undefined> {\n const wallets = await this.getWallets()\n return wallets.find((w) => w.primary === true)\n }\n\n async setPrimaryWallet(partyId: PartyId): Promise<void> {\n const network = await this.getCurrentNetwork()\n const userId = this.assertConnected()\n const wallets = await this.getWallets()\n\n if (!wallets.some((w) => w.partyId === partyId)) {\n throw new Error(\n `Wallet with partyId \"${partyId}\" not found in network \"${network.id}\"`\n )\n }\n\n const primary = wallets.find((w) => w.primary === true)\n\n await this.db.transaction().execute(async (trx) => {\n if (primary) {\n // Unset primary for current network only\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', primary.partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n // Set new primary for current network\n await trx\n .updateTable('wallets')\n .set({ primary: 1 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async addWallet(wallet: Wallet): Promise<void> {\n this.logger.info('Adding wallet')\n const userId = this.assertConnected()\n\n const wallets = await this.getWallets()\n if (\n wallets.some(\n (w) =>\n w.partyId === wallet.partyId &&\n w.networkId === wallet.networkId\n )\n ) {\n throw new Error(\n `Wallet with partyId \"${wallet.partyId}\" networkId \"${wallet.networkId}\" userId \"${userId}\" already exists`\n )\n }\n\n if (\n !wallet.disabled &&\n wallet.status === 'allocated' &&\n !wallets.some((wallet) => wallet.primary)\n ) {\n // If there is no primary wallet yet, set current one as primary (unless disabled or not allocated).\n // In regular case it would be the first added wallet.\n wallet.primary = true\n }\n\n await this.db.transaction().execute(async (trx) => {\n if (wallet.primary) {\n // If the new wallet is primary, set all others in the same network and for this user to non-primary\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('primary', '=', 1),\n eb('networkId', '=', wallet.networkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n await trx\n .insertInto('wallets')\n .values(fromWallet(wallet, userId))\n .execute()\n\n if (wallet.rights && wallet.rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n wallet.rights.map((right) => ({\n userId,\n networkId: wallet.networkId,\n partyId: wallet.partyId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n async updateWallet(params: UpdateWallet): Promise<void> {\n const { partyId, networkId, rights } = params\n this.logger.info('Updating wallet')\n const userId = this.assertConnected()\n\n const updates = toWalletUpdateProperties(params)\n\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n if (Object.keys(updates).length === 0 && rights === undefined) return\n\n await this.db.transaction().execute(async (trx) => {\n if (Object.keys(updates).length > 0) {\n await trx\n .updateTable('wallets')\n .set(updates)\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n\n if (rights !== undefined) {\n await trx\n .deleteFrom('userPartyRights')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId: targetNetworkId,\n partyId,\n right,\n }))\n )\n .execute()\n }\n }\n })\n }\n\n async removeWallet(partyId: PartyId): Promise<void> {\n this.logger.info('Removing wallet')\n const userId = this.assertConnected()\n\n // Remove wallet from current network only\n const network = await this.getCurrentNetwork()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('wallets')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async getUserRights(networkId?: string): Promise<Array<UserLevelRight>> {\n const userId = this.assertConnected()\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n const rows = await this.db\n .selectFrom('userRights')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', targetNetworkId),\n ])\n )\n .execute()\n\n return rows\n .map((row) => fromUserRight(row.right))\n .filter((right): right is UserLevelRight => right !== undefined)\n }\n\n async setUserRights(\n networkId: string,\n rights: Array<UserLevelRight>\n ): Promise<void> {\n const userId = this.assertConnected()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('userRights')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', networkId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n // Session methods\n async getSession(accessToken: AccessToken): Promise<Session | undefined> {\n const userId = this.assertConnected()\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async listSessions(): Promise<Array<Session>> {\n const userId = this.assertConnected()\n const rows = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n return rows.map((row) => toSession(row))\n }\n\n async setSession(session: Session): Promise<void> {\n const userId = this.assertConnected()\n\n if (!session.origin) {\n throw new Error('Session origin is required')\n }\n\n await this.db.transaction().execute(async (trx) => {\n const deleted = await trx\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('origin', '=', session.origin),\n ])\n )\n .execute()\n this.logger.debug(deleted, 'Deleted old session')\n\n const inserted = await trx\n .insertInto('sessions')\n .values({ ...session, userId })\n .execute()\n\n this.logger.debug(inserted, 'Inserted new session')\n })\n }\n\n async removeSession(accessToken: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .execute()\n }\n\n /**\n * Lists all pending transactions across all users.\n */\n async listAllPendingTransactions(): Promise<Array<Transaction>> {\n const rows = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where('status', '=', 'pending')\n .execute()\n\n return rows.map((row) => toTransaction(row))\n }\n\n // IDP methods\n\n async getIdp(idpId: string): Promise<Idp> {\n const idps = await this.listIdps()\n if (!idps) throw new Error('No IDPs available')\n\n const idp = idps.find((n) => n.id === idpId)\n if (!idp) throw new Error(`IDP \"${idpId}\" not found`)\n return idp\n }\n\n async listIdps(): Promise<Array<Idp>> {\n // All IDPs are global for now -- TO-DO: user-specific IDPs\n const query = this.db.selectFrom('idps').selectAll()\n\n const idps = await query.execute()\n return idps.map((table) => toIdp(table))\n }\n\n async updateIdp(idp: Idp): Promise<void> {\n // todo: check and compare userid of existing idp\n await this.db.transaction().execute(async (trx) => {\n const idpEntry = fromIdp(idp)\n this.logger.info(idpEntry, 'Updating idp table')\n await trx\n .updateTable('idps')\n .set(idpEntry)\n .where('id', '=', idp.id)\n .execute()\n })\n }\n\n async addIdp(idp: Idp): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n const idpAlreadyExists = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idp.id)\n .executeTakeFirst()\n if (idpAlreadyExists) {\n throw new Error(`IDP ${idp.id} already exists`)\n } else {\n await trx.insertInto('idps').values(fromIdp(idp)).execute()\n }\n })\n }\n\n async removeIdp(idpId: string): Promise<void> {\n const networks = await this.listNetworks()\n if (networks.some((n) => n.identityProviderId === idpId)) {\n throw new Error(\n `Cannot delete IDP ${idpId} as it is in use by existing networks`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const idp = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idpId)\n .executeTakeFirst()\n if (!idp) {\n throw new Error(`IDP ${idpId} does not exists`)\n }\n await trx.deleteFrom('idps').where('id', '=', idpId).execute()\n })\n }\n\n // Network methods\n async getNetwork(networkId: string): Promise<Network> {\n const networks = await this.listNetworks()\n if (!networks) throw new Error('No networks available')\n\n const network = networks.find((n) => n.id === networkId)\n if (!network) throw new Error(`Network \"${networkId}\" not found`)\n return network\n }\n\n async getCurrentNetwork(): Promise<Network> {\n const token = this.authContext?.accessToken as AccessToken\n\n if (!token) {\n throw new Error('No access token found in auth context')\n }\n\n const session = await this.getSession(token)\n if (!session) {\n throw new Error('No session found')\n }\n const networkId = session.network\n if (!networkId) {\n throw new Error('No current network set in session')\n }\n\n const networks = await this.listNetworks()\n const network = networks.find((n) => n.id === networkId)\n if (!network) {\n throw new Error(`Network \"${networkId}\" not found`)\n }\n return network\n }\n\n async listNetworks(): Promise<Array<Network>> {\n let query = this.db.selectFrom('networks').selectAll()\n\n if (this.authContext) {\n const userId = this.assertConnected()\n query = query.where((eb) =>\n eb.or([\n eb('userId', 'is', null), // Global networks\n eb('userId', '=', userId), // User-specific networks\n ])\n )\n } else {\n query = query.where('userId', 'is', null) // Only global networks\n }\n\n const networks = await query.execute()\n return networks.map((table) => toNetwork(table))\n }\n\n async updateNetwork(network: Network): Promise<void> {\n // todo: check and compare idpId of existing network\n this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n // we do not set a userId for now and leave all networks global when updating\n const networkEntry = fromNetwork(network, undefined)\n this.logger.info(networkEntry, 'Updating network table')\n await trx\n .updateTable('networks')\n .set(networkEntry)\n .where('id', '=', network.id)\n .execute()\n })\n }\n\n async addNetwork(network: Network): Promise<void> {\n const userId = this.authContext?.userId\n const idps = await this.listIdps()\n const networkIdp = idps.find(\n (idp) => idp.id === network.identityProviderId\n )\n\n if (!networkIdp) {\n throw new Error(\n `Identity provider \"${network.identityProviderId}\" not found`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const networkAlreadyExists = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', network.id)\n .executeTakeFirst()\n if (networkAlreadyExists) {\n throw new Error(`Network ${network.id} already exists`)\n } else {\n await trx\n .insertInto('networks')\n .values(fromNetwork(network, userId))\n .execute()\n }\n })\n }\n\n async removeNetwork(networkId: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n const network = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!network) {\n throw new Error(`Network ${networkId} does not exists`)\n }\n if (network.userId !== userId) {\n throw new Error(\n `Network ${networkId} is not owned by user ${userId}`\n )\n }\n await trx\n .deleteFrom('networks')\n .where('id', '=', networkId)\n .execute()\n })\n }\n\n private mergeTransactionStatusUpdate(\n existing: Transaction,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {}\n ): Transaction {\n const payload = updates.payload ?? existing.payload\n const signedAt = updates.signedAt ?? existing.signedAt\n const externalTxId = updates.externalTxId ?? existing.externalTxId\n\n return {\n id: existing.id,\n commandId: existing.commandId,\n status,\n preparedTransaction: existing.preparedTransaction,\n preparedTransactionHash: existing.preparedTransactionHash,\n origin: existing.origin,\n ...(payload !== undefined && { payload }),\n ...(existing.createdAt !== undefined && {\n createdAt: existing.createdAt,\n }),\n ...(signedAt !== undefined && { signedAt }),\n ...(externalTxId !== undefined && { externalTxId }),\n }\n }\n\n // Transaction methods\n async setTransaction(transaction: Transaction): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n await this.db\n .insertInto('transactions')\n .values(fromTransaction(transaction, userId, network.id))\n .execute()\n }\n\n async setTransactionSigned(\n transactionId: string,\n signedAt: Date,\n externalTxId?: string\n ): Promise<void> {\n await this.setTransactionStatus(transactionId, 'signed', {\n signedAt,\n ...(externalTxId !== undefined && { externalTxId }),\n })\n }\n\n async setTransactionStatus(\n transactionId: string,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {}\n ): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getTransaction(transactionId)\n if (!existing) {\n throw new Error(`Transaction not found with id: ${transactionId}`)\n }\n\n const updated = this.mergeTransactionStatusUpdate(\n existing,\n status,\n updates\n )\n\n await this.db\n .updateTable('transactions')\n .set(fromTransaction(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n async getTransaction(\n transactionId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async getLatestTransactionByCommandId(\n commandId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('commandId', '=', commandId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .executeTakeFirst()\n\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async transactionsCount(): Promise<number> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n const result = await this.db\n .selectFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .select((eb) => eb.fn.count<number>('id').as('count'))\n .executeTakeFirstOrThrow()\n\n return Number(result.count)\n }\n\n async listTransactions(options?: ListTransactionsOptions) {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const { cursor, limit } = options ?? {}\n const lim = limit ? Math.min(limit, 100) : 100\n\n let query = this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .orderBy('id', 'desc')\n .limit(lim + 1)\n\n if (cursor) {\n const split = cursor.split('::')\n const dateString = split[0] === 'null' ? null : split[0]\n const cursorId = split[1]\n\n query = query.where((eb) => {\n if (dateString === null) {\n return eb.and([\n eb('createdAt', 'is', null),\n eb('id', '<', cursorId),\n ])\n }\n\n return eb.or([\n eb('createdAt', '<', dateString),\n eb.and([\n eb('createdAt', '=', dateString),\n eb('id', '<', split[1]),\n ]),\n eb('createdAt', 'is', null),\n ])\n })\n }\n\n const rows = await query.execute()\n const txs = rows.map((r) => toTransaction(r))\n\n const hasNextPage = txs.length > lim\n if (hasNextPage) {\n txs.pop()\n }\n\n if (txs.length === 0) {\n return {\n transactions: [],\n nextCursor: null,\n }\n }\n\n const lastTx = txs[txs.length - 1]\n if (lastTx === undefined) {\n return {\n transactions: txs,\n nextCursor: null,\n }\n }\n\n //handle case for if timestamp is null\n if (lastTx.createdAt) {\n const d = new Date(lastTx.createdAt).toISOString()\n const nextCursor = hasNextPage ? `${d}::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n } else {\n const nextCursor = hasNextPage ? `null::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n }\n }\n\n async removeTransaction(transactionId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n private mergeMessageRawStatusUpdate(\n existing: MessageRaw,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): MessageRaw {\n const signedAt = updates.signedAt ?? existing.signedAt\n const signature = updates.signature ?? existing.signature\n\n return {\n ...existing,\n status,\n ...(signedAt !== undefined && { signedAt }),\n ...(signature !== undefined && { signature }),\n }\n }\n\n // Message signing request methods\n async setMessageRaw(message: MessageRaw): Promise<void> {\n const userId = this.assertConnected()\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n const network = await this.getCurrentNetwork()\n await this.db\n .insertInto('messagesRaw')\n .values(fromMessageRaw(message, userId, network.id))\n .execute()\n }\n\n async setMessageRawStatus(\n messageId: string,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getMessageRaw(messageId)\n if (!existing) {\n throw new Error(`MessageRaw not found with id: ${messageId}`)\n }\n\n const updated = this.mergeMessageRawStatusUpdate(\n existing,\n status,\n updates\n )\n\n await this.db\n .updateTable('messagesRaw')\n .set(fromMessageRaw(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n async getMessageRaw(messageId: string): Promise<MessageRaw | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const message = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return message ? toMessageRaw(message) : undefined\n }\n\n async listMessageRaws(): Promise<Array<MessageRaw>> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const messages = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .execute()\n return messages.map((m) => toMessageRaw(m))\n }\n\n async removeMessageRaw(messageId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('messagesRaw')\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n // API keys\n async addApiKey(apiKey: ApiKey): Promise<void> {\n const userId = this.assertConnected()\n if (apiKey.userId !== userId) {\n throw new Error(\n `ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`\n )\n }\n\n const network = await this.getCurrentNetwork()\n if (apiKey.networkId !== network.id) {\n throw new Error(\n `ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`\n )\n }\n\n await this.db.insertInto('apiKeys').values(toApiKey(apiKey)).execute()\n }\n\n async listApiKeys(): Promise<Array<ApiKey>> {\n const query = this.db\n .selectFrom('apiKeys')\n .selectAll()\n .orderBy('createdAt', 'desc')\n\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const apiKeys = await query\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n\n return apiKeys.map(fromApiKey)\n }\n\n async getApiKey(digest: string): Promise<ApiKey | undefined> {\n const apiKey = await this.db\n .selectFrom('apiKeys')\n .selectAll()\n .where((eb) => eb('digest', '=', digest))\n .executeTakeFirst()\n\n return apiKey ? fromApiKey(apiKey) : undefined\n }\n\n async removeApiKey(apiKeyId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('apiKeys')\n .where((eb) =>\n eb.and([\n eb('id', '=', apiKeyId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n}\n\nexport const connection = (config: StoreConfig) => {\n let database\n switch (config.connection.type) {\n case 'sqlite':\n database = new Database(config.connection.database)\n // normally sqlite3 has foreign_keys = OFF for each connection,\n // but better-sqlite3 uses custom build with compile flag SQLITE_DEFAULT_FOREIGN_KEYS=1,\n // making it ON by default.\n // Set explicitly ON anyway as redundancy\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'postgres':\n return new Kysely<DB>({\n dialect: new PostgresDialect({\n pool: new pg.Pool(config.connection),\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'memory':\n database = new Database(':memory:')\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Umzug, MigrationMeta, UmzugStorage } from 'umzug'\nimport { Kysely } from 'kysely'\nimport { DB } from './schema'\n\nclass KyselyStorage implements UmzugStorage {\n constructor(private db: Kysely<DB>) {}\n\n private async ensureTable() {\n await this.db.schema\n .createTable('migrations')\n .ifNotExists()\n .addColumn('name', 'text', (col) => col.primaryKey())\n .addColumn('executedAt', 'text', (col) => col.notNull())\n .execute()\n }\n\n async executed(): Promise<string[]> {\n await this.ensureTable()\n const rows = await this.db\n .selectFrom('migrations')\n .select('name')\n .execute()\n return rows.map((r) => r.name)\n }\n\n async logMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .insertInto('migrations')\n .values({ name, executedAt: new Date().toISOString() })\n .execute()\n }\n\n async unlogMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .deleteFrom('migrations')\n .where('name', '=', name)\n .execute()\n }\n}\n\nexport const migrator = (db: Kysely<DB>) => {\n const ext = import.meta.url.endsWith('.ts') ? 'ts' : 'js'\n const glob = new URL(`./migrations/*.${ext}`, import.meta.url).pathname\n return new Umzug({\n migrations: {\n glob: glob,\n resolve: ({ name, path, context }) => {\n // Dynamic import for ESM\n return {\n name,\n up: async () => {\n console.log(path)\n const { up } = await import(path!)\n return up(context)\n },\n down: async () => {\n const { down } = await import(path!)\n return down(context)\n },\n }\n },\n },\n context: db,\n storage: new KyselyStorage(db),\n logger: console,\n })\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Kysely } from 'kysely'\nimport { StoreSql } from './store-sql.js'\nimport { BootstrapConfig } from '@canton-network/core-wallet-store'\nimport { Logger } from 'pino'\nimport { DB } from './schema'\n\nexport async function bootstrap(\n db: Kysely<DB>,\n config: BootstrapConfig,\n logger: Logger\n): Promise<void> {\n const store = new StoreSql(db, logger)\n\n // Load all IDPs from config into the store\n await Promise.all(config.idps.map((idp) => store.addIdp(idp)))\n\n // Load all networks from config into the store\n await Promise.all(\n config.networks.map((network) => store.addNetwork(network))\n )\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Command } from 'commander'\nimport { connection } from './store-sql.js'\nimport { migrator } from './migrator.js'\nimport type {\n StoreConfig,\n BootstrapConfig,\n} from '@canton-network/core-wallet-store'\nimport { pino } from 'pino'\nimport { bootstrap } from './bootstrap.js'\n\nconst logger = pino({ name: 'main', level: 'debug' })\n\nexport function createCLI(\n config: StoreConfig,\n bootstrapConfig?: BootstrapConfig\n): Command {\n const program = new Command()\n\n program\n .command('up')\n .description('Run all pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('down')\n .description('Rollback last migration')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.down()\n await db.destroy()\n })\n\n program\n .command('status')\n .description('Show executed and pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n const pending = await umzug.pending()\n\n console.log('Executed migrations:', executed)\n console.log('Pending migrations:', pending)\n\n await db.destroy()\n })\n\n program\n .command('reset')\n .description('Rollback all migrations and reapply them')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n\n // Rollback all executed migrations in reverse order\n for (const migration of executed.reverse()) {\n await umzug.down({ to: migration.name })\n }\n\n // Reapply all migrations\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('bootstrap')\n .description('Bootstrap DB from config')\n .action(async () => {\n if (!bootstrapConfig) {\n throw new Error(\n 'Bootstrap config (idps/networks) is required for the bootstrap command'\n )\n }\n const db = connection(config)\n await bootstrap(db, bootstrapConfig, logger)\n await db.destroy()\n })\n\n return program\n}\n"],"mappings":";;;;;;;;;AAkJA,MAAa,SAAS,UAAyB;CAC3C,QAAQ,MAAM,MAAd;EACI,KAAK;GACD,IAAI,CAAC,MAAM,WACP,MAAM,IAAI,MAAM,oCAAoC,MAAM,IAAI;GAGlE,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;IACd,WAAW,MAAM;GACrB;EAEJ,KAAK,eACD,OAAO;GACH,IAAI,MAAM;GACV,MAAM,MAAM;GACZ,QAAQ,MAAM;EAClB;CACR;AACJ;AAEA,M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strap.ts","../src/cli.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { authSchema, Idp, UserId } from '@canton-network/core-wallet-auth'\nimport {\n Wallet,\n Transaction,\n Session,\n Network,\n WalletStatus,\n UpdateWallet,\n PartyLevelRight,\n UserLevelRight,\n MessageRaw,\n ApiKey,\n} from '@canton-network/core-wallet-store'\n\ninterface MigrationTable {\n name: string\n executedAt: string\n}\n\ninterface IdpTable {\n id: string\n type: 'oauth' | 'self_signed'\n issuer: string\n configUrl: string | undefined\n}\n\ninterface NetworkTable {\n id: string\n name: string\n synchronizerId: string | null // retrieved at runtime if null\n description: string\n ledgerApiBaseUrl: string\n identityProviderId: string\n userId: UserId | undefined // global if undefined\n\n auth: string // json stringified\n adminAuth: string | undefined // json stringified\n serviceAccountAuth: string | undefined // json stringified\n}\n\n/**\n * Wallet table schema\n * Primary key on (partyId, networkId, userId)\n * Unique constraint on (networkId, userId) for primary wallet per network per user\n */\ninterface WalletTable {\n primary: number\n partyId: string\n hint: string\n publicKey: string\n namespace: string\n networkId: string\n signingProviderId: string\n userId: UserId\n externalTxId: string | null\n topologyTransactions: string | null\n status: string | null\n disabled: number\n reason: string | null\n}\ninterface UpdateWalletProperties {\n primary?: number\n externalTxId?: string | null\n topologyTransactions?: string | null\n status?: string | null\n disabled?: number\n reason?: string | null\n}\n\ninterface UserPartyRightTable {\n userId: UserId\n networkId: string\n partyId: string\n right: PartyLevelRight\n}\n\ninterface UserRightTable {\n userId: UserId\n networkId: string\n right: UserLevelRight\n}\n\ninterface TransactionTable {\n id: string\n status: string\n commandId: string\n networkId: string\n preparedTransaction: string\n preparedTransactionHash: string\n payload: string | undefined\n origin: string | null\n userId: UserId\n createdAt: string | null\n signedAt: string | null\n externalTxId: string | null\n}\n\ninterface MessageRawTable {\n id: string\n status: string\n partyId: string\n publicKey: string\n message: string\n origin: string | null\n userId: UserId\n networkId: string\n createdAt: string\n signedAt: string | null\n signature: string | null\n}\n\ninterface SessionTable {\n id: string\n origin: string\n network: string\n accessToken: string\n userId: UserId\n}\n\ninterface ApiKeysTable {\n id: string\n digest: string\n name: string\n userId: UserId\n email: string | null\n networkId: string\n createdAt: string\n lastUsedAt: string | null\n}\n\nexport interface DB {\n migrations: MigrationTable\n idps: IdpTable\n networks: NetworkTable\n wallets: WalletTable\n userPartyRights: UserPartyRightTable\n userRights: UserRightTable\n transactions: TransactionTable\n messagesRaw: MessageRawTable\n sessions: SessionTable\n apiKeys: ApiKeysTable\n}\n\nexport const toIdp = (table: IdpTable): Idp => {\n switch (table.type) {\n case 'oauth': {\n if (!table.configUrl) {\n throw new Error(`Missing configUrl for oauth IdP: ${table.id}`)\n }\n\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n configUrl: table.configUrl,\n }\n }\n case 'self_signed':\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n }\n }\n}\n\nexport const fromIdp = (idp: Idp): IdpTable => {\n switch (idp.type) {\n case 'oauth':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: idp.configUrl,\n }\n case 'self_signed':\n return {\n id: idp.id,\n type: idp.type,\n issuer: idp.issuer,\n configUrl: undefined,\n }\n }\n}\n\nexport const toNetwork = (table: NetworkTable): Network => {\n return {\n name: table.name,\n id: table.id,\n synchronizerId: table.synchronizerId ?? undefined,\n identityProviderId: table.identityProviderId,\n description: table.description,\n ledgerApi: {\n baseUrl: table.ledgerApiBaseUrl,\n },\n auth: authSchema.parse(\n typeof table.auth === 'string' ? JSON.parse(table.auth) : table.auth\n ),\n adminAuth: table.adminAuth\n ? authSchema.parse(\n typeof table.adminAuth === 'string'\n ? JSON.parse(table.adminAuth)\n : table.adminAuth\n )\n : undefined,\n serviceAccountAuth: table.serviceAccountAuth\n ? authSchema.parse(\n typeof table.serviceAccountAuth === 'string'\n ? JSON.parse(table.serviceAccountAuth)\n : table.serviceAccountAuth\n )\n : undefined,\n }\n}\n\nexport const fromNetwork = (\n network: Network,\n userId?: UserId\n): NetworkTable => {\n return {\n name: network.name,\n id: network.id,\n synchronizerId: network.synchronizerId ?? null,\n description: network.description,\n ledgerApiBaseUrl: network.ledgerApi.baseUrl,\n userId: userId,\n identityProviderId: network.identityProviderId,\n auth: JSON.stringify(network.auth),\n adminAuth: network.adminAuth\n ? JSON.stringify(network.adminAuth)\n : undefined,\n serviceAccountAuth: network.serviceAccountAuth\n ? JSON.stringify(network.serviceAccountAuth)\n : undefined,\n }\n}\n\nexport const toSession = (table: SessionTable): Session => {\n return {\n id: table.id,\n network: table.network,\n origin: table.origin,\n accessToken: table.accessToken,\n userId: table.userId,\n }\n}\n\nexport const fromWallet = (wallet: Wallet, userId: UserId): WalletTable => {\n const { externalTxId, topologyTransactions, rights, ...rest } = wallet\n void rights\n return {\n ...rest,\n primary: wallet.primary ? 1 : 0,\n userId: userId,\n disabled: wallet.disabled !== undefined && wallet.disabled ? 1 : 0,\n reason: wallet.reason ?? null,\n externalTxId: externalTxId && externalTxId !== '' ? externalTxId : null,\n topologyTransactions:\n topologyTransactions && topologyTransactions !== ''\n ? topologyTransactions\n : null,\n }\n}\n\n// only update fields that are explicitly provided to prevent data loss\nexport const toWalletUpdateProperties = (\n params: UpdateWallet\n): UpdateWalletProperties => {\n const {\n status,\n externalTxId,\n topologyTransactions,\n disabled,\n reason,\n primary,\n signingProviderId,\n publicKey,\n namespace,\n } = params\n return {\n ...(status !== undefined && { status }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(topologyTransactions !== undefined && { topologyTransactions }),\n ...(primary !== undefined && { primary: primary ? 1 : 0 }),\n ...(disabled !== undefined && { disabled: disabled ? 1 : 0 }),\n ...(reason !== undefined && { reason }),\n ...(signingProviderId !== undefined && { signingProviderId }),\n ...(publicKey !== undefined && { publicKey }),\n ...(namespace !== undefined && { namespace }),\n }\n}\n\nexport const toWalletStatus = (status?: string | null): WalletStatus => {\n if (status === 'allocated') return 'allocated'\n if (status === 'removed') return 'removed'\n return 'initialized'\n}\n\nexport const toWallet = (table: WalletTable): Wallet => {\n return {\n primary: Boolean(table.primary),\n status: toWalletStatus(table.status),\n partyId: table.partyId,\n hint: table.hint,\n publicKey: table.publicKey,\n namespace: table.namespace,\n networkId: table.networkId,\n signingProviderId: table.signingProviderId,\n disabled: table.disabled === 1,\n userId: table.userId,\n ...(table.externalTxId !== null && {\n externalTxId: table.externalTxId,\n }),\n ...(table.topologyTransactions !== null && {\n topologyTransactions: table.topologyTransactions,\n }),\n ...(table.reason !== null && {\n reason: table.reason,\n }),\n rights: [],\n }\n}\n\nexport const fromPartyRight = (right: string): PartyLevelRight | undefined => {\n if (Object.values(PartyLevelRight).includes(right as PartyLevelRight)) {\n return right as PartyLevelRight\n }\n return undefined\n}\n\nexport const fromUserRight = (right: string): UserLevelRight | undefined => {\n if (Object.values(UserLevelRight).includes(right as UserLevelRight)) {\n return right as UserLevelRight\n }\n return undefined\n}\n\nexport const fromTransaction = (\n transaction: Transaction,\n userId: UserId,\n networkId: string\n): TransactionTable => {\n return {\n ...transaction,\n networkId,\n payload: transaction.payload\n ? JSON.stringify(transaction.payload)\n : undefined,\n origin: transaction.origin || null,\n userId: userId,\n createdAt: transaction.createdAt?.toISOString() || null,\n signedAt: transaction.signedAt?.toISOString() || null,\n externalTxId: transaction.externalTxId ?? null,\n }\n}\n\nexport const toTransaction = (table: TransactionTable): Transaction => {\n const result: Transaction = {\n id: table.id,\n commandId: table.commandId,\n status: table.status as 'pending' | 'signed' | 'executed' | 'failed',\n preparedTransaction: table.preparedTransaction,\n preparedTransactionHash: table.preparedTransactionHash,\n payload: table.payload ? JSON.parse(table.payload) : undefined,\n origin: table.origin || null,\n userId: table.userId,\n networkId: table.networkId,\n }\n\n if (table.createdAt) {\n result.createdAt = new Date(table.createdAt)\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n\n if (table.externalTxId) {\n result.externalTxId = table.externalTxId\n }\n\n return result\n}\n\nexport const fromMessageRaw = (\n message: MessageRaw,\n userId: UserId,\n networkId: string\n): MessageRawTable => {\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n return {\n id: message.id,\n status: message.status,\n userId: message.userId,\n partyId: message.partyId,\n publicKey: message.publicKey,\n message: message.message,\n origin: message.origin || null,\n networkId,\n createdAt: message.createdAt.toISOString(),\n signedAt: message.signedAt?.toISOString() || null,\n signature: message.signature ?? null,\n }\n}\n\nexport const toMessageRaw = (table: MessageRawTable): MessageRaw => {\n const result: MessageRaw = {\n id: table.id,\n status: table.status as MessageRaw['status'],\n userId: table.userId,\n partyId: table.partyId,\n publicKey: table.publicKey,\n message: table.message,\n origin: table.origin || null,\n createdAt: new Date(table.createdAt),\n }\n\n if (table.signedAt) {\n result.signedAt = new Date(table.signedAt)\n }\n if (table.signature) {\n result.signature = table.signature\n }\n\n return result\n}\n\nexport const fromApiKey = (table: ApiKeysTable): ApiKey => {\n return {\n id: table.id,\n digest: table.digest,\n name: table.name,\n userId: table.userId,\n email: table.email,\n networkId: table.networkId,\n createdAt: new Date(table.createdAt),\n lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : undefined,\n }\n}\n\nexport const toApiKey = (apiKey: ApiKey): ApiKeysTable => {\n return {\n id: apiKey.id,\n digest: apiKey.digest,\n name: apiKey.name,\n userId: apiKey.userId,\n email: apiKey.email,\n networkId: apiKey.networkId,\n createdAt: apiKey.createdAt.toISOString(),\n lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null,\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Logger } from 'pino'\nimport {\n AuthContext,\n UserId,\n AuthAware,\n assertConnected,\n Idp,\n} from '@canton-network/core-wallet-auth'\nimport {\n Store as BaseStore,\n Wallet,\n PartyId,\n Session,\n WalletFilter,\n Transaction,\n MessageRaw,\n MessageRawStatusUpdate,\n Network,\n StoreConfig,\n UpdateWallet,\n CurrentNetworkWalletFilter,\n PartyLevelRight,\n TransactionStatusUpdate,\n UserLevelRight,\n ApiKey,\n ListTransactionsOptions,\n WalletUniqueConstraint,\n} from '@canton-network/core-wallet-store'\nimport { CamelCasePlugin, Kysely, PostgresDialect, SqliteDialect } from 'kysely'\nimport Database from 'better-sqlite3'\nimport {\n DB,\n fromIdp,\n fromNetwork,\n fromTransaction,\n fromMessageRaw,\n fromWallet,\n fromPartyRight,\n fromUserRight,\n toWalletUpdateProperties,\n toIdp,\n toNetwork,\n toTransaction,\n toMessageRaw,\n toWallet,\n fromApiKey,\n toApiKey,\n toSession,\n} from './schema.js'\nimport pg from 'pg'\nimport { sql } from 'kysely'\nimport { AccessToken } from '@canton-network/core-types'\n\nexport class StoreSql implements BaseStore, AuthAware<StoreSql> {\n authContext: AuthContext | undefined\n\n constructor(\n private db: Kysely<DB>,\n private logger: Logger,\n authContext?: AuthContext\n ) {\n this.logger = logger.child({ component: 'StoreSql' })\n this.authContext = authContext\n }\n\n withAuthContext(context?: AuthContext): StoreSql {\n return new StoreSql(this.db, this.logger, context)\n }\n\n private assertConnected(): UserId {\n return assertConnected(this.authContext).userId\n }\n\n // Wallet methods\n\n async getAllWallets(filter: WalletFilter = {}): Promise<Array<Wallet>> {\n const userId = this.assertConnected()\n const { networkIds, signingProviderIds } = filter\n const networkIdSet = networkIds ? new Set(networkIds) : null\n const signingProviderIdSet = signingProviderIds\n ? new Set(signingProviderIds)\n : null\n\n const wallets = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const userPartyRights = await this.db\n .selectFrom('userPartyRights')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n const rightsByWallet = new Map<string, PartyLevelRight[]>()\n for (const row of userPartyRights) {\n const right = fromPartyRight(row.right)\n if (!right) continue\n const key = `${row.partyId}:${row.networkId}`\n const existing = rightsByWallet.get(key) ?? []\n rightsByWallet.set(key, [...existing, right])\n }\n\n return wallets\n .filter((wallet) => {\n const matchedNetworkIds = networkIdSet\n ? networkIdSet.has(wallet.networkId)\n : true\n const matchedSigningProviderIds = signingProviderIdSet\n ? signingProviderIdSet.has(wallet.signingProviderId)\n : true\n return matchedNetworkIds && matchedSigningProviderIds\n })\n .map((table) => {\n const wallet = toWallet(table)\n const rights = rightsByWallet.get(\n `${table.partyId}:${table.networkId}`\n )\n return {\n ...wallet,\n rights: rights ?? [],\n }\n })\n }\n\n async getWallets(\n filter: CurrentNetworkWalletFilter = {}\n ): Promise<Array<Wallet>> {\n const network = await this.getCurrentNetwork()\n return this.getAllWallets({\n ...filter,\n networkIds: [network.id],\n })\n }\n\n async getWallet(partyId: PartyId): Promise<Wallet | null> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const constraint: WalletUniqueConstraint = {\n partyId,\n networkId: network.id,\n userId,\n }\n\n const row = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where((eb) => eb.and(constraint))\n .executeTakeFirst()\n\n if (!row) return null\n\n const rightRows = await this.db\n .selectFrom('userPartyRights')\n .select('right')\n .where((eb) => eb.and(constraint))\n .execute()\n\n return {\n ...toWallet(row),\n rights: rightRows\n .map(({ right }) => fromPartyRight(right))\n .filter((right) => right !== undefined),\n }\n }\n\n async getPrimaryWallet(): Promise<Wallet | undefined> {\n const wallets = await this.getWallets()\n return wallets.find((w) => w.primary === true)\n }\n\n async setPrimaryWallet(partyId: PartyId): Promise<void> {\n const network = await this.getCurrentNetwork()\n const userId = this.assertConnected()\n const wallets = await this.getWallets()\n\n if (!wallets.some((w) => w.partyId === partyId)) {\n throw new Error(\n `Wallet with partyId \"${partyId}\" not found in network \"${network.id}\"`\n )\n }\n\n const primary = wallets.find((w) => w.primary === true)\n\n await this.db.transaction().execute(async (trx) => {\n if (primary) {\n // Unset primary for current network only\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', primary.partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n // Set new primary for current network\n await trx\n .updateTable('wallets')\n .set({ primary: 1 })\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async addWallet(wallet: Wallet): Promise<void> {\n this.logger.info('Adding wallet')\n const userId = this.assertConnected()\n\n const wallets = await this.getWallets()\n if (\n wallets.some(\n (w) =>\n w.partyId === wallet.partyId &&\n w.networkId === wallet.networkId\n )\n ) {\n throw new Error(\n `Wallet with partyId \"${wallet.partyId}\" networkId \"${wallet.networkId}\" userId \"${userId}\" already exists`\n )\n }\n\n if (\n !wallet.disabled &&\n wallet.status === 'allocated' &&\n !wallets.some((wallet) => wallet.primary)\n ) {\n // If there is no primary wallet yet, set current one as primary (unless disabled or not allocated).\n // In regular case it would be the first added wallet.\n wallet.primary = true\n }\n\n await this.db.transaction().execute(async (trx) => {\n if (wallet.primary) {\n // If the new wallet is primary, set all others in the same network and for this user to non-primary\n await trx\n .updateTable('wallets')\n .set({ primary: 0 })\n .where((eb) =>\n eb.and([\n eb('primary', '=', 1),\n eb('networkId', '=', wallet.networkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n await trx\n .insertInto('wallets')\n .values(fromWallet(wallet, userId))\n .execute()\n\n if (wallet.rights && wallet.rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n wallet.rights.map((right) => ({\n userId,\n networkId: wallet.networkId,\n partyId: wallet.partyId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n async updateWallet(params: UpdateWallet): Promise<void> {\n const { partyId, networkId, rights } = params\n this.logger.info('Updating wallet')\n const userId = this.assertConnected()\n\n const updates = toWalletUpdateProperties(params)\n\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n if (Object.keys(updates).length === 0 && rights === undefined) return\n\n await this.db.transaction().execute(async (trx) => {\n if (Object.keys(updates).length > 0) {\n await trx\n .updateTable('wallets')\n .set(updates)\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n }\n\n if (rights !== undefined) {\n await trx\n .deleteFrom('userPartyRights')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', targetNetworkId),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userPartyRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId: targetNetworkId,\n partyId,\n right,\n }))\n )\n .execute()\n }\n }\n })\n }\n\n async removeWallet(partyId: PartyId): Promise<void> {\n this.logger.info('Removing wallet')\n const userId = this.assertConnected()\n\n // Remove wallet from current network only\n const network = await this.getCurrentNetwork()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('wallets')\n .where((eb) =>\n eb.and([\n eb('partyId', '=', partyId),\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n ])\n )\n .execute()\n })\n }\n\n async getUserRights(networkId?: string): Promise<Array<UserLevelRight>> {\n const userId = this.assertConnected()\n const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id\n const rows = await this.db\n .selectFrom('userRights')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', targetNetworkId),\n ])\n )\n .execute()\n\n return rows\n .map((row) => fromUserRight(row.right))\n .filter((right): right is UserLevelRight => right !== undefined)\n }\n\n async setUserRights(\n networkId: string,\n rights: Array<UserLevelRight>\n ): Promise<void> {\n const userId = this.assertConnected()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .deleteFrom('userRights')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', networkId),\n ])\n )\n .execute()\n\n if (rights.length > 0) {\n await trx\n .insertInto('userRights')\n .values(\n rights.map((right) => ({\n userId,\n networkId,\n right,\n }))\n )\n .execute()\n }\n })\n }\n\n // Session methods\n async getSession(accessToken: AccessToken): Promise<Session | undefined> {\n const userId = this.assertConnected()\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async listSessions(): Promise<Array<Session>> {\n const userId = this.assertConnected()\n const rows = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .execute()\n\n return rows.map((row) => toSession(row))\n }\n\n async setSession(session: Session): Promise<void> {\n const userId = this.assertConnected()\n\n if (!session.origin) {\n throw new Error('Session origin is required')\n }\n\n await this.db.transaction().execute(async (trx) => {\n const deleted = await trx\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('origin', '=', session.origin),\n ])\n )\n .execute()\n this.logger.debug(deleted, 'Deleted old session')\n\n const inserted = await trx\n .insertInto('sessions')\n .values({ ...session, userId })\n .execute()\n\n this.logger.debug(inserted, 'Inserted new session')\n })\n }\n\n async removeSession(accessToken: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('accessToken', '=', accessToken),\n ])\n )\n .execute()\n }\n\n /**\n * Lists all pending transactions across all users.\n */\n async listAllPendingTransactions(): Promise<Array<Transaction>> {\n const rows = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where('status', '=', 'pending')\n .execute()\n\n return rows.map((row) => toTransaction(row))\n }\n\n // IDP methods\n\n async getIdp(idpId: string): Promise<Idp> {\n const idps = await this.listIdps()\n if (!idps) throw new Error('No IDPs available')\n\n const idp = idps.find((n) => n.id === idpId)\n if (!idp) throw new Error(`IDP \"${idpId}\" not found`)\n return idp\n }\n\n async listIdps(): Promise<Array<Idp>> {\n // All IDPs are global for now -- TO-DO: user-specific IDPs\n const query = this.db.selectFrom('idps').selectAll()\n\n const idps = await query.execute()\n return idps.map((table) => toIdp(table))\n }\n\n async updateIdp(idp: Idp): Promise<void> {\n // todo: check and compare userid of existing idp\n await this.db.transaction().execute(async (trx) => {\n const idpEntry = fromIdp(idp)\n this.logger.info(idpEntry, 'Updating idp table')\n await trx\n .updateTable('idps')\n .set(idpEntry)\n .where('id', '=', idp.id)\n .execute()\n })\n }\n\n async addIdp(idp: Idp): Promise<void> {\n await this.db.transaction().execute(async (trx) => {\n const idpAlreadyExists = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idp.id)\n .executeTakeFirst()\n if (idpAlreadyExists) {\n throw new Error(`IDP ${idp.id} already exists`)\n } else {\n await trx.insertInto('idps').values(fromIdp(idp)).execute()\n }\n })\n }\n\n async removeIdp(idpId: string): Promise<void> {\n const networks = await this.listNetworks()\n if (networks.some((n) => n.identityProviderId === idpId)) {\n throw new Error(\n `Cannot delete IDP ${idpId} as it is in use by existing networks`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const idp = await trx\n .selectFrom('idps')\n .selectAll()\n .where('id', '=', idpId)\n .executeTakeFirst()\n if (!idp) {\n throw new Error(`IDP ${idpId} does not exists`)\n }\n await trx.deleteFrom('idps').where('id', '=', idpId).execute()\n })\n }\n\n // Network methods\n async getNetwork(networkId: string): Promise<Network> {\n const networks = await this.listNetworks()\n if (!networks) throw new Error('No networks available')\n\n const network = networks.find((n) => n.id === networkId)\n if (!network) throw new Error(`Network \"${networkId}\" not found`)\n return network\n }\n\n async getCurrentNetwork(): Promise<Network> {\n const token = this.authContext?.accessToken as AccessToken\n\n if (!token) {\n throw new Error('No access token found in auth context')\n }\n\n const session = await this.getSession(token)\n if (!session) {\n throw new Error('No session found')\n }\n const networkId = session.network\n if (!networkId) {\n throw new Error('No current network set in session')\n }\n\n const networks = await this.listNetworks()\n const network = networks.find((n) => n.id === networkId)\n if (!network) {\n throw new Error(`Network \"${networkId}\" not found`)\n }\n return network\n }\n\n async listNetworks(): Promise<Array<Network>> {\n let query = this.db.selectFrom('networks').selectAll()\n\n if (this.authContext) {\n const userId = this.assertConnected()\n query = query.where((eb) =>\n eb.or([\n eb('userId', 'is', null), // Global networks\n eb('userId', '=', userId), // User-specific networks\n ])\n )\n } else {\n query = query.where('userId', 'is', null) // Only global networks\n }\n\n const networks = await query.execute()\n return networks.map((table) => toNetwork(table))\n }\n\n async updateNetwork(network: Network): Promise<void> {\n // todo: check and compare idpId of existing network\n this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n // we do not set a userId for now and leave all networks global when updating\n const networkEntry = fromNetwork(network, undefined)\n this.logger.info(networkEntry, 'Updating network table')\n await trx\n .updateTable('networks')\n .set(networkEntry)\n .where('id', '=', network.id)\n .execute()\n })\n }\n\n async addNetwork(network: Network): Promise<void> {\n const userId = this.authContext?.userId\n const idps = await this.listIdps()\n const networkIdp = idps.find(\n (idp) => idp.id === network.identityProviderId\n )\n\n if (!networkIdp) {\n throw new Error(\n `Identity provider \"${network.identityProviderId}\" not found`\n )\n }\n\n await this.db.transaction().execute(async (trx) => {\n const networkAlreadyExists = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', network.id)\n .executeTakeFirst()\n if (networkAlreadyExists) {\n throw new Error(`Network ${network.id} already exists`)\n } else {\n await trx\n .insertInto('networks')\n .values(fromNetwork(network, userId))\n .execute()\n }\n })\n }\n\n async removeNetwork(networkId: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db.transaction().execute(async (trx) => {\n const network = await trx\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!network) {\n throw new Error(`Network ${networkId} does not exists`)\n }\n if (network.userId !== userId) {\n throw new Error(\n `Network ${networkId} is not owned by user ${userId}`\n )\n }\n await trx\n .deleteFrom('networks')\n .where('id', '=', networkId)\n .execute()\n })\n }\n\n private mergeTransactionStatusUpdate(\n existing: Transaction,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {}\n ): Transaction {\n const payload = updates.payload ?? existing.payload\n const signedAt = updates.signedAt ?? existing.signedAt\n const externalTxId = updates.externalTxId ?? existing.externalTxId\n\n return {\n id: existing.id,\n commandId: existing.commandId,\n status,\n preparedTransaction: existing.preparedTransaction,\n preparedTransactionHash: existing.preparedTransactionHash,\n origin: existing.origin,\n ...(payload !== undefined && { payload }),\n ...(existing.createdAt !== undefined && {\n createdAt: existing.createdAt,\n }),\n ...(signedAt !== undefined && { signedAt }),\n ...(externalTxId !== undefined && { externalTxId }),\n }\n }\n\n // Transaction methods\n async setTransaction(transaction: Transaction): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n await this.db\n .insertInto('transactions')\n .values(fromTransaction(transaction, userId, network.id))\n .execute()\n }\n\n async setTransactionSigned(\n transactionId: string,\n signedAt: Date,\n externalTxId?: string\n ): Promise<void> {\n await this.setTransactionStatus(transactionId, 'signed', {\n signedAt,\n ...(externalTxId !== undefined && { externalTxId }),\n })\n }\n\n async setTransactionStatus(\n transactionId: string,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {}\n ): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getTransaction(transactionId)\n if (!existing) {\n throw new Error(`Transaction not found with id: ${transactionId}`)\n }\n\n const updated = this.mergeTransactionStatusUpdate(\n existing,\n status,\n updates\n )\n\n await this.db\n .updateTable('transactions')\n .set(fromTransaction(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n async getTransaction(\n transactionId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async getLatestTransactionByCommandId(\n commandId: string\n ): Promise<Transaction | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const transaction = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('commandId', '=', commandId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .executeTakeFirst()\n\n return transaction ? toTransaction(transaction) : undefined\n }\n\n async transactionsCount(): Promise<number> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n\n const result = await this.db\n .selectFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .select((eb) => eb.fn.count<number>('id').as('count'))\n .executeTakeFirstOrThrow()\n\n return Number(result.count)\n }\n\n async listTransactions(options?: ListTransactionsOptions) {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const { cursor, limit } = options ?? {}\n const lim = limit ? Math.min(limit, 100) : 100\n\n let query = this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy(sql`${sql.ref('createdAt')} desc nulls last`)\n .orderBy('id', 'desc')\n .limit(lim + 1)\n\n if (cursor) {\n const split = cursor.split('::')\n const dateString = split[0] === 'null' ? null : split[0]\n const cursorId = split[1]\n\n query = query.where((eb) => {\n if (dateString === null) {\n return eb.and([\n eb('createdAt', 'is', null),\n eb('id', '<', cursorId),\n ])\n }\n\n return eb.or([\n eb('createdAt', '<', dateString),\n eb.and([\n eb('createdAt', '=', dateString),\n eb('id', '<', split[1]),\n ]),\n eb('createdAt', 'is', null),\n ])\n })\n }\n\n const rows = await query.execute()\n const txs = rows.map((r) => toTransaction(r))\n\n const hasNextPage = txs.length > lim\n if (hasNextPage) {\n txs.pop()\n }\n\n if (txs.length === 0) {\n return {\n transactions: [],\n nextCursor: null,\n }\n }\n\n const lastTx = txs[txs.length - 1]\n if (lastTx === undefined) {\n return {\n transactions: txs,\n nextCursor: null,\n }\n }\n\n //handle case for if timestamp is null\n if (lastTx.createdAt) {\n const d = new Date(lastTx.createdAt).toISOString()\n const nextCursor = hasNextPage ? `${d}::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n } else {\n const nextCursor = hasNextPage ? `null::${lastTx.id}` : null\n return {\n transactions: txs,\n nextCursor: nextCursor,\n }\n }\n }\n\n async removeTransaction(transactionId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('transactions')\n .where((eb) =>\n eb.and([\n eb('id', '=', transactionId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n private mergeMessageRawStatusUpdate(\n existing: MessageRaw,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): MessageRaw {\n const signedAt = updates.signedAt ?? existing.signedAt\n const signature = updates.signature ?? existing.signature\n\n return {\n ...existing,\n status,\n ...(signedAt !== undefined && { signedAt }),\n ...(signature !== undefined && { signature }),\n }\n }\n\n // Message signing request methods\n async setMessageRaw(message: MessageRaw): Promise<void> {\n const userId = this.assertConnected()\n if (message.userId !== userId) {\n throw new Error(\n `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`\n )\n }\n const network = await this.getCurrentNetwork()\n await this.db\n .insertInto('messagesRaw')\n .values(fromMessageRaw(message, userId, network.id))\n .execute()\n }\n\n async setMessageRawStatus(\n messageId: string,\n status: MessageRaw['status'],\n updates: MessageRawStatusUpdate = {}\n ): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const existing = await this.getMessageRaw(messageId)\n if (!existing) {\n throw new Error(`MessageRaw not found with id: ${messageId}`)\n }\n\n const updated = this.mergeMessageRawStatusUpdate(\n existing,\n status,\n updates\n )\n\n await this.db\n .updateTable('messagesRaw')\n .set(fromMessageRaw(updated, userId, network.id))\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n async getMessageRaw(messageId: string): Promise<MessageRaw | undefined> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const message = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .executeTakeFirst()\n return message ? toMessageRaw(message) : undefined\n }\n\n async listMessageRaws(): Promise<Array<MessageRaw>> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const messages = await this.db\n .selectFrom('messagesRaw')\n .selectAll()\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .orderBy('createdAt', 'desc')\n .orderBy('id', 'desc')\n .execute()\n return messages.map((m) => toMessageRaw(m))\n }\n\n async removeMessageRaw(messageId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('messagesRaw')\n .where((eb) =>\n eb.and([\n eb('id', '=', messageId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n\n // API keys\n async addApiKey(apiKey: ApiKey): Promise<void> {\n const userId = this.assertConnected()\n if (apiKey.userId !== userId) {\n throw new Error(\n `ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`\n )\n }\n\n const network = await this.getCurrentNetwork()\n if (apiKey.networkId !== network.id) {\n throw new Error(\n `ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`\n )\n }\n\n await this.db.insertInto('apiKeys').values(toApiKey(apiKey)).execute()\n }\n\n async listApiKeys(): Promise<Array<ApiKey>> {\n const query = this.db\n .selectFrom('apiKeys')\n .selectAll()\n .orderBy('createdAt', 'desc')\n\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n const apiKeys = await query\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n\n return apiKeys.map(fromApiKey)\n }\n\n async getApiKey(digest: string): Promise<ApiKey | undefined> {\n const apiKey = await this.db\n .selectFrom('apiKeys')\n .selectAll()\n .where((eb) => eb('digest', '=', digest))\n .executeTakeFirst()\n\n return apiKey ? fromApiKey(apiKey) : undefined\n }\n\n async removeApiKey(apiKeyId: string): Promise<void> {\n const userId = this.assertConnected()\n const network = await this.getCurrentNetwork()\n await this.db\n .deleteFrom('apiKeys')\n .where((eb) =>\n eb.and([\n eb('id', '=', apiKeyId),\n eb('userId', '=', userId),\n eb('networkId', '=', network.id),\n ])\n )\n .execute()\n }\n}\n\nexport const connection = (config: StoreConfig) => {\n let database\n switch (config.connection.type) {\n case 'sqlite':\n database = new Database(config.connection.database)\n // normally sqlite3 has foreign_keys = OFF for each connection,\n // but better-sqlite3 uses custom build with compile flag SQLITE_DEFAULT_FOREIGN_KEYS=1,\n // making it ON by default.\n // Set explicitly ON anyway as redundancy\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'postgres':\n return new Kysely<DB>({\n dialect: new PostgresDialect({\n pool: new pg.Pool(config.connection),\n }),\n plugins: [new CamelCasePlugin()],\n })\n case 'memory':\n database = new Database(':memory:')\n database.pragma('foreign_keys = ON')\n return new Kysely<DB>({\n dialect: new SqliteDialect({\n database,\n }),\n plugins: [new CamelCasePlugin()],\n })\n }\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Umzug, MigrationMeta, UmzugStorage } from 'umzug'\nimport { Kysely } from 'kysely'\nimport { DB } from './schema'\n\nclass KyselyStorage implements UmzugStorage {\n constructor(private db: Kysely<DB>) {}\n\n private async ensureTable() {\n await this.db.schema\n .createTable('migrations')\n .ifNotExists()\n .addColumn('name', 'text', (col) => col.primaryKey())\n .addColumn('executedAt', 'text', (col) => col.notNull())\n .execute()\n }\n\n async executed(): Promise<string[]> {\n await this.ensureTable()\n const rows = await this.db\n .selectFrom('migrations')\n .select('name')\n .execute()\n return rows.map((r) => r.name)\n }\n\n async logMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .insertInto('migrations')\n .values({ name, executedAt: new Date().toISOString() })\n .execute()\n }\n\n async unlogMigration({ name }: MigrationMeta): Promise<void> {\n await this.ensureTable()\n await this.db\n .deleteFrom('migrations')\n .where('name', '=', name)\n .execute()\n }\n}\n\nexport const migrator = (db: Kysely<DB>) => {\n const ext = import.meta.url.endsWith('.ts') ? 'ts' : 'js'\n const glob = new URL(`./migrations/*.${ext}`, import.meta.url).pathname\n return new Umzug({\n migrations: {\n glob: glob,\n resolve: ({ name, path, context }) => {\n // Dynamic import for ESM\n return {\n name,\n up: async () => {\n console.log(path)\n const { up } = await import(path!)\n return up(context)\n },\n down: async () => {\n const { down } = await import(path!)\n return down(context)\n },\n }\n },\n },\n context: db,\n storage: new KyselyStorage(db),\n logger: console,\n })\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Kysely } from 'kysely'\nimport { StoreSql } from './store-sql.js'\nimport { BootstrapConfig } from '@canton-network/core-wallet-store'\nimport { Logger } from 'pino'\nimport { DB } from './schema'\n\nexport async function bootstrap(\n db: Kysely<DB>,\n config: BootstrapConfig,\n logger: Logger\n): Promise<void> {\n const store = new StoreSql(db, logger)\n\n // Load all IDPs from config into the store\n await Promise.all(config.idps.map((idp) => store.addIdp(idp)))\n\n // Load all networks from config into the store\n await Promise.all(\n config.networks.map((network) => store.addNetwork(network))\n )\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Command } from 'commander'\nimport { connection } from './store-sql.js'\nimport { migrator } from './migrator.js'\nimport type {\n StoreConfig,\n BootstrapConfig,\n} from '@canton-network/core-wallet-store'\nimport { pino } from 'pino'\nimport { bootstrap } from './bootstrap.js'\n\nconst logger = pino({ name: 'main', level: 'debug' })\n\nexport function createCLI(\n config: StoreConfig,\n bootstrapConfig?: BootstrapConfig\n): Command {\n const program = new Command()\n\n program\n .command('up')\n .description('Run all pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('down')\n .description('Rollback last migration')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n await umzug.down()\n await db.destroy()\n })\n\n program\n .command('status')\n .description('Show executed and pending migrations')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n const pending = await umzug.pending()\n\n console.log('Executed migrations:', executed)\n console.log('Pending migrations:', pending)\n\n await db.destroy()\n })\n\n program\n .command('reset')\n .description('Rollback all migrations and reapply them')\n .action(async () => {\n const db = connection(config)\n const umzug = migrator(db)\n const executed = await umzug.executed()\n\n // Rollback all executed migrations in reverse order\n for (const migration of executed.reverse()) {\n await umzug.down({ to: migration.name })\n }\n\n // Reapply all migrations\n await umzug.up()\n await db.destroy()\n })\n\n program\n .command('bootstrap')\n .description('Bootstrap DB from config')\n .action(async () => {\n if (!bootstrapConfig) {\n throw new Error(\n 'Bootstrap config (idps/networks) is required for the bootstrap command'\n )\n }\n const db = connection(config)\n await bootstrap(db, bootstrapConfig, logger)\n await db.destroy()\n })\n\n return program\n}\n"],"mappings":";;;;;;;;;AAkJA,MAAa,SAAS,UAAyB;CAC3C,QAAQ,MAAM,MAAd;EACI,KAAK;GACD,IAAI,CAAC,MAAM,WACP,MAAM,IAAI,MAAM,oCAAoC,MAAM,IAAI;GAGlE,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;IAC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AAQ;CACrB,CAAC;CAEL,OAAO;AACX"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@canton-network/core-wallet-store-sql",
3
- "version": "1.13.1",
3
+ "version": "1.13.2-backport.3",
4
4
  "type": "module",
5
5
  "description": "SQL implementation of the Store API",
6
6
  "license": "Apache-2.0",
@@ -17,29 +17,29 @@
17
17
  }
18
18
  },
19
19
  "dependencies": {
20
- "@canton-network/core-ledger-client": "^1.12.1",
21
- "@canton-network/core-rpc-errors": "^1.11.0",
22
- "@canton-network/core-types": "^1.12.0",
23
- "@canton-network/core-wallet-auth": "^1.12.0",
24
- "@canton-network/core-wallet-store": "^1.13.0",
20
+ "@canton-network/core-ledger-client": "^1.12.2-backport.3",
21
+ "@canton-network/core-rpc-errors": "^1.11.1-backport.3",
22
+ "@canton-network/core-types": "^1.12.1-backport.3",
23
+ "@canton-network/core-wallet-auth": "^1.12.1-backport.3",
24
+ "@canton-network/core-wallet-store": "^1.13.1-backport.3",
25
25
  "better-sqlite3": "^12.11.1",
26
26
  "commander": "^14.0.3",
27
- "kysely": "^0.28.17",
28
- "pg": "^8.22.0",
27
+ "kysely": "^0.28.18",
28
+ "pg": "^8.23.1",
29
29
  "pino": "^10.3.1",
30
30
  "umzug": "^3.8.3",
31
- "zod": "^4.4.3"
31
+ "zod": "^4.6.7"
32
32
  },
33
33
  "devDependencies": {
34
34
  "@testcontainers/postgresql": "^11.14.0",
35
35
  "@types/better-sqlite3": "^7.6.13",
36
- "@types/pg": "^8.20.0",
37
- "@vitest/coverage-v8": "^4.1.10",
36
+ "@types/pg": "^8.23.1",
37
+ "@vitest/coverage-v8": "^4.1.12",
38
38
  "pino-test": "^1.1.0",
39
- "tsdown": "^0.22.9",
40
- "tsx": "^4.23.0",
39
+ "tsdown": "^0.22.14",
40
+ "tsx": "^4.23.15",
41
41
  "typescript": "^5.9.3",
42
- "vitest": "^4.1.11"
42
+ "vitest": "^4.1.12"
43
43
  },
44
44
  "files": [
45
45
  "dist/**"