@canton-network/core-wallet-store-sql 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import Database from "better-sqlite3";
7
7
  import pg from "pg";
8
8
  import { Umzug } from "umzug";
9
9
  import { Command } from "commander";
10
- //#region src/schema.ts
10
+ // src/schema.ts
11
11
  const toIdp = (table) => {
12
12
  switch (table.type) {
13
13
  case "oauth":
@@ -238,8 +238,7 @@ const toApiKey = (apiKey) => {
238
238
  lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null
239
239
  };
240
240
  };
241
- //#endregion
242
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/typeof.js
241
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/typeof.js
243
242
  function _typeof(o) {
244
243
  "@babel/helpers - typeof";
245
244
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -248,8 +247,7 @@ function _typeof(o) {
248
247
  return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
249
248
  }, _typeof(o);
250
249
  }
251
- //#endregion
252
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/toPrimitive.js
250
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/toPrimitive.js
253
251
  function toPrimitive(t, r) {
254
252
  if ("object" != _typeof(t) || !t) return t;
255
253
  var e = t[Symbol.toPrimitive];
@@ -260,14 +258,12 @@ function toPrimitive(t, r) {
260
258
  }
261
259
  return ("string" === r ? String : Number)(t);
262
260
  }
263
- //#endregion
264
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/toPropertyKey.js
261
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/toPropertyKey.js
265
262
  function toPropertyKey(t) {
266
263
  var i = toPrimitive(t, "string");
267
264
  return "symbol" == _typeof(i) ? i : i + "";
268
265
  }
269
- //#endregion
270
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/defineProperty.js
266
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/defineProperty.js
271
267
  function _defineProperty(e, r, t) {
272
268
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
273
269
  value: t,
@@ -276,8 +272,7 @@ function _defineProperty(e, r, t) {
276
272
  writable: !0
277
273
  }) : e[r] = t, e;
278
274
  }
279
- //#endregion
280
- //#region src/store-sql.ts
275
+ // src/store-sql.ts
281
276
  var StoreSql = class StoreSql {
282
277
  constructor(db, authContext) {
283
278
  this.db = db;
@@ -848,8 +843,7 @@ const connection = (config) => {
848
843
  });
849
844
  }
850
845
  };
851
- //#endregion
852
- //#region src/migrator.ts
846
+ // src/migrator.ts
853
847
  var KyselyStorage = class {
854
848
  constructor(db) {
855
849
  this.db = db;
@@ -899,15 +893,13 @@ const migrator = (db) => {
899
893
  logger: console
900
894
  });
901
895
  };
902
- //#endregion
903
- //#region src/bootstrap.ts
896
+ // src/bootstrap.ts
904
897
  async function bootstrap(db, config) {
905
898
  const store = new StoreSql(db);
906
899
  await Promise.all(config.idps.map((idp) => store.addIdp(idp)));
907
900
  await Promise.all(config.networks.map((network) => store.addNetwork(network)));
908
901
  }
909
- //#endregion
910
- //#region src/cli.ts
902
+ // src/cli.ts
911
903
  const logger = getLogger([
912
904
  "core",
913
905
  "wallet-store-sql",
@@ -950,7 +942,6 @@ function createCLI(config, bootstrapConfig) {
950
942
  });
951
943
  return program;
952
944
  }
953
- //#endregion
954
945
  export { StoreSql, bootstrap, connection, createCLI, migrator };
955
946
 
