@canton-network/dapp-sdk 1.1.0 → 1.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
@@ -1,10 +1,11 @@
1
- import { DappSyncProvider, injectProvider, DappAsyncProvider } from '@canton-network/core-provider-dapp';
1
+ import { DappSyncProvider, DappAsyncProvider } from '@canton-network/core-provider-dapp';
2
2
  import { CANTON_ANNOUNCE_PROVIDER_EVENT, CANTON_REQUEST_PROVIDER_EVENT, WalletEvent, DiscoverResult } from '@canton-network/core-types';
3
3
  import { pickWallet, notifyWalletPickerConnected, notifyWalletPickerError, waitForWalletPickerRetrySelection, popup } from '@canton-network/core-wallet-ui-components';
4
4
  import { DiscoveryClient } from '@canton-network/core-wallet-discovery';
5
5
  export { DiscoveryClient, DiscoveryError, EventEmitter, NotConnectedError, SessionExpiredError, TimeoutError, UserRejectedError, WalletNotFoundError, WalletNotInstalledError } from '@canton-network/core-wallet-discovery';
6
6
  import { WindowTransport } from '@canton-network/core-rpc-transport';
7
7
  import SignClient from '@walletconnect/sign-client';
8
+ import { v4 } from 'uuid';
8
9
  import * as coreWalletDappRpcClient from '@canton-network/core-wallet-dapp-rpc-client';
9
10
  export { coreWalletDappRpcClient as dappAPI };
10
11
 
@@ -64,6 +65,31 @@ var clearAllLocalState = ({
64
65
  popup.close();
65
66
  }
66
67
  };
68
+ var composeSIWXMessage = (params) => {
69
+ {
70
+ const networkName = "Canton";
71
+ return [
72
+ `${params.domain} wants you to sign in with your ${networkName} account:`,
73
+ params.accountAddress,
74
+ params.statement ? `
75
+ ${params.statement}
76
+ ` : "",
77
+ `URI: ${params.uri}`,
78
+ `Version: ${params.version}`,
79
+ `Chain ID: ${params.chainId}`,
80
+ `Nonce: ${params.nonce}`,
81
+ params.issuedAt && `Issued At: ${params.issuedAt}`,
82
+ params.expirationTime && `Expiration Time: ${params.expirationTime}`,
83
+ params.notBefore && `Not Before: ${params.notBefore}`,
84
+ params.requestId && `Request ID: ${params.requestId}`,
85
+ params.resources?.length && params.resources.reduce(
86
+ (acc, resource) => `${acc}
87
+ - ${resource}`,
88
+ "Resources:"
89
+ )
90
+ ].filter((line) => typeof line === "string").join("\n").trim();
91
+ }
92
+ };
67
93
 
68
94
  // src/client.ts
69
95
  var DappClient = class {
@@ -72,9 +98,6 @@ var DappClient = class {
72
98
  __publicField(this, "options");
73
99
  this.provider = provider;
74
100
  this.options = options;
75
- if (options.injectGlobal !== false) {
76
- injectProvider(provider);
77
- }
78
101
  }
79
102
  // ── Provider access ───────────────────────────────────
80
103
  getProvider() {
@@ -99,6 +122,9 @@ var DappClient = class {
99
122
  params
100
123
  });
101
124
  }
125
+ async signMessage(params) {
126
+ return this.provider.request({ method: "signMessage", params });
127
+ }
102
128
  async ledgerApi(params) {
103
129
  return this.provider.request({ method: "ledgerApi", params });
104
130
  }
