@xian-tech/wallet-core 0.3.7 → 0.3.8-beta.2

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.
@@ -7,6 +7,15 @@ const SAFE_CHAIN_ID_LOOKUP_TIMEOUT_MS = 2_000;
7
7
  const TRUSTED_DAPP_POLICY_TTL_MS = 30 * 24 * 60 * 60 * 1000;
8
8
  const MAX_DAPP_METADATA_TEXT_LENGTH = 120;
9
9
  const MAX_DAPP_ICON_URL_LENGTH = 2048;
10
+ const DEX_ROUTER_CONTRACT = "con_dex";
11
+ const DEX_PAIRS_CONTRACT = "con_pairs";
12
+ const DEFAULT_DEX_FEE_BPS = 30;
13
+ const ZERO_DEX_FEE_BPS = 0;
14
+ const DEX_MAX_HOPS = 3;
15
+ const DEX_REQUIRED_SWAP_EXPORTS = new Set([
16
+ "swapExactTokensForTokens",
17
+ "swapExactTokensForTokensSupportingFeeOnTransferTokens"
18
+ ]);
10
19
  function firstParamObject(params) {
11
20
  if (Array.isArray(params)) {
12
21
  return (params[0] ?? {});
@@ -108,6 +117,23 @@ function messageFromUnknown(value) {
108
117
  return String(value);
109
118
  }
110
119
  }
120
+ function numberFromUnknown(value, fallback = 0) {
121
+ if (typeof value === "number") {
122
+ return Number.isFinite(value) ? value : fallback;
123
+ }
124
+ if (typeof value === "bigint") {
125
+ return Number(value);
126
+ }
127
+ if (typeof value === "string") {
128
+ const trimmed = value.trim();
129
+ if (!trimmed) {
130
+ return fallback;
131
+ }
132
+ const parsed = Number(trimmed);
133
+ return Number.isFinite(parsed) ? parsed : fallback;
134
+ }
135
+ return fallback;
136
+ }
111
137
  function isMissingContractResult(value) {
112
138
  const message = messageFromUnknown(value);
113
139
  return /ImportError\(['"]Module\s+[^'"]+\s+not found['"]\)/i.test(message) ||
@@ -116,6 +142,30 @@ function isMissingContractResult(value) {
116
142
  function isRecord(value) {
117
143
  return typeof value === "object" && value != null;
118
144
  }
145
+ function readExportDecoratorFlag(value) {
146
+ if (typeof value === "string") {
147
+ return value === "export";
148
+ }
149
+ if (Array.isArray(value)) {
150
+ let sawDecorator = false;
151
+ for (const entry of value) {
152
+ const flag = readExportDecoratorFlag(entry);
153
+ if (flag == null) {
154
+ continue;
155
+ }
156
+ sawDecorator = true;
157
+ if (flag) {
158
+ return true;
159
+ }
160
+ }
161
+ return sawDecorator ? false : null;
162
+ }
163
+ if (isRecord(value)) {
164
+ const name = value.name ?? value.id;
165
+ return typeof name === "string" ? name === "export" : null;
166
+ }
167
+ return null;
168
+ }
119
169
  function normalizeAssetNetworkStates(value) {
120
170
  if (!isRecord(value)) {
121
171
  return {};
@@ -269,6 +319,80 @@ function normalizeConnectedDappMetadata(value, connectedOrigins) {
269
319
  }
270
320
  return metadata;
271
321
  }
322
+ function readExportedFunctionNamesFromIr(contractIr) {
323
+ if (!contractIr) {
324
+ return null;
325
+ }
326
+ let parsed;
327
+ try {
328
+ parsed = JSON.parse(contractIr);
329
+ }
330
+ catch {
331
+ return null;
332
+ }
333
+ if (!isRecord(parsed) || !Array.isArray(parsed.functions)) {
334
+ return null;
335
+ }
336
+ const exported = new Set();
337
+ let sawExportMetadata = false;
338
+ for (const entry of parsed.functions) {
339
+ if (!isRecord(entry) || typeof entry.name !== "string") {
340
+ continue;
341
+ }
342
+ if (entry.name.startsWith("__")) {
343
+ continue;
344
+ }
345
+ let isExported = false;
346
+ if (typeof entry.visibility === "string") {
347
+ sawExportMetadata = true;
348
+ isExported = entry.visibility === "export";
349
+ }
350
+ for (const decoratorValue of [entry.decorator, entry.decorators]) {
351
+ const decoratorFlag = readExportDecoratorFlag(decoratorValue);
352
+ if (decoratorFlag == null) {
353
+ continue;
354
+ }
355
+ sawExportMetadata = true;
356
+ isExported = isExported || decoratorFlag;
357
+ }
358
+ if (isExported) {
359
+ exported.add(entry.name);
360
+ }
361
+ }
362
+ return sawExportMetadata ? exported : null;
363
+ }
364
+ function readExportedFunctionNamesFromSource(source) {
365
+ if (!source) {
366
+ return null;
367
+ }
368
+ const exported = new Set();
369
+ let pendingExport = false;
370
+ for (const line of source.split(/\r?\n/)) {
371
+ const trimmed = line.trim();
372
+ if (!trimmed || trimmed.startsWith("#")) {
373
+ continue;
374
+ }
375
+ if (/^@export(?:\s*(?:\(|$))/.test(trimmed)) {
376
+ pendingExport = true;
377
+ continue;
378
+ }
379
+ if (trimmed.startsWith("@")) {
380
+ pendingExport = false;
381
+ continue;
382
+ }
383
+ const match = /^(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/.exec(trimmed);
384
+ if (match) {
385
+ const name = match[1];
386
+ if (pendingExport && !name.startsWith("__")) {
387
+ exported.add(name);
388
+ }
389
+ pendingExport = false;
390
+ continue;
391
+ }
392
+ pendingExport = false;
393
+ }
394
+ return exported;
395
+ }
272
396
  function normalizeTrackedAsset(asset) {
273
397
  return {
274
398
  contract: asset.contract.trim(),
@@ -551,6 +675,34 @@ export class WalletController {
551
675
  await this.expireUnlockedSession();
552
676
  return false;
553
677
  }
678
+ if ((!this.unlockedPrivateKey || !this.unlockedSessionKey) && session.sessionKey) {
679
+ const state = await this.loadWalletState();
680
+ if (!state || state.publicKey !== session.publicKey) {
681
+ await this.clearUnlockedSession();
682
+ return false;
683
+ }
684
+ try {
685
+ const privateKey = await decryptPrivateKeyWithSessionKey(state.encryptedPrivateKey, session.sessionKey);
686
+ const signer = new Ed25519Signer(privateKey);
687
+ if (signer.address !== session.publicKey) {
688
+ await this.clearUnlockedSession();
689
+ return false;
690
+ }
691
+ this.unlockedPrivateKey = privateKey;
692
+ this.unlockedSigner = signer;
693
+ this.unlockedSessionKey = session.sessionKey;
694
+ if (state.encryptedMnemonic) {
695
+ this.unlockedMnemonic = await decryptMnemonicWithSessionKey(state.encryptedMnemonic, session.sessionKey).catch(() => null);
696
+ }
697
+ else {
698
+ this.unlockedMnemonic = null;
699
+ }
700
+ }
701
+ catch {
702
+ await this.clearUnlockedSession();
703
+ return false;
704
+ }
705
+ }
554
706
  if (!this.unlockedPrivateKey || !this.unlockedSessionKey) {
555
707
  await this.clearUnlockedSession();
556
708
  return false;
@@ -584,7 +736,8 @@ export class WalletController {
584
736
  : resolvedExpiresAt;
585
737
  const session = {
586
738
  publicKey: this.unlockedSigner.address,
587
- expiresAt: nextExpiresAt
739
+ expiresAt: nextExpiresAt,
740
+ sessionKey: this.unlockedSessionKey
588
741
  };
589
742
  await this.store.saveUnlockedSession(session);
590
743
  this.unlockedSessionExpiresAt = nextExpiresAt;
@@ -1250,15 +1403,65 @@ export class WalletController {
1250
1403
  error: serialized
1251
1404
  };
1252
1405
  }
1406
+ async requestWithEstimatedSendCallChi(request, account) {
1407
+ if (request.method !== "xian_sendCall" || !account) {
1408
+ return request;
1409
+ }
1410
+ const firstParam = firstParamObject(request.params);
1411
+ const intent = isRecord(firstParam.intent) ? firstParam.intent : null;
1412
+ if (!intent ||
1413
+ intent.chi != null ||
1414
+ intent.chiSupplied != null ||
1415
+ typeof intent.contract !== "string" ||
1416
+ typeof intent.function !== "string") {
1417
+ return request;
1418
+ }
1419
+ const kwargs = isRecord(intent.kwargs) ? intent.kwargs : {};
1420
+ try {
1421
+ const state = this.requireStoredWallet(await this.loadWalletState());
1422
+ const estimated = await this.currentClient(state).estimateChi({
1423
+ sender: account,
1424
+ contract: intent.contract,
1425
+ function: intent.function,
1426
+ kwargs
1427
+ });
1428
+ if (!Number.isFinite(estimated.estimated) || estimated.estimated <= 0) {
1429
+ return request;
1430
+ }
1431
+ const nextFirstParam = {
1432
+ ...firstParam,
1433
+ intent: {
1434
+ ...intent,
1435
+ kwargs,
1436
+ chi: estimated.estimated
1437
+ }
1438
+ };
1439
+ return {
1440
+ ...request,
1441
+ params: Array.isArray(request.params)
1442
+ ? [nextFirstParam, ...request.params.slice(1)]
1443
+ : nextFirstParam
1444
+ };
1445
+ }
1446
+ catch {
1447
+ return request;
1448
+ }
1449
+ }
1253
1450
  async createApprovalRequest(requestState, account, chainId) {
1451
+ const request = await this.requestWithEstimatedSendCallChi(requestState.request, account);
1254
1452
  const record = {
1255
1453
  id: this.createId(),
1256
1454
  origin: requestState.origin,
1257
1455
  kind: approvalKindFromMethod(requestState.request.method),
1258
- request: requestState.request,
1456
+ request,
1259
1457
  createdAt: this.now()
1260
1458
  };
1261
- const view = buildApprovalView(record, { account, chainId });
1459
+ const chiRate = record.kind === "signTransaction" ||
1460
+ record.kind === "sendTransaction" ||
1461
+ record.kind === "sendCall"
1462
+ ? await this.getChiRate()
1463
+ : null;
1464
+ const view = buildApprovalView(record, { account, chainId, chiRate });
1262
1465
  const approval = {
1263
1466
  id: record.id,
1264
1467
  requestId: requestState.requestId,
@@ -1268,6 +1471,7 @@ export class WalletController {
1268
1471
  await this.store.saveApprovalState(approval);
1269
1472
  await this.store.saveRequestState({
1270
1473
  ...requestState,
1474
+ request,
1271
1475
  updatedAt: this.now(),
1272
1476
  status: "pending",
1273
1477
  approvalId: record.id
@@ -1618,9 +1822,184 @@ export class WalletController {
1618
1822
  });
1619
1823
  return this.sendPreparedTransaction(state, tx, { mode: "commit" });
1620
1824
  }
1825
+ async getDexSnapshot() {
1826
+ const state = this.requireStoredWallet(await this.loadWalletState());
1827
+ const client = this.currentClient(state);
1828
+ if (typeof client.getState !== "function") {
1829
+ return {
1830
+ available: false,
1831
+ contract: DEX_ROUTER_CONTRACT,
1832
+ pairsContract: DEX_PAIRS_CONTRACT,
1833
+ reason: "Current network client does not support DEX state reads.",
1834
+ tradeFeeBps: DEFAULT_DEX_FEE_BPS,
1835
+ maxHops: DEX_MAX_HOPS,
1836
+ pairs: [],
1837
+ tokens: []
1838
+ };
1839
+ }
1840
+ const methods = await this.getContractMethods(DEX_ROUTER_CONTRACT);
1841
+ const methodNames = new Set(methods.map((method) => method.name));
1842
+ const hasSwapExport = [...DEX_REQUIRED_SWAP_EXPORTS].some((name) => methodNames.has(name));
1843
+ if (!hasSwapExport) {
1844
+ return {
1845
+ available: false,
1846
+ contract: DEX_ROUTER_CONTRACT,
1847
+ pairsContract: DEX_PAIRS_CONTRACT,
1848
+ reason: `${DEX_ROUTER_CONTRACT} is not deployed on this network.`,
1849
+ tradeFeeBps: DEFAULT_DEX_FEE_BPS,
1850
+ maxHops: DEX_MAX_HOPS,
1851
+ pairs: [],
1852
+ tokens: []
1853
+ };
1854
+ }
1855
+ const pairs = await this.readDexPairs(client);
1856
+ const tokenContracts = new Set();
1857
+ for (const asset of state.watchedAssets) {
1858
+ tokenContracts.add(asset.contract);
1859
+ }
1860
+ for (const pair of pairs) {
1861
+ tokenContracts.add(pair.token0);
1862
+ tokenContracts.add(pair.token1);
1863
+ }
1864
+ const [tradeFeeBps, tokens] = await Promise.all([
1865
+ this.readDexTradeFeeBps(client, state.publicKey),
1866
+ Promise.all([...tokenContracts].map((contract) => this.readDexTokenInfo(state, client, contract)))
1867
+ ]);
1868
+ return {
1869
+ available: true,
1870
+ contract: DEX_ROUTER_CONTRACT,
1871
+ pairsContract: DEX_PAIRS_CONTRACT,
1872
+ tradeFeeBps,
1873
+ maxHops: DEX_MAX_HOPS,
1874
+ pairs,
1875
+ tokens
1876
+ };
1877
+ }
1878
+ async readDexPairs(client) {
1879
+ if (typeof client.getState !== "function") {
1880
+ return [];
1881
+ }
1882
+ const countRaw = await client
1883
+ .getState(DEX_PAIRS_CONTRACT, "pairs_num")
1884
+ .catch(() => 0);
1885
+ const count = Math.max(0, Math.floor(numberFromUnknown(countRaw)));
1886
+ if (count <= 0) {
1887
+ return [];
1888
+ }
1889
+ const pairs = await Promise.all(Array.from({ length: count }, (_, index) => this.readDexPair(client, index + 1).catch(() => null)));
1890
+ return pairs.filter((pair) => pair != null);
1891
+ }
1892
+ async readDexPair(client, id) {
1893
+ if (typeof client.getState !== "function") {
1894
+ return null;
1895
+ }
1896
+ const key = String(id);
1897
+ const [token0, token1, reserve0, reserve1, totalSupply, blockTimestampLast, creationTime] = await Promise.all([
1898
+ client.getState(DEX_PAIRS_CONTRACT, "pairs", [key, "token0"]),
1899
+ client.getState(DEX_PAIRS_CONTRACT, "pairs", [key, "token1"]),
1900
+ client.getState(DEX_PAIRS_CONTRACT, "pairs", [key, "reserve0"]),
1901
+ client.getState(DEX_PAIRS_CONTRACT, "pairs", [key, "reserve1"]),
1902
+ client.getState(DEX_PAIRS_CONTRACT, "pairs", [key, "totalSupply"]),
1903
+ client.getState(DEX_PAIRS_CONTRACT, "pairs", [key, "blockTimestampLast"]),
1904
+ client.getState(DEX_PAIRS_CONTRACT, "pairs", [key, "creationTime"])
1905
+ ]);
1906
+ if (typeof token0 !== "string" || typeof token1 !== "string") {
1907
+ return null;
1908
+ }
1909
+ return {
1910
+ id,
1911
+ token0,
1912
+ token1,
1913
+ reserve0: numberFromUnknown(reserve0),
1914
+ reserve1: numberFromUnknown(reserve1),
1915
+ totalSupply: numberFromUnknown(totalSupply),
1916
+ blockTimestampLast: blockTimestampLast == null ? null : String(blockTimestampLast),
1917
+ creationTime: creationTime == null ? null : String(creationTime)
1918
+ };
1919
+ }
1920
+ async readDexTradeFeeBps(client, account) {
1921
+ if (typeof client.call !== "function") {
1922
+ return DEFAULT_DEX_FEE_BPS;
1923
+ }
1924
+ try {
1925
+ const result = await client.call({
1926
+ sender: account,
1927
+ contract: DEX_ROUTER_CONTRACT,
1928
+ function: "getTradeFeeBps",
1929
+ kwargs: { account }
1930
+ });
1931
+ const bps = numberFromUnknown(result, DEFAULT_DEX_FEE_BPS);
1932
+ return bps === ZERO_DEX_FEE_BPS ? ZERO_DEX_FEE_BPS : DEFAULT_DEX_FEE_BPS;
1933
+ }
1934
+ catch {
1935
+ return DEFAULT_DEX_FEE_BPS;
1936
+ }
1937
+ }
1938
+ async readDexTokenInfo(state, client, contract) {
1939
+ const [metadata, precisionRaw, balanceRaw, allowanceRaw, feeOnTransferRaw] = await Promise.all([
1940
+ this.resolveTokenMetadataForState(state, contract).catch(() => ({
1941
+ contract,
1942
+ name: null,
1943
+ symbol: null,
1944
+ logoUrl: null,
1945
+ logoSvg: null
1946
+ })),
1947
+ client.getState
1948
+ ? client.getState(contract, "metadata", ["precision"]).catch(() => null)
1949
+ : Promise.resolve(null),
1950
+ client.getBalance(state.publicKey, { contract }).catch(() => 0),
1951
+ client.getState
1952
+ ? client
1953
+ .getState(contract, "approvals", [
1954
+ state.publicKey,
1955
+ DEX_ROUTER_CONTRACT
1956
+ ])
1957
+ .catch(() => 0)
1958
+ : Promise.resolve(0),
1959
+ client.getState
1960
+ ? client
1961
+ .getState(DEX_ROUTER_CONTRACT, "fee_on_transfer_tokens", [
1962
+ contract
1963
+ ])
1964
+ .catch(() => false)
1965
+ : Promise.resolve(false)
1966
+ ]);
1967
+ const watched = state.watchedAssets.find((asset) => asset.contract === contract);
1968
+ const precision = Number.isInteger(numberFromUnknown(precisionRaw, NaN))
1969
+ ? numberFromUnknown(precisionRaw)
1970
+ : typeof watched?.decimals === "number"
1971
+ ? watched.decimals
1972
+ : null;
1973
+ return {
1974
+ contract,
1975
+ name: metadata.name,
1976
+ symbol: metadata.symbol,
1977
+ logoUrl: metadata.logoUrl,
1978
+ logoSvg: metadata.logoSvg,
1979
+ precision,
1980
+ balance: numberFromUnknown(balanceRaw),
1981
+ allowance: numberFromUnknown(allowanceRaw),
1982
+ feeOnTransfer: feeOnTransferRaw === true
1983
+ };
1984
+ }
1621
1985
  async getContractMethods(contract) {
1622
1986
  const state = this.requireStoredWallet(await this.loadWalletState());
1623
- return this.currentClient(state).getContractMethods(contract);
1987
+ const client = this.currentClient(state);
1988
+ const methods = await client.getContractMethods(contract);
1989
+ let exportedNames = null;
1990
+ if (client.getContractIr) {
1991
+ const contractIr = await client.getContractIr(contract).catch(() => null);
1992
+ exportedNames = readExportedFunctionNamesFromIr(contractIr);
1993
+ }
1994
+ if (!exportedNames && client.getContractSource) {
1995
+ const contractSource = await client
1996
+ .getContractSource(contract)
1997
+ .catch(() => null);
1998
+ exportedNames = readExportedFunctionNamesFromSource(contractSource);
1999
+ }
2000
+ return exportedNames
2001
+ ? methods.filter((method) => exportedNames.has(method.name))
2002
+ : methods;
1624
2003
  }
1625
2004
  async fetchAssetBalanceSnapshot(state, assets) {
1626
2005
  const balances = {};