956
947
  //# 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 {\n authSchema,\n type Idp,\n type UserId,\n} from '@canton-network/core-wallet-auth'\nimport {\n type Wallet,\n type Transaction,\n type Session,\n type Network,\n type WalletStatus,\n type UpdateWallet,\n PartyLevelRight,\n UserLevelRight,\n type MessageRaw,\n type 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' | 'self_issued'\n issuer: string | null\n configUrl: string | null\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 isAuthParty: number\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 isAuthParty?: number\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 failureReason: 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 externalTxId: string | null\n failureReason: string | null\n}\n\ninterface SessionTable {\n id: string\n origin: string\n network: string\n accessToken: string | null\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 if (table.issuer === null) {\n throw new Error(`Missing issuer 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 if (table.issuer === null) {\n throw new Error(\n `Missing issuer for self_signed IdP: ${table.id}`\n )\n }\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n }\n case 'self_issued':\n return {\n id: table.id,\n type: table.type,\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: null,\n }\n case 'self_issued':\n return {\n id: idp.id,\n type: idp.type,\n issuer: null,\n configUrl: null,\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 ...(table.accessToken ? { accessToken: table.accessToken } : {}),\n userId: table.userId,\n }\n}\n\nexport const fromWallet = (wallet: Wallet, userId: UserId): WalletTable => {\n const { externalTxId, topologyTransactions, rights, isAuthParty, ...rest } =\n 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 isAuthParty: isAuthParty ? 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 isAuthParty,\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 ...(isAuthParty !== undefined && { isAuthParty: isAuthParty ? 1 : 0 }),\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 isAuthParty: Boolean(table.isAuthParty),\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 failureReason: transaction.failureReason || 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 if (table.failureReason) {\n result.failureReason = table.failureReason\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 externalTxId: message.externalTxId ?? null,\n failureReason: message.failureReason ?? 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 if (table.externalTxId) {\n result.externalTxId = table.externalTxId\n }\n if (table.failureReason) {\n result.failureReason = table.failureReason\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 { getLogger } from '@logtape/logtape'\nimport {\n type AuthContext,\n type UserId,\n type AuthAware,\n assertConnected,\n type Idp,\n} from '@canton-network/core-wallet-auth'\nimport { providerErrors } from '@canton-network/core-rpc-errors'\nimport type {\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 {\n assertUniqueSelfIssuedAudience,\n resolveSelfIssuedNetworkByAudiences,\n} from '@canton-network/core-wallet-store'\nimport {\n CamelCasePlugin,\n Kysely,\n PostgresDialect,\n SqliteDialect,\n sql,\n} from 'kysely'\nimport Database from 'better-sqlite3'\nimport {\n type 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 type { AccessToken } from '@canton-network/core-types'\n\nexport class StoreSql implements BaseStore, AuthAware<StoreSql> {\n private logger = getLogger(['core', 'wallet-store-sql', 'StoreSql'])\n authContext: AuthContext | undefined\n\n constructor(\n private db: Kysely<DB>,\n authContext?: AuthContext\n ) {\n this.authContext = authContext\n }\n\n withAuthContext(context?: AuthContext): StoreSql {\n return new StoreSql(this.db, 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 getWalletByJwt(\n userId: string,\n partyId: PartyId,\n audiences: string[]\n ): Promise<Wallet | undefined> {\n const networks = (\n await this.db.selectFrom('networks').selectAll().execute()\n ).map(toNetwork)\n const network = resolveSelfIssuedNetworkByAudiences(networks, audiences)\n if (!network) {\n return undefined\n }\n\n const row = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where('userId', '=', userId)\n .where('partyId', '=', partyId)\n .where('networkId', '=', network.id)\n .executeTakeFirst()\n\n return row ? toWallet(row) : undefined\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 setAuthPartyWallet(partyId: PartyId | null): Promise<void> {\n const network = await this.getCurrentNetwork()\n const userId = this.assertConnected()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .updateTable('wallets')\n .set({ isAuthParty: 0 })\n .where((eb) =>\n eb.and([\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n eb('isAuthParty', '=', 1),\n ])\n )\n .execute()\n\n if (partyId === null) return\n\n await trx\n .updateTable('wallets')\n .set({ isAuthParty: 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 if (session.accessToken) {\n // Regular session - one user can have only one session per origin.\n // Tokenless sessions are not replaced by duplicates.\n const deleted = await trx\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('origin', '=', session.origin),\n eb('accessToken', 'is not', null),\n ])\n )\n .execute()\n this.logger.info('Deleted old session', { deleted })\n }\n\n const inserted = await trx\n .insertInto('sessions')\n .values({\n ...session,\n accessToken: session.accessToken ?? null,\n userId,\n })\n .execute()\n\n this.logger.info('Inserted new session', { inserted })\n })\n }\n\n async getSelfIssuedLoginSession(\n sessionId: string\n ): Promise<Session | undefined> {\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('id', '=', sessionId)\n .where('accessToken', 'is', null)\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async removeSelfIssuedLoginSession(sessionId: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db\n .deleteFrom('sessions')\n .where('id', '=', sessionId)\n .where('userId', '=', userId)\n .where('accessToken', 'is', null)\n .execute()\n }\n\n async upgradeSelfIssuedLoginSession(\n sessionId: string,\n accessToken: AccessToken\n ): Promise<Session> {\n const userId = this.assertConnected()\n\n return this.db.transaction().execute(async (trx) => {\n const row = await trx\n .selectFrom('sessions')\n .selectAll()\n .where('id', '=', sessionId)\n .where('userId', '=', userId)\n .where('accessToken', 'is', null)\n .executeTakeFirst()\n if (!row) {\n throw new Error('Self-issued login session not found')\n }\n\n await trx\n .deleteFrom('sessions')\n .where('userId', '=', userId)\n .where('origin', '=', row.origin)\n .where('id', '!=', sessionId)\n .execute()\n await trx\n .updateTable('sessions')\n .set({ accessToken })\n .where('id', '=', sessionId)\n .execute()\n\n return toSession({ ...row, accessToken })\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\n async listAllPendingTransactions(): Promise<Array<Transaction>> {\n const rows = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.or([\n eb('status', '=', 'pending'),\n eb('status', '=', 'awaiting-signature'),\n ])\n )\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('Updating idp table', { idpEntry })\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 userId = this.assertConnected()\n const token = this.authContext?.accessToken\n const selfIssuedLoginSessionId =\n this.authContext && !this.authContext.isApiKey\n ? this.authContext.sessionId\n : undefined\n if (!token && !selfIssuedLoginSessionId) {\n throw providerErrors.unauthorized({ message: 'No session found' })\n }\n\n const sessionRow = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .where((eb) =>\n token\n ? eb('accessToken', '=', token)\n : eb.and([\n eb('id', '=', selfIssuedLoginSessionId!),\n eb('accessToken', 'is', null),\n ])\n )\n .executeTakeFirst()\n if (!sessionRow) {\n throw providerErrors.unauthorized({ message: 'No session found' })\n }\n\n const session = toSession(sessionRow)\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 getNetworkForTokenVerification(\n networkId: string\n ): Promise<Network | undefined> {\n // Not scoped by userId: key id resolution happens during token\n // verification, before there is an authenticated user.\n const row = await this.db\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!row) return undefined\n\n const network = toNetwork(row)\n return network.auth.method === 'self_signed' ? network : undefined\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 const existing = (\n await trx.selectFrom('networks').selectAll().execute()\n ).map(toNetwork)\n assertUniqueSelfIssuedAudience(existing, network, network.id)\n\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('Updating network table', { networkEntry })\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 }\n\n const existing = (\n await trx.selectFrom('networks').selectAll().execute()\n ).map(toNetwork)\n assertUniqueSelfIssuedAudience(existing, network)\n\n await trx\n .insertInto('networks')\n .values(fromNetwork(network, userId))\n .execute()\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 const failureReason = updates.failureReason ?? existing.failureReason\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 ...(failureReason && { failureReason }),\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 opts?: { expectedStatus: Transaction['status'] }\n ): Promise<boolean> {\n return await this.setTransactionStatus(\n transactionId,\n 'signed',\n {\n signedAt,\n ...(externalTxId !== undefined && { externalTxId }),\n },\n opts\n )\n }\n\n async setTransactionStatus(\n transactionId: string,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {},\n opts?: { expectedStatus?: Transaction['status'] }\n ): Promise<boolean> {\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 if (opts?.expectedStatus && existing.status !== opts.expectedStatus) {\n return false\n }\n\n const updated = this.mergeTransactionStatusUpdate(\n existing,\n status,\n updates\n )\n\n const res = 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 ...(opts?.expectedStatus\n ? [eb('status', '=', opts.expectedStatus)]\n : []),\n ])\n )\n .executeTakeFirst()\n\n return res.numUpdatedRows > 0n\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 const externalTxId = updates.externalTxId ?? existing.externalTxId\n const failureReason = updates.failureReason ?? existing.failureReason\n\n return {\n ...existing,\n status,\n ...(signedAt !== undefined && { signedAt }),\n ...(signature !== undefined && { signature }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(failureReason !== undefined && { failureReason }),\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, type MigrationMeta, type UmzugStorage } from 'umzug'\nimport type { Kysely } from 'kysely'\nimport type { 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 type { Kysely } from 'kysely'\nimport { StoreSql } from './store-sql.js'\nimport type { BootstrapConfig } from '@canton-network/core-wallet-store'\nimport type { DB } from './schema'\n\nexport async function bootstrap(\n db: Kysely<DB>,\n config: BootstrapConfig\n): Promise<void> {\n const store = new StoreSql(db)\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 { bootstrap } from './bootstrap.js'\nimport { getLogger } from '@logtape/logtape'\n\nconst logger = getLogger(['core', 'wallet-store-sql', 'cli'])\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 logger.info('Executed migrations: {executed}', { executed })\n logger.info('Pending migrations: {pending}', { 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)\n await db.destroy()\n })\n\n return program\n}\n"],"mappings":";;;;;;;;;;AA2JA,MAAa,SAAS,UAAyB;CAC3C,QAAQ,MAAM,MAAd;EACI,KAAK;GACD,IAAI,CAAC,MAAM,WACP,MAAM,IAAI,MAAM,oCAAoC,MAAM,IAAI;GAElE,IAAI,MAAM,WAAW,MACjB,MAAM,IAAI,MAAM,iCAAiC,MAAM,IAAI;GAG/D,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;IACd,WAAW,MAAM;GACrB;EAEJ,KAAK;GACD,IAAI,MAAM,WAAW,MACjB,MAAM,IAAI,MACN,uCAAuC,MAAM,IACjD;GAEJ,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;GAClB;EACJ,KAAK,eACD,OAAO;GACH,IAAI,MAAM;GACV,MAAM,MAAM;EAChB;CACR;AACJ;AAEA,MAAa,WAAW,QAA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,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,eAAe;EACnC,MAAM,GAAG,QAAQ;CACrB,CAAC;CAEL,OAAO;AACX"}
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 {\n authSchema,\n type Idp,\n type UserId,\n} from '@canton-network/core-wallet-auth'\nimport {\n type Wallet,\n type Transaction,\n type Session,\n type Network,\n type WalletStatus,\n type UpdateWallet,\n PartyLevelRight,\n UserLevelRight,\n type MessageRaw,\n type 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' | 'self_issued'\n issuer: string | null\n configUrl: string | null\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 isAuthParty: number\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 isAuthParty?: number\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 failureReason: 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 externalTxId: string | null\n failureReason: string | null\n}\n\ninterface SessionTable {\n id: string\n origin: string\n network: string\n accessToken: string | null\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 if (table.issuer === null) {\n throw new Error(`Missing issuer 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 if (table.issuer === null) {\n throw new Error(\n `Missing issuer for self_signed IdP: ${table.id}`\n )\n }\n return {\n id: table.id,\n type: table.type,\n issuer: table.issuer,\n }\n case 'self_issued':\n return {\n id: table.id,\n type: table.type,\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: null,\n }\n case 'self_issued':\n return {\n id: idp.id,\n type: idp.type,\n issuer: null,\n configUrl: null,\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 ...(table.accessToken ? { accessToken: table.accessToken } : {}),\n userId: table.userId,\n }\n}\n\nexport const fromWallet = (wallet: Wallet, userId: UserId): WalletTable => {\n const { externalTxId, topologyTransactions, rights, isAuthParty, ...rest } =\n 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 isAuthParty: isAuthParty ? 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 isAuthParty,\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 ...(isAuthParty !== undefined && { isAuthParty: isAuthParty ? 1 : 0 }),\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 isAuthParty: Boolean(table.isAuthParty),\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 failureReason: transaction.failureReason || 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 if (table.failureReason) {\n result.failureReason = table.failureReason\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 externalTxId: message.externalTxId ?? null,\n failureReason: message.failureReason ?? 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 if (table.externalTxId) {\n result.externalTxId = table.externalTxId\n }\n if (table.failureReason) {\n result.failureReason = table.failureReason\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 { getLogger } from '@logtape/logtape'\nimport {\n type AuthContext,\n type UserId,\n type AuthAware,\n assertConnected,\n type Idp,\n} from '@canton-network/core-wallet-auth'\nimport { providerErrors } from '@canton-network/core-rpc-errors'\nimport type {\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 {\n assertUniqueSelfIssuedAudience,\n resolveSelfIssuedNetworkByAudiences,\n} from '@canton-network/core-wallet-store'\nimport {\n CamelCasePlugin,\n Kysely,\n PostgresDialect,\n SqliteDialect,\n sql,\n} from 'kysely'\nimport Database from 'better-sqlite3'\nimport {\n type 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 type { AccessToken } from '@canton-network/core-types'\n\nexport class StoreSql implements BaseStore, AuthAware<StoreSql> {\n private logger = getLogger(['core', 'wallet-store-sql', 'StoreSql'])\n authContext: AuthContext | undefined\n\n constructor(\n private db: Kysely<DB>,\n authContext?: AuthContext\n ) {\n this.authContext = authContext\n }\n\n withAuthContext(context?: AuthContext): StoreSql {\n return new StoreSql(this.db, 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 getWalletByJwt(\n userId: string,\n partyId: PartyId,\n audiences: string[]\n ): Promise<Wallet | undefined> {\n const networks = (\n await this.db.selectFrom('networks').selectAll().execute()\n ).map(toNetwork)\n const network = resolveSelfIssuedNetworkByAudiences(networks, audiences)\n if (!network) {\n return undefined\n }\n\n const row = await this.db\n .selectFrom('wallets')\n .selectAll()\n .where('userId', '=', userId)\n .where('partyId', '=', partyId)\n .where('networkId', '=', network.id)\n .executeTakeFirst()\n\n return row ? toWallet(row) : undefined\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 setAuthPartyWallet(partyId: PartyId | null): Promise<void> {\n const network = await this.getCurrentNetwork()\n const userId = this.assertConnected()\n\n await this.db.transaction().execute(async (trx) => {\n await trx\n .updateTable('wallets')\n .set({ isAuthParty: 0 })\n .where((eb) =>\n eb.and([\n eb('networkId', '=', network.id),\n eb('userId', '=', userId),\n eb('isAuthParty', '=', 1),\n ])\n )\n .execute()\n\n if (partyId === null) return\n\n await trx\n .updateTable('wallets')\n .set({ isAuthParty: 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 if (session.accessToken) {\n // Regular session - one user can have only one session per origin.\n // Tokenless sessions are not replaced by duplicates.\n const deleted = await trx\n .deleteFrom('sessions')\n .where((eb) =>\n eb.and([\n eb('userId', '=', userId),\n eb('origin', '=', session.origin),\n eb('accessToken', 'is not', null),\n ])\n )\n .execute()\n this.logger.info('Deleted old session', { deleted })\n }\n\n const inserted = await trx\n .insertInto('sessions')\n .values({\n ...session,\n accessToken: session.accessToken ?? null,\n userId,\n })\n .execute()\n\n this.logger.info('Inserted new session', { inserted })\n })\n }\n\n async getSelfIssuedLoginSession(\n sessionId: string\n ): Promise<Session | undefined> {\n const row = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('id', '=', sessionId)\n .where('accessToken', 'is', null)\n .executeTakeFirst()\n return row ? toSession(row) : undefined\n }\n\n async removeSelfIssuedLoginSession(sessionId: string): Promise<void> {\n const userId = this.assertConnected()\n await this.db\n .deleteFrom('sessions')\n .where('id', '=', sessionId)\n .where('userId', '=', userId)\n .where('accessToken', 'is', null)\n .execute()\n }\n\n async upgradeSelfIssuedLoginSession(\n sessionId: string,\n accessToken: AccessToken\n ): Promise<Session> {\n const userId = this.assertConnected()\n\n return this.db.transaction().execute(async (trx) => {\n const row = await trx\n .selectFrom('sessions')\n .selectAll()\n .where('id', '=', sessionId)\n .where('userId', '=', userId)\n .where('accessToken', 'is', null)\n .executeTakeFirst()\n if (!row) {\n throw new Error('Self-issued login session not found')\n }\n\n await trx\n .deleteFrom('sessions')\n .where('userId', '=', userId)\n .where('origin', '=', row.origin)\n .where('id', '!=', sessionId)\n .execute()\n await trx\n .updateTable('sessions')\n .set({ accessToken })\n .where('id', '=', sessionId)\n .execute()\n\n return toSession({ ...row, accessToken })\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\n async listAllPendingTransactions(): Promise<Array<Transaction>> {\n const rows = await this.db\n .selectFrom('transactions')\n .selectAll()\n .where((eb) =>\n eb.or([\n eb('status', '=', 'pending'),\n eb('status', '=', 'awaiting-signature'),\n ])\n )\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('Updating idp table', { idpEntry })\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 userId = this.assertConnected()\n const token = this.authContext?.accessToken\n const selfIssuedLoginSessionId =\n this.authContext && !this.authContext.isApiKey\n ? this.authContext.sessionId\n : undefined\n if (!token && !selfIssuedLoginSessionId) {\n throw providerErrors.unauthorized({ message: 'No session found' })\n }\n\n const sessionRow = await this.db\n .selectFrom('sessions')\n .selectAll()\n .where('userId', '=', userId)\n .where((eb) =>\n token\n ? eb('accessToken', '=', token)\n : eb.and([\n eb('id', '=', selfIssuedLoginSessionId!),\n eb('accessToken', 'is', null),\n ])\n )\n .executeTakeFirst()\n if (!sessionRow) {\n throw providerErrors.unauthorized({ message: 'No session found' })\n }\n\n const session = toSession(sessionRow)\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 getNetworkForTokenVerification(\n networkId: string\n ): Promise<Network | undefined> {\n // Not scoped by userId: key id resolution happens during token\n // verification, before there is an authenticated user.\n const row = await this.db\n .selectFrom('networks')\n .selectAll()\n .where('id', '=', networkId)\n .executeTakeFirst()\n if (!row) return undefined\n\n const network = toNetwork(row)\n return network.auth.method === 'self_signed' ? network : undefined\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 const existing = (\n await trx.selectFrom('networks').selectAll().execute()\n ).map(toNetwork)\n assertUniqueSelfIssuedAudience(existing, network, network.id)\n\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('Updating network table', { networkEntry })\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 }\n\n const existing = (\n await trx.selectFrom('networks').selectAll().execute()\n ).map(toNetwork)\n assertUniqueSelfIssuedAudience(existing, network)\n\n await trx\n .insertInto('networks')\n .values(fromNetwork(network, userId))\n .execute()\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 const failureReason = updates.failureReason ?? existing.failureReason\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 ...(failureReason && { failureReason }),\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 opts?: { expectedStatus: Transaction['status'] }\n ): Promise<boolean> {\n return await this.setTransactionStatus(\n transactionId,\n 'signed',\n {\n signedAt,\n ...(externalTxId !== undefined && { externalTxId }),\n },\n opts\n )\n }\n\n async setTransactionStatus(\n transactionId: string,\n status: Transaction['status'],\n updates: TransactionStatusUpdate = {},\n opts?: { expectedStatus?: Transaction['status'] }\n ): Promise<boolean> {\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 if (opts?.expectedStatus && existing.status !== opts.expectedStatus) {\n return false\n }\n\n const updated = this.mergeTransactionStatusUpdate(\n existing,\n status,\n updates\n )\n\n const res = 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 ...(opts?.expectedStatus\n ? [eb('status', '=', opts.expectedStatus)]\n : []),\n ])\n )\n .executeTakeFirst()\n\n return res.numUpdatedRows > 0n\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 const externalTxId = updates.externalTxId ?? existing.externalTxId\n const failureReason = updates.failureReason ?? existing.failureReason\n\n return {\n ...existing,\n status,\n ...(signedAt !== undefined && { signedAt }),\n ...(signature !== undefined && { signature }),\n ...(externalTxId !== undefined && { externalTxId }),\n ...(failureReason !== undefined && { failureReason }),\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, type MigrationMeta, type UmzugStorage } from 'umzug'\nimport type { Kysely } from 'kysely'\nimport type { 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 type { Kysely } from 'kysely'\nimport { StoreSql } from './store-sql.js'\nimport type { BootstrapConfig } from '@canton-network/core-wallet-store'\nimport type { DB } from './schema'\n\nexport async function bootstrap(\n db: Kysely<DB>,\n config: BootstrapConfig\n): Promise<void> {\n const store = new StoreSql(db)\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 { bootstrap } from './bootstrap.js'\nimport { getLogger } from '@logtape/logtape'\n\nconst logger = getLogger(['core', 'wallet-store-sql', 'cli'])\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 logger.info('Executed migrations: {executed}', { executed })\n logger.info('Pending migrations: {pending}', { 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)\n await db.destroy()\n })\n\n return program\n}\n"],"mappings":";;;;;;;;;;AA2JA,MAAa,SAAS,UAAyB;CAC3C,QAAQ,MAAM,MAAd;EACI,KAAK;GACD,IAAI,CAAC,MAAM,WACP,MAAM,IAAI,MAAM,oCAAoC,MAAM,IAAI;GAElE,IAAI,MAAM,WAAW,MACjB,MAAM,IAAI,MAAM,iCAAiC,MAAM,IAAI;GAG/D,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;IACd,WAAW,MAAM;GACrB;EAEJ,KAAK;GACD,IAAI,MAAM,WAAW,MACjB,MAAM,IAAI,MACN,uCAAuC,MAAM,IACjD;GAEJ,OAAO;IACH,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ,MAAM;GAClB;EACJ,KAAK,eACD,OAAO;GACH,IAAI,MAAM;GACV,MAAM,MAAM;EAChB;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;EACf;EACJ,KAAK,eACD,OAAO;GACH,IAAI,IAAI;GACR,MAAM,IAAI;GACV,QAAQ;GACR,WAAW;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,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MAAM;EAC5B,MAAM,UAAU,IAAI,eAAe;EACnC,MAAM,GAAG,QAAQ;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": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "type": "module",
5
5
  "description": "SQL implementation of the Store API",
6
6
  "license": "Apache-2.0",
@@ -17,25 +17,23 @@
17
17
  }