@@ -115,6 +141,9 @@ var DappClient = class {
115
141
  onTxChanged(listener) {
116
142
  this.provider.on("txChanged", listener);
117
143
  }
144
+ onMessageSignature(listener) {
145
+ this.provider.on("messageSignature", listener);
146
+ }
118
147
  removeOnStatusChanged(listener) {
119
148
  this.provider.removeListener("statusChanged", listener);
120
149
  }
@@ -130,6 +159,12 @@ var DappClient = class {
130
159
  removeOnTxChanged(listener) {
131
160
  this.provider.removeListener("txChanged", listener);
132
161
  }
162
+ removeOnMessageSignature(listener) {
163
+ this.provider.removeListener(
164
+ "messageSignature",
165
+ listener
166
+ );
167
+ }
133
168
  // ── Open wallet UI ─────────────────────────────────────
134
169
  async open() {
135
170
  const statusResult = await this.status();
@@ -243,52 +278,6 @@ var ExtensionAdapter = class {
243
278
  }
244
279
  };
245
280
 
246
- // src/adapter/injected-adapter.ts
247
- var InjectedAdapter = class {
248
- constructor(config) {
249
- __publicField(this, "providerId");
250
- __publicField(this, "name");
251
- __publicField(this, "type", "browser");
252
- __publicField(this, "icon");
253
- __publicField(this, "providerInstance");
254
- __publicField(this, "description");
255
- this.providerId = `browser:${config.id}`;
256
- this.name = config.name;
257
- this.icon = config.icon;
258
- this.providerInstance = config.provider;
259
- this.description = config.description;
260
- }
261
- getInfo() {
262
- return {
263
- providerId: this.providerId,
264
- name: this.name,
265
- type: this.type,
266
- description: this.description ?? "Connect via an injected CIP-103 provider (window namespace)",
267
- icon: this.icon
268
- };
269
- }
270
- async detect() {
271
- return true;
272
- }
273
- provider() {
274
- return this.providerInstance;
275
- }
276
- teardown() {
277
- }
278
- async restore() {
279
- try {
280
- const status2 = await this.providerInstance.request({
281
- method: "status"
282
- });
283
- if (status2.connection.isConnected) {
284
- return this.providerInstance;
285
- }
286
- } catch {
287
- }
288
- return null;
289
- }
290
- };
291
-
292
281
  // src/dapp-api/rpc-gen/index.ts
293
282
  function buildController(methods) {
294
283
  return {
@@ -304,7 +293,8 @@ function buildController(methods) {
304
293
  accountsChanged: methods.accountsChanged,
305
294
  getPrimaryAccount: methods.getPrimaryAccount,
306
295
  listAccounts: methods.listAccounts,
307
- txChanged: methods.txChanged
296
+ txChanged: methods.txChanged,
297
+ messageSignature: methods.messageSignature
308
298
  };
309
299
  }
310
300
  var rpc_gen_default = buildController;
@@ -430,13 +420,51 @@ var dappSDKController = (provider) => rpc_gen_default({
430
420
  getActiveNetwork: async () => provider.request({
431
421
  method: "getActiveNetwork"
432
422
  }),
433
- signMessage: async (params) => provider.request({
434
- method: "signMessage",
435
- params
436
- }),
423
+ signMessage: async (params) => {
424
+ const response = await provider.request({
425
+ method: "signMessage",
426
+ params
427
+ });
428
+ const { userUrl } = response;
429
+ popup.open(userUrl);
430
+ const messageId = new URL(userUrl).searchParams.get("messageId");
431
+ if (!messageId) {
432
+ throw new Error(
433
+ "Remote signMessage userUrl is missing messageId query param"
434
+ );
435
+ }
436
+ return await new Promise((resolve, reject) => {
437
+ const timeout = withTimeout(
438
+ reject,
439
+ "Timed out waiting for message signing approval"
440
+ );
441
+ const listener = (event) => {
442
+ if (event.messageId !== messageId) return;
443
+ if (event.status === "pending") return;
444
+ provider.removeListener("messageSignature", listener);
445
+ clearTimeout(timeout);
446
+ if (event.status === "failed") {
447
+ reject({
448
+ status: "error",
449
+ error: 3 /* TransactionFailed */,
450
+ details: `Message signing failed for messageId ${event.messageId}.`
451
+ });
452
+ return;
453
+ }
454
+ resolve({ signature: event.signature });
455
+ };
456
+ provider.on(
457
+ "messageSignature",
458
+ listener
459
+ );
460
+ });
461
+ },
437
462
  getPrimaryAccount: async () => provider.request({
438
463
  method: "getPrimaryAccount"
439
- })
464
+ }),
465
+ messageSignature: function() {
466
+ throw new Error("Only for events.");
467
+ }
440
468
  });
441
469
 
442
470
  // src/adapter/remote-adapter.ts
@@ -598,6 +626,8 @@ var WalletConnectAdapter = class _WalletConnectAdapter {
598
626
  __publicField(this, "chainId");
599
627
  __publicField(this, "metadata");
600
628
  __publicField(this, "onUri");
629
+ __publicField(this, "onSignInWithCanton");
630
+ __publicField(this, "signInWithCanton");
601
631
  __publicField(this, "signClient", null);
602
632
  __publicField(this, "session", null);
603
633
  __publicField(this, "initPromise", null);
@@ -605,9 +635,11 @@ var WalletConnectAdapter = class _WalletConnectAdapter {
605
635
  __publicField(this, "listeners", {});
606
636
  __publicField(this, "eventBuffer", /* @__PURE__ */ new Map());
607
637
  this.projectId = config.projectId;
638
+ this.signInWithCanton = config.signInWithCanton;
608
639
  this.chainId = config.chainId ?? "canton:devnet";
609
640
  this.metadata = config.metadata;
610
641
  this.onUri = config.onUri;
642
+ this.onSignInWithCanton = config.onSignInWithCanton;
611
643
  }
612
644
  static create(config) {
613
645
  return new _WalletConnectAdapter(config);
@@ -814,6 +846,46 @@ var WalletConnectAdapter = class _WalletConnectAdapter {
814
846
  }
815
847
  this.session = await approval();
816
848
  this.setupSessionEvents();
849
+ if (this.signInWithCanton) {
850
+ const nonce = this.signInWithCanton.nonce || v4();
851
+ try {
852
+ const account = this.session?.namespaces?.canton?.accounts?.[0];
853
+ const address = decodeURIComponent(account?.split(":")[2]);
854
+ const chainId = account?.split(":")[1] ?? this.chainId;
855
+ const message = composeSIWXMessage({
856
+ ...this.signInWithCanton,
857
+ accountAddress: address,
858
+ chainId
859
+ });
860
+ const result = await this.walletConnectRequest("signMessage", {
861
+ message
862
+ });
863
+ this.onSignInWithCanton?.({
864
+ requestId: this.signInWithCanton.requestId,
865
+ nonce,
866
+ account,
867
+ chainId,
868
+ message,
869
+ signature: result.signature,
870
+ publicKey: result.publicKey
871
+ });
872
+ } catch (error) {
873
+ const err = error;
874
+ this.onSignInWithCanton?.({
875
+ requestId: this.signInWithCanton.requestId,
876
+ nonce,
877
+ account: "",
878
+ chainId: "",
879
+ message: "",
880
+ publicKey: "",
881
+ signature: "",
882
+ error: {
883
+ message: err.message,
884
+ code: -32603
885
+ }
886
+ });
887
+ }
888
+ }
817
889
  }
818
890
  async showUriInPopup(uri) {
819
891
  try {
@@ -842,48 +914,6 @@ var gateways_default = [
842
914
  rpcUrl: "http://localhost:3030/api/v0/dapp"
843
915
  }
844
916
  ];
845
-
846
- // src/injected-discovery.ts
847
- var DEFAULT_ROOTS = ["canton"];
848
- var isProviderLike = (obj) => {
849
- if (typeof obj !== "object" || obj === null) return false;
850
- const p = obj;
851
- return typeof p.request === "function" && typeof p.on === "function" && typeof p.emit === "function" && typeof p.removeListener === "function";
852
- };
853
- function discoverInjectedProviders(roots = DEFAULT_ROOTS) {
854
- if (typeof window === "undefined") return [];
855
- const discovered = [];
856
- const seen = /* @__PURE__ */ new Set();
857
- const win = window;
858
- for (const root of roots) {
859
- const candidate = win[root];
860
- if (candidate === void 0 || candidate === null) continue;
861
- if (isProviderLike(candidate) && !seen.has(candidate)) {
862
- seen.add(candidate);
863
- discovered.push({
864
- id: root,
865
- provider: candidate,
866
- sourceRoot: root
867
- });
868
- continue;
869
- }
870
- if (typeof candidate === "object") {
871
- for (const [key, value] of Object.entries(
872
- candidate
873
- )) {
874
- if (isProviderLike(value) && !seen.has(value)) {
875
- seen.add(value);
876
- discovered.push({
877
- id: `${root}.${key}`,
878
- provider: value,
879
- sourceRoot: root
880
- });
881
- }
882
- }
883
- }
884
- }
885
- return discovered;
886
- }
887
917
  async function requestAnnouncedProviders(options) {
888
918
  if (typeof window === "undefined") return [];
889
919
  const timeoutMs = 300;
@@ -944,25 +974,6 @@ var DappSDK = class {
944
974
  }
945
975
  }
946
976
  }
947
- async registerInjectedNamespaceAdapters(discovery) {
948
- const existingIds = new Set(
949
- discovery.listAdapters().map((a) => a.providerId)
950
- );
951
- const injected = discoverInjectedProviders();
952
- for (const item of injected) {
953
- const id = `browser:${item.id}`;
954
- if (existingIds.has(id)) continue;
955
- const key = `${item.id} (injected)`;
956
- const adapter = new InjectedAdapter({
957
- id: item.id,
958
- name: key,
959
- provider: item.provider,
960
- description: `Injected provider from window.${item.id}`
961
- });
962
- discovery.registerAdapter(adapter);
963
- existingIds.add(id);
964
- }
965
- }
966
977
  async registerAnnouncedAdapters(discovery) {
967
978
  const existingIds = new Set(
968
979
  discovery.listAdapters().map((a) => a.providerId)
@@ -995,7 +1006,6 @@ var DappSDK = class {
995
1006
  } else {
996
1007
  await this.registerAdapters(this.discovery, initAdapters);
997
1008
  }
998
- await this.registerInjectedNamespaceAdapters(this.discovery);
999
1009
  await this.registerAnnouncedAdapters(this.discovery);
1000
1010
  await this.discovery.restorePersistedSessionIfNeeded();
1001
1011
  if (!this.client) {
@@ -1126,7 +1136,6 @@ var DappSDK = class {
1126
1136
  await this.init();
1127
1137
  }
1128
1138
  const discovery = this.discovery;
1129
- await this.registerInjectedNamespaceAdapters(discovery);
1130
1139
  await this.registerAnnouncedAdapters(discovery);
1131
1140
  clearAllLocalState();
1132
1141
  const entries = discovery.listAdapters().filter((a) => !this.dynamicAdapterIds.has(a.providerId)).map((a) => {
@@ -1255,6 +1264,9 @@ var DappSDK = class {
1255
1264
  async prepareExecuteAndWait(params) {
1256
1265
  return this.requireClient().prepareExecuteAndWait(params);
1257
1266
  }
1267
+ async signMessage(params) {
1268
+ return this.requireClient().signMessage(params);
1269
+ }
1258
1270
  async ledgerApi(params) {
1259
1271
  return this.requireClient().ledgerApi(params);
1260
1272
  }
@@ -1273,6 +1285,9 @@ var DappSDK = class {
1273
1285
  async onTxChanged(listener) {
1274
1286
  this.requireClient().onTxChanged(listener);
1275
1287
  }
1288
+ async onMessageSignature(listener) {
1289
+ this.requireClient().onMessageSignature(listener);
1290
+ }
1276
1291
  async removeOnStatusChanged(listener) {
1277
1292
  if (!this.client) return;
1278
1293
  this.client.removeOnStatusChanged(listener);
@@ -1289,6 +1304,10 @@ var DappSDK = class {
1289
1304
  if (!this.client) return;
1290
1305
  this.client.removeOnTxChanged(listener);
1291
1306
  }
1307
+ async removeOnMessageSignature(listener) {
1308
+ if (!this.client) return;
1309
+ this.client.removeOnMessageSignature(listener);
1310
+ }
1292
1311
  };
1293
1312
  var sdk = new DappSDK();
1294
1313
  function connect(options) {
@@ -1324,6 +1343,6 @@ function createDefaultAdapters(defaultGatewayConfigs) {
1324
1343
  );
1325
1344
  }
1326
1345
 
1327
- export { CANTON_LOGO_PNG, DappClient, DappSDK, ErrorCode, ExtensionAdapter, InjectedAdapter, RemoteAdapter, WALLET_GATEWAY_ICON, WalletConnectAdapter, connect, sdk as dappSDK, disconnect, getConnectedProvider, init, isConnected, ledgerApi, listAccounts, onAccountsChanged, onConnected, onStatusChanged, onTxChanged, open, prepareExecute, prepareExecuteAndWait, removeOnAccountsChanged, removeOnConnected, removeOnStatusChanged, removeOnTxChanged, status };
1346
+ export { CANTON_LOGO_PNG, DappClient, DappSDK, ErrorCode, ExtensionAdapter, RemoteAdapter, WALLET_GATEWAY_ICON, WalletConnectAdapter, connect, sdk as dappSDK, disconnect, getConnectedProvider, init, isConnected, ledgerApi, listAccounts, onAccountsChanged, onConnected, onStatusChanged, onTxChanged, open, prepareExecute, prepareExecuteAndWait, removeOnAccountsChanged, removeOnConnected, removeOnStatusChanged, removeOnTxChanged, status };
1328
1347
  //# sourceMappingURL=index.js.map
1329
1348
  //# sourceMappingURL=index.js.map