18
18
  },
19
19
  "dependencies": {
20
- "@canton-network/core-ledger-client": "2.1.0",
21
- "@canton-network/core-rpc-errors": "1.14.0",
22
- "@canton-network/core-types": "2.1.0",
23
- "@canton-network/core-wallet-auth": "2.1.0",
24
- "@canton-network/core-wallet-store": "1.16.0",
20
+ "@canton-network/core-rpc-errors": "1.15.0",
21
+ "@canton-network/core-types": "2.2.0",
22
+ "@canton-network/core-wallet-auth": "2.2.0",
23
+ "@canton-network/core-wallet-store": "1.17.0",
25
24
  "@logtape/logtape": "^2.4.1",
26
25
  "better-sqlite3": "^13.0.3",
27
26
  "commander": "^15.0.0",
28
27
  "kysely": "^0.29.6",
29
28
  "pg": "^8.23.1",
30
- "umzug": "^3.8.3",
31
- "zod": "^4.6.7"
29
+ "umzug": "^3.8.3"
32
30
  },
33
31
  "devDependencies": {
34
32
  "@testcontainers/postgresql": "^12.2.1",
35
33
  "@types/better-sqlite3": "^9.6.0",
36
34
  "@types/pg": "^8.23.1",
37
35
  "@vitest/coverage-v8": "^5.0.5",
38
- "tsdown": "^0.23.1",
36
+ "tsdown": "^0.23.2",
39
37
  "tsx": "^4.23.15",
40
38
  "typescript": "npm:@typescript/typescript6@^6.0.2",
41
39
  "vitest": "^5.0.5"