@hashgraph/hedera-wallet-connect 0.1.0 → 1.0.2
Sign up to get free protection for your applications and to get access to all the features.
- package/.github/ISSUE_TEMPLATE/bug_report.md +35 -0
- package/.github/ISSUE_TEMPLATE/feature_request.md +17 -0
- package/.github/ISSUE_TEMPLATE/hip_820.md +16 -0
- package/.github/dependabot.yml +17 -0
- package/.github/workflows/prettier.yml +28 -0
- package/.github/workflows/publish.yml +35 -0
- package/.github/workflows/test.yml +32 -0
- package/.husky/pre-commit +4 -0
- package/.lintstagedrc.json +5 -0
- package/.prettierignore +3 -0
- package/LICENSE +201 -21
- package/README.md +132 -107
- package/dist/browser-cjs-metafile.json +1 -0
- package/dist/browser-cjs.js +240 -0
- package/dist/browser-esm-metafile.json +1 -0
- package/dist/browser-esm.js +240 -0
- package/dist/node-cjs-metafile.json +1 -0
- package/dist/node-cjs.js +11391 -0
- package/dist/node-esm-metafile.json +1 -0
- package/dist/node-esm.js +11391 -0
- package/jest.config.ts +33 -0
- package/package.json +59 -31
- package/scripts/examples/build.mjs +54 -0
- package/scripts/examples/dev.mjs +54 -0
- package/scripts/lib/build.mjs +40 -0
- package/scripts/lib/context.mjs +71 -0
- package/scripts/lib/watch.mjs +28 -0
- package/typedoc.json +10 -0
- package/.editorconfig +0 -19
- package/.github/workflows/npm-publish.yml +0 -18
- package/lib/esm/Connector.js +0 -81
- package/lib/esm/Connector.js.map +0 -1
- package/lib/esm/DAppConnector.js +0 -118
- package/lib/esm/DAppConnector.js.map +0 -1
- package/lib/esm/ErrorHelper.js +0 -97
- package/lib/esm/ErrorHelper.js.map +0 -1
- package/lib/esm/Utils.js +0 -99
- package/lib/esm/Utils.js.map +0 -1
- package/lib/esm/WCSigner.js +0 -241
- package/lib/esm/WCSigner.js.map +0 -1
- package/lib/esm/WalletConnector.js +0 -203
- package/lib/esm/WalletConnector.js.map +0 -1
- package/lib/esm/index.js +0 -4
- package/lib/esm/index.js.map +0 -1
- package/lib/esm/types/Connector.d.ts +0 -18
- package/lib/esm/types/Connector.d.ts.map +0 -1
- package/lib/esm/types/DAppConnector.d.ts +0 -27
- package/lib/esm/types/DAppConnector.d.ts.map +0 -1
- package/lib/esm/types/ErrorHelper.d.ts +0 -15
- package/lib/esm/types/ErrorHelper.d.ts.map +0 -1
- package/lib/esm/types/Utils.d.ts +0 -39
- package/lib/esm/types/Utils.d.ts.map +0 -1
- package/lib/esm/types/WCSigner.d.ts +0 -33
- package/lib/esm/types/WCSigner.d.ts.map +0 -1
- package/lib/esm/types/WalletConnector.d.ts +0 -21
- package/lib/esm/types/WalletConnector.d.ts.map +0 -1
- package/lib/esm/types/index.d.ts +0 -4
- package/lib/esm/types/index.d.ts.map +0 -1
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"DAppConnector.js","sourceRoot":"","sources":["../../src/DAppConnector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,SAAS,EAAE,QAAQ,EAAC,MAAM,gBAAgB,CAAC;AACnD,OAAO,WAAW,MAAM,6BAA6B,CAAC;AACtD,OAAO,EAAC,UAAU,EAAC,MAAM,4BAA4B,CAAC;AAEtD,OAAO,EAAC,OAAO,EAAC,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAC,SAAS,EAAC,MAAM,gBAAgB,CAAC;AACzC,OAAO,EACL,gCAAgC,EAAE,8BAA8B,EAChE,uBAAuB,EACvB,qBAAqB,EACtB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAC,QAAQ,EAAC,MAAM,eAAe,CAAC;AACvC,OAAO,EAAC,QAAQ,EAAC,MAAM,kBAAkB,CAAC;AAS1C,MAAM,OAAO,aAAc,SAAQ,SAAS;IAClC,aAAa,GAAa,EAAE,CAAC;IAC7B,gBAAgB,GAAa,EAAE,CAAC;IACxC,MAAM,CAAC,QAAQ,CAAgB;IACxB,OAAO,GAAyB,IAAI,OAAO,EAAe,CAAC;IAElE,YAAY,QAAuB;QACjC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAChB,aAAa,CAAC,QAAQ,GAAG,IAAI,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E,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAC,EAAC,OAAO,EAAE,OAAO,EAAC,EAAE,EAAE,CAAC,IAAI,QAAQ,CAC1E,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC,EAC7B,IAAI,CAAC,MAAM,EACX,OAAO,CAAC,KAAK,EACb,OAAO,EACP,8BAA8B,CAAC,OAAO,CAAC,CACxC,CAAC,CAAA;IACJ,CAAC;IAED,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;CACF","sourcesContent":["import {AccountId, LedgerId} from \"@hashgraph/sdk\";\nimport QRCodeModal from \"@walletconnect/qrcode-modal\";\nimport {SignClient} from \"@walletconnect/sign-client\";\nimport {SessionTypes, SignClientTypes} from \"@walletconnect/types\";\nimport {Subject} from \"rxjs\";\nimport {Connector} from \"./Connector.js\";\nimport {\n getAccountLedgerPairsFromSession, getExtensionMethodsFromSession,\n getLedgerIDsFromSession,\n getRequiredNamespaces\n} from \"./Utils.js\";\nimport {WCSigner} from \"./WCSigner.js\";\nimport {HWCError} from \"./ErrorHelper.js\";\n\ntype WalletEvent = {\n name: string,\n data: any\n}\n\nexport type DAppMetadata = SignClientTypes.Metadata;\n\nexport class DAppConnector extends Connector {\n private allowedEvents: string[] = [];\n private extensionMethods: string[] = [];\n static instance: DAppConnector;\n public $events: Subject<WalletEvent> = new Subject<WalletEvent>();\n\n constructor(metadata?: DAppMetadata) {\n super(metadata);\n DAppConnector.instance = this;\n }\n\n async init(events: string[] = [], methods: string[] = []) {\n this.allowedEvents = events;\n this.extensionMethods = methods;\n try {\n this.isInitializing = true;\n this.client = await SignClient.init({\n relayUrl: \"wss://relay.walletconnect.com\",\n projectId: \"ce06497abf4102004138a10edd29c921\",\n metadata: this.dAppMetadata\n });\n this.subscribeToEvents();\n const existingSession = await this.checkPersistedState();\n if (existingSession) {\n await this.onSessionConnected(existingSession);\n }\n } finally {\n this.isInitializing = false;\n }\n }\n\n private subscribeToEvents() {\n if (!this.client) {\n throw new Error(\"WC is not initialized\");\n }\n\n this.client.on(\"session_update\", ({ topic, params }) => {\n const { namespaces } = params;\n const session = this.client!.session.get(topic);\n const updatedSession = { ...session, namespaces };\n this.onSessionConnected(updatedSession);\n });\n this.client.on(\"session_event\", ({topic, params}) => {\n if (params.chainId.includes(\"hedera:\")) {\n this.$events.next(params.event);\n }\n });\n }\n\n async connect(ledgerId: LedgerId = LedgerId.MAINNET, activeTopic?: string) {\n if (!this.client) {\n throw new Error(\"WC is not initialized\");\n }\n\n if (this.session) {\n const sessionNetworks = getLedgerIDsFromSession(this.session).map(l => l.toString());\n if (sessionNetworks.includes(ledgerId.toString())) {\n return;\n }\n }\n\n return new Promise<void>(async (resolve, reject) => {\n try {\n const requiredNamespaces = getRequiredNamespaces(ledgerId);\n requiredNamespaces.hedera.events.push(...this.allowedEvents)\n const { uri, approval } = await this.client.connect({\n pairingTopic: activeTopic,\n requiredNamespaces\n });\n\n if (uri) {\n // @ts-ignore\n QRCodeModal.open(uri, () => {\n reject(new HWCError(402, \"User rejected pairing\", {}));\n });\n }\n\n const session = await approval();\n await this.onSessionConnected(session);\n resolve();\n } catch (e: any) {\n reject(e);\n } finally {\n // @ts-ignore\n QRCodeModal.close();\n }\n });\n }\n\n async prepareConnectURI(ledgerId: LedgerId = LedgerId.MAINNET, activeTopic?: string): Promise<{\n uri?: string;\n approval: () => Promise<SessionTypes.Struct>;\n }> {\n if (!this.client) {\n throw new Error(\"WC is not initialized\");\n }\n\n if (this.session) {\n const sessionNetworks = getLedgerIDsFromSession(this.session).map(l => l.toString());\n if (sessionNetworks.includes(ledgerId.toString())) {\n return;\n }\n }\n\n const requiredNamespaces = getRequiredNamespaces(ledgerId);\n requiredNamespaces.hedera.events.push(...this.allowedEvents);\n requiredNamespaces.hedera.methods.push(...this.extensionMethods);\n return this.client.connect({\n pairingTopic: activeTopic,\n requiredNamespaces\n });\n }\n\n async onSessionConnected(session: SessionTypes.Struct) {\n const allNamespaceAccounts = getAccountLedgerPairsFromSession(session);\n this.session = session;\n this.signers = allNamespaceAccounts.map(({account, network}) => new WCSigner(\n AccountId.fromString(account),\n this.client,\n session.topic,\n network,\n getExtensionMethodsFromSession(session)\n ))\n }\n\n getSigners() {\n return this.signers;\n }\n}\n"]}
|
package/lib/esm/ErrorHelper.js
DELETED
@@ -1,97 +0,0 @@
|
|
1
|
-
export class HWCError extends Error {
|
2
|
-
code;
|
3
|
-
description;
|
4
|
-
error;
|
5
|
-
constructor(code, description, error) {
|
6
|
-
super(`HWC Error: ${description}`);
|
7
|
-
this.code = code;
|
8
|
-
this.description = description;
|
9
|
-
this.error = error;
|
10
|
-
}
|
11
|
-
}
|
12
|
-
function sleep(delay) {
|
13
|
-
return new Promise((resolve) => setTimeout(resolve, delay));
|
14
|
-
}
|
15
|
-
export const Catch = (errorType, handler, options) => {
|
16
|
-
async function handleError(ctx, errorType, handler, error) {
|
17
|
-
if (typeof handler === "function" && error instanceof errorType) {
|
18
|
-
const result = handler.call(null, error, ctx);
|
19
|
-
if (typeof result !== "undefined" && result instanceof Promise) {
|
20
|
-
return await result;
|
21
|
-
}
|
22
|
-
return result;
|
23
|
-
}
|
24
|
-
else {
|
25
|
-
switch (error.code) {
|
26
|
-
// @ts-ignore
|
27
|
-
case 402: {
|
28
|
-
throw new HWCError(402, "Signature rejected by user", error);
|
29
|
-
}
|
30
|
-
case 403:
|
31
|
-
case 423: {
|
32
|
-
throw new HWCError(403, "Wallet is closed or locked", error);
|
33
|
-
}
|
34
|
-
default: {
|
35
|
-
throw new HWCError(error.code || 500, "WalletConnect error", error);
|
36
|
-
}
|
37
|
-
}
|
38
|
-
}
|
39
|
-
}
|
40
|
-
function generateDescriptor(descriptor, errorType, handler) {
|
41
|
-
const originalMethod = descriptor.value;
|
42
|
-
descriptor.value = function (...args) {
|
43
|
-
let isRetry = false;
|
44
|
-
try {
|
45
|
-
const result = originalMethod.apply(this, args);
|
46
|
-
if (result && result instanceof Promise) {
|
47
|
-
return result.catch(async (error) => {
|
48
|
-
const canRetry = await handleError(this, errorType, handler, error);
|
49
|
-
if (options?.retry && canRetry) {
|
50
|
-
isRetry = true;
|
51
|
-
if (options.retryDelay) {
|
52
|
-
await sleep(options.retryDelay);
|
53
|
-
}
|
54
|
-
return originalMethod.apply(this, args);
|
55
|
-
}
|
56
|
-
});
|
57
|
-
}
|
58
|
-
return result;
|
59
|
-
}
|
60
|
-
catch (error) {
|
61
|
-
if (!isRetry) {
|
62
|
-
handleError(this, errorType, handler, error).then(async (canRetry) => {
|
63
|
-
if (options?.retry && canRetry) {
|
64
|
-
if (options.retryDelay) {
|
65
|
-
await sleep(options.retryDelay);
|
66
|
-
}
|
67
|
-
return originalMethod.apply(this, args);
|
68
|
-
}
|
69
|
-
});
|
70
|
-
}
|
71
|
-
else {
|
72
|
-
throw error;
|
73
|
-
}
|
74
|
-
}
|
75
|
-
};
|
76
|
-
return descriptor;
|
77
|
-
}
|
78
|
-
return (target, propertyKey, descriptor) => {
|
79
|
-
if (descriptor) {
|
80
|
-
// Method descriptor
|
81
|
-
return generateDescriptor(descriptor, errorType, handler);
|
82
|
-
}
|
83
|
-
else {
|
84
|
-
// Iterate over class properties except constructor
|
85
|
-
Reflect.ownKeys(target.prototype)
|
86
|
-
.filter(prop => prop !== "constructor")
|
87
|
-
.forEach((propertyName) => {
|
88
|
-
const desc = Object.getOwnPropertyDescriptor(target.prototype, propertyName);
|
89
|
-
if (desc.value instanceof Function) {
|
90
|
-
Object.defineProperty(target.prototype, propertyName, generateDescriptor(desc, errorType, handler));
|
91
|
-
}
|
92
|
-
});
|
93
|
-
}
|
94
|
-
};
|
95
|
-
};
|
96
|
-
export const CatchAll = (handler, options) => Catch(Error, handler, options);
|
97
|
-
//# sourceMappingURL=ErrorHelper.js.map
|
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"ErrorHelper.js","sourceRoot":"","sources":["../../src/ErrorHelper.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CAAC;6BACjC;4BACD,OAAO,cAAc,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;yBACzC;oBACH,CAAC,CAAC,CAAC;iBACJ;qBAAM;oBACL,MAAM,KAAK,CAAC;iBACb;aACF;QACH,CAAC,CAAC;QAEF,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,OAAO,CAAC,MAAW,EAAE,WAAmB,EAAE,UAA8B,EAAE,EAAE;QAC1E,IAAI,UAAU,EAAE;YACd,oBAAoB;YACpB,OAAO,kBAAkB,CAAC,UAAU,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;SAC3D;aAAM;YACL,mDAAmD;YACnD,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC;iBAC9B,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,KAAK,aAAa,CAAC;iBACtC,OAAO,CAAC,CAAC,YAAY,EAAE,EAAE;gBACxB,MAAM,IAAI,GAAG,MAAM,CAAC,wBAAwB,CAAC,MAAM,CAAC,SAAS,EAAE,YAAY,CAAE,CAAC;gBAC9E,IAAI,IAAI,CAAC,KAAK,YAAY,QAAQ,EAAE;oBAClC,MAAM,CAAC,cAAc,CACnB,MAAM,CAAC,SAAS,EAChB,YAAY,EACZ,kBAAkB,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,CAC7C,CAAC;iBACH;YACH,CAAC,CAAC,CAAC;SACN;IACH,CAAC,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,OAAwB,EAAE,OAAsB,EAAO,EAAE,CAAC,KAAK,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC","sourcesContent":["type HandlerFunction = (error: Error, ctx: any) => Promise<boolean> | boolean;\ntype CatchOptions = {\n retry?: boolean,\n retryDelay?: number\n}\n\nexport class HWCError extends Error {\n constructor(\n public readonly code: number,\n public readonly description: string,\n public readonly error: Error | {}\n ) {\n super(`HWC Error: ${description}`);\n }\n}\n\nfunction sleep(delay: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, delay));\n}\n\nexport const Catch = (errorType: any, handler: HandlerFunction, options?: CatchOptions): any => {\n async function handleError(ctx: any, errorType: any, handler: HandlerFunction, error: Error): Promise<boolean> {\n if (typeof handler === \"function\" && error instanceof errorType) {\n const result = handler.call(null, error, ctx);\n if (typeof result !== \"undefined\" && result instanceof Promise) {\n return await result;\n }\n return result;\n } else {\n switch ((error as any).code) {\n // @ts-ignore\n case 402: {\n throw new HWCError(402,\"Signature rejected by user\", error);\n }\n case 403:\n case 423: {\n throw new HWCError(403,\"Wallet is closed or locked\", error);\n }\n default: {\n throw new HWCError((error as any).code || 500,\"WalletConnect error\", error);\n }\n }\n }\n }\n\n function generateDescriptor(\n descriptor: PropertyDescriptor,\n errorType: any,\n handler: HandlerFunction\n ): PropertyDescriptor {\n const originalMethod = descriptor.value;\n\n descriptor.value = function (...args: any[]) {\n let isRetry = false;\n try {\n const result = originalMethod.apply(this, args);\n\n if (result && result instanceof Promise) {\n return result.catch(async (error: any) => {\n const canRetry = await handleError(this, errorType, handler, error);\n if (options?.retry && canRetry) {\n isRetry = true;\n if (options.retryDelay) {\n await sleep(options.retryDelay);\n }\n return originalMethod.apply(this, args);\n }\n });\n }\n\n return result;\n } catch (error: any) {\n if (!isRetry) {\n handleError(this, errorType, handler, error).then(async (canRetry) => {\n if (options?.retry && canRetry) {\n if (options.retryDelay) {\n await sleep(options.retryDelay);\n }\n return originalMethod.apply(this, args);\n }\n });\n } else {\n throw error;\n }\n }\n };\n\n return descriptor;\n }\n\n return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n if (descriptor) {\n // Method descriptor\n return generateDescriptor(descriptor, errorType, handler);\n } else {\n // Iterate over class properties except constructor\n Reflect.ownKeys(target.prototype)\n .filter(prop => prop !== \"constructor\")\n .forEach((propertyName) => {\n const desc = Object.getOwnPropertyDescriptor(target.prototype, propertyName)!;\n if (desc.value instanceof Function) {\n Object.defineProperty(\n target.prototype,\n propertyName,\n generateDescriptor(desc, errorType, handler)\n );\n }\n });\n }\n };\n};\n\nexport const CatchAll = (handler: HandlerFunction, options?: CatchOptions): any => Catch(Error, handler, options);"]}
|
package/lib/esm/Utils.js
DELETED
@@ -1,99 +0,0 @@
|
|
1
|
-
import { AccountId, LedgerId, PublicKey, SignerSignature, Transaction } from "@hashgraph/sdk";
|
2
|
-
import { Buffer } from "buffer";
|
3
|
-
const chainsMap = new Map();
|
4
|
-
chainsMap.set(LedgerId.MAINNET.toString(), 295);
|
5
|
-
chainsMap.set(LedgerId.TESTNET.toString(), 296);
|
6
|
-
chainsMap.set(LedgerId.PREVIEWNET.toString(), 297);
|
7
|
-
export var METHODS;
|
8
|
-
(function (METHODS) {
|
9
|
-
METHODS["SIGN_TRANSACTION"] = "signTransaction";
|
10
|
-
METHODS["CALL"] = "call";
|
11
|
-
METHODS["GET_ACCOUNT_BALANCE"] = "getAccountBalance";
|
12
|
-
METHODS["GET_ACCOUNT_INFO"] = "getAccountInfo";
|
13
|
-
METHODS["GET_LEDGER_ID"] = "getLedgerId";
|
14
|
-
METHODS["GET_ACCOUNT_ID"] = "getAccountId";
|
15
|
-
METHODS["GET_ACCOUNT_KEY"] = "getAccountKey";
|
16
|
-
METHODS["GET_NETWORK"] = "getNetwork";
|
17
|
-
METHODS["GET_MIRROR_NETWORK"] = "getMirrorNetwork";
|
18
|
-
METHODS["SIGN"] = "sign";
|
19
|
-
METHODS["GET_ACCOUNT_RECORDS"] = "getAccountRecords";
|
20
|
-
METHODS["CHECK_TRANSACTION"] = "checkTransaction";
|
21
|
-
METHODS["POPULATE_TRANSACTION"] = "populateTransaction";
|
22
|
-
})(METHODS || (METHODS = {}));
|
23
|
-
export var EVENTS;
|
24
|
-
(function (EVENTS) {
|
25
|
-
EVENTS["ACCOUNTS_CHANGED"] = "accountsChanged";
|
26
|
-
})(EVENTS || (EVENTS = {}));
|
27
|
-
export const getChainByLedgerId = (ledgerId) => {
|
28
|
-
return `hedera:${chainsMap.get(ledgerId.toString())}`;
|
29
|
-
};
|
30
|
-
export const getLedgerIdByChainId = (chainId) => {
|
31
|
-
const ledgerIdsMap = Object.fromEntries(Array.from(chainsMap.entries()).map(a => a.reverse()));
|
32
|
-
return ledgerIdsMap[parseInt(chainId)];
|
33
|
-
};
|
34
|
-
export const getRequiredNamespaces = (ledgerId) => {
|
35
|
-
return {
|
36
|
-
hedera: {
|
37
|
-
chains: [getChainByLedgerId(ledgerId)],
|
38
|
-
methods: Object.values(METHODS),
|
39
|
-
events: Object.values(EVENTS),
|
40
|
-
}
|
41
|
-
};
|
42
|
-
};
|
43
|
-
export const getLedgerIDsFromSession = (session) => {
|
44
|
-
return Object.values(session?.namespaces || {})
|
45
|
-
.flatMap(namespace => namespace.accounts.map(acc => {
|
46
|
-
const [network, chainId, account] = acc.split(":");
|
47
|
-
return LedgerId.fromString(getLedgerIdByChainId(chainId));
|
48
|
-
}));
|
49
|
-
};
|
50
|
-
export const getAccountLedgerPairsFromSession = (session) => {
|
51
|
-
return Object.values(session?.namespaces || {})
|
52
|
-
.flatMap(namespace => namespace.accounts.map(acc => {
|
53
|
-
const [network, chainId, account] = acc.split(":");
|
54
|
-
return { network: LedgerId.fromString(getLedgerIdByChainId(chainId)), account };
|
55
|
-
}));
|
56
|
-
};
|
57
|
-
export const getExtensionMethodsFromSession = (session) => {
|
58
|
-
return Object.values(session.namespaces)
|
59
|
-
.flatMap(ns => ns.methods)
|
60
|
-
.filter(method => !Object.values(METHODS).includes(method));
|
61
|
-
};
|
62
|
-
export const isEncodable = (obj) => {
|
63
|
-
return ("toBytes" in obj) &&
|
64
|
-
(typeof obj.toBytes === "function");
|
65
|
-
};
|
66
|
-
export const isTransaction = (obj) => {
|
67
|
-
if (obj instanceof Transaction) {
|
68
|
-
return true;
|
69
|
-
}
|
70
|
-
else if ("transactionId" in obj && "sign" in obj) {
|
71
|
-
return true;
|
72
|
-
}
|
73
|
-
return false;
|
74
|
-
};
|
75
|
-
export const evmAddressFromObject = (data) => {
|
76
|
-
try {
|
77
|
-
return Buffer.from(Object.values(data?._bytes || [])).toString("hex");
|
78
|
-
}
|
79
|
-
catch {
|
80
|
-
return null;
|
81
|
-
}
|
82
|
-
};
|
83
|
-
export const publicKeyFromObject = (data) => {
|
84
|
-
try {
|
85
|
-
return PublicKey.fromBytes(Buffer.from(Object.values(data?._key?._key?._keyData || [])));
|
86
|
-
}
|
87
|
-
catch {
|
88
|
-
return null;
|
89
|
-
}
|
90
|
-
};
|
91
|
-
export const convertToSignerSignature = (data) => {
|
92
|
-
const publicKey = publicKeyFromObject(data.publicKey);
|
93
|
-
const { shard, realm, num, aliasKey, aliasEvmAddress } = data.accountId;
|
94
|
-
const accountAddress = evmAddressFromObject(aliasEvmAddress) || publicKeyFromObject(aliasKey) || num.low;
|
95
|
-
const accountId = AccountId.fromString(`${shard.low}.${realm.low}.${accountAddress.toString()}`);
|
96
|
-
const signature = Buffer.from(Object.values(data.signature.data || data.signature));
|
97
|
-
return new SignerSignature({ accountId, signature, publicKey });
|
98
|
-
};
|
99
|
-
//# sourceMappingURL=Utils.js.map
|
package/lib/esm/Utils.js.map
DELETED
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"Utils.js","sourceRoot":"","sources":["../../src/Utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAE5F,OAAO,EAAC,MAAM,EAAC,MAAM,QAAQ,CAAC;AAE9B,MAAM,SAAS,GAAG,IAAI,GAAG,EAAE,CAAC;AAC5B,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,GAAG,CAAC,CAAC;AAChD,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,GAAG,CAAC,CAAC;AAChD,SAAS,CAAC,GAA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I,EAAmB,EAAE;IAChE,MAAM,SAAS,GAAG,mBAAmB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACtD,MAAM,EAAC,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,eAAe,EAAC,GAAG,IAAI,CAAC,SAAS,CAAC;IACtE,MAAM,cAAc,GAAG,oBAAoB,CAAC,eAAe,CAAC,IAAI,mBAAmB,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC;IACzG,MAAM,SAAS,GAAG,SAAS,CAAC,UAAU,CAAC,GAAG,KAAK,CAAC,GAAG,IAAI,KAAK,CAAC,GAAG,IAAI,cAAc,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IACjG,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,IAAI,IAAI,CAAC,SAAS,CAAO,CAAC,CAAC;IAC1F,OAAO,IAAI,eAAe,CAAC,EAAC,SAAS,EAAE,SAAS,EAAE,SAAS,EAAC,CAAC,CAAC;AAChE,CAAC,CAAA","sourcesContent":["import {AccountId, LedgerId, PublicKey, SignerSignature, Transaction} from \"@hashgraph/sdk\";\nimport {ProposalTypes, SessionTypes} from \"@walletconnect/types\";\nimport {Buffer} from \"buffer\";\n\nconst chainsMap = new Map();\nchainsMap.set(LedgerId.MAINNET.toString(), 295);\nchainsMap.set(LedgerId.TESTNET.toString(), 296);\nchainsMap.set(LedgerId.PREVIEWNET.toString(), 297);\n\nexport enum METHODS {\n SIGN_TRANSACTION = \"signTransaction\",\n CALL = \"call\",\n GET_ACCOUNT_BALANCE = \"getAccountBalance\",\n GET_ACCOUNT_INFO = \"getAccountInfo\",\n GET_LEDGER_ID = \"getLedgerId\",\n GET_ACCOUNT_ID = \"getAccountId\",\n GET_ACCOUNT_KEY = \"getAccountKey\",\n GET_NETWORK = \"getNetwork\",\n GET_MIRROR_NETWORK = \"getMirrorNetwork\",\n SIGN = \"sign\",\n GET_ACCOUNT_RECORDS = \"getAccountRecords\",\n CHECK_TRANSACTION = \"checkTransaction\",\n POPULATE_TRANSACTION = \"populateTransaction\"\n}\n\nexport enum EVENTS {\n ACCOUNTS_CHANGED = \"accountsChanged\",\n}\n\nexport const getChainByLedgerId = (ledgerId: LedgerId): string => {\n return `hedera:${chainsMap.get(ledgerId.toString())}`;\n}\n\nexport const getLedgerIdByChainId = (chainId: string): string => {\n const ledgerIdsMap = Object.fromEntries(Array.from(chainsMap.entries()).map(a => a.reverse()));\n return ledgerIdsMap[parseInt(chainId)];\n};\n\nexport const getRequiredNamespaces = (ledgerId: LedgerId): ProposalTypes.RequiredNamespaces => {\n return {\n hedera: {\n chains: [getChainByLedgerId(ledgerId)],\n methods: Object.values(METHODS),\n events: Object.values(EVENTS),\n }\n };\n};\n\nexport const getLedgerIDsFromSession = (session: SessionTypes.Struct): LedgerId[] => {\n return Object.values(session?.namespaces || {})\n .flatMap(namespace => namespace.accounts.map(acc => {\n const [network, chainId, account] = acc.split(\":\");\n return LedgerId.fromString(getLedgerIdByChainId(chainId));\n }));\n};\nexport const getAccountLedgerPairsFromSession = (session: SessionTypes.Struct): {network: LedgerId, account: string}[] => {\n return Object.values(session?.namespaces || {})\n .flatMap(namespace => namespace.accounts.map(acc => {\n const [network, chainId, account] = acc.split(\":\");\n return {network: LedgerId.fromString(getLedgerIdByChainId(chainId)), account};\n }));\n};\n\nexport const getExtensionMethodsFromSession = (session: SessionTypes.Struct): string[] => {\n return Object.values(session.namespaces)\n .flatMap(ns => ns.methods)\n .filter(method => !Object.values(METHODS).includes(method as any));\n}\n\ntype Encodable = {\n toBytes(): Uint8Array\n}\n\nexport const isEncodable = (obj: any): obj is Encodable => {\n return (\"toBytes\" in obj) &&\n (typeof (obj as Encodable).toBytes === \"function\");\n};\n\nexport const isTransaction = (obj: any): obj is Transaction => {\n if (obj instanceof Transaction) {\n return true;\n } else if (\"transactionId\" in obj && \"sign\" in obj) {\n return true;\n }\n return false;\n};\n\nexport const evmAddressFromObject = (data): string | null => {\n try {\n return Buffer.from(Object.values(data?._bytes || []) as number[]).toString(\"hex\");\n } catch {\n return null;\n }\n}\n\nexport const publicKeyFromObject = (data): PublicKey | null => {\n try {\n return PublicKey.fromBytes(Buffer.from(Object.values(data?._key?._key?._keyData || []) as number[]));\n } catch {\n return null;\n }\n}\n\nexport const convertToSignerSignature = (data): SignerSignature => {\n const publicKey = publicKeyFromObject(data.publicKey);\n const {shard, realm, num, aliasKey, aliasEvmAddress} = data.accountId;\n const accountAddress = evmAddressFromObject(aliasEvmAddress) || publicKeyFromObject(aliasKey) || num.low;\n const accountId = AccountId.fromString(`${shard.low}.${realm.low}.${accountAddress.toString()}`);\n const signature = Buffer.from(Object.values(data.signature.data || data.signature) as []);\n return new SignerSignature({accountId, signature, publicKey});\n}\n"]}
|
package/lib/esm/WCSigner.js
DELETED
@@ -1,241 +0,0 @@
|
|
1
|
-
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
2
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
3
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
4
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
5
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
6
|
-
};
|
7
|
-
import { AccountId, LedgerId, Transaction, TransactionId, TransactionResponse } from "@hashgraph/sdk";
|
8
|
-
import { Buffer } from "buffer";
|
9
|
-
import { convertToSignerSignature, getChainByLedgerId, isEncodable, isTransaction, METHODS } from "./Utils.js";
|
10
|
-
import { CatchAll, HWCError } from "./ErrorHelper.js";
|
11
|
-
import { DAppConnector } from "./DAppConnector.js";
|
12
|
-
import { catchError, defer, delay, filter, from, lastValueFrom, takeUntil, throwIfEmpty, timeout } from "rxjs";
|
13
|
-
const handleSignerError = async (error, signer) => {
|
14
|
-
try {
|
15
|
-
const existingSession = await DAppConnector.instance.checkPersistedState();
|
16
|
-
if (existingSession) {
|
17
|
-
await DAppConnector.instance.onSessionConnected(existingSession);
|
18
|
-
}
|
19
|
-
else {
|
20
|
-
const pairing = signer.client.pairing.getAll({ active: true }).pop();
|
21
|
-
await DAppConnector.instance.connect(signer.getLedgerId(), pairing?.topic);
|
22
|
-
}
|
23
|
-
}
|
24
|
-
catch (e) {
|
25
|
-
try {
|
26
|
-
await DAppConnector.instance.disconnect();
|
27
|
-
}
|
28
|
-
finally {
|
29
|
-
await DAppConnector.instance.connect(signer.getLedgerId());
|
30
|
-
}
|
31
|
-
}
|
32
|
-
return true;
|
33
|
-
};
|
34
|
-
/**
|
35
|
-
* Implements Hedera Signer interface.
|
36
|
-
* https://hips.hedera.com/hip/hip-338
|
37
|
-
*/
|
38
|
-
let WCSigner = class WCSigner {
|
39
|
-
accountId;
|
40
|
-
client;
|
41
|
-
topic;
|
42
|
-
ledgerId;
|
43
|
-
extensionMethods;
|
44
|
-
constructor(accountId, client, topic, ledgerId = LedgerId.MAINNET, extensionMethods = []) {
|
45
|
-
this.accountId = accountId;
|
46
|
-
this.client = client;
|
47
|
-
this.topic = topic;
|
48
|
-
this.ledgerId = ledgerId;
|
49
|
-
this.extensionMethods = extensionMethods;
|
50
|
-
this.extensionMethods
|
51
|
-
.filter(method => !Object.values(METHODS).includes(method))
|
52
|
-
.forEach(method => {
|
53
|
-
this[method] = (...args) => this.extensionMethodCall(method, args);
|
54
|
-
});
|
55
|
-
}
|
56
|
-
wrappedRequest(params) {
|
57
|
-
const cancelWithPing$ = defer(() => this.client.ping({ topic: this.topic }))
|
58
|
-
.pipe(delay(5000), timeout(10000), catchError(async () => true), filter(error => !!error));
|
59
|
-
return lastValueFrom(from(this.client.request(params))
|
60
|
-
.pipe(takeUntil(cancelWithPing$), throwIfEmpty(() => new HWCError(403, "Wallet is closed or locked", {}))));
|
61
|
-
}
|
62
|
-
getAccountId() {
|
63
|
-
return this.accountId;
|
64
|
-
}
|
65
|
-
async getAccountKey() {
|
66
|
-
return this.wrappedRequest({
|
67
|
-
topic: this.topic,
|
68
|
-
request: {
|
69
|
-
method: "getAccountKey",
|
70
|
-
params: {
|
71
|
-
accountId: this.accountId.toString()
|
72
|
-
}
|
73
|
-
},
|
74
|
-
chainId: getChainByLedgerId(this.ledgerId)
|
75
|
-
});
|
76
|
-
}
|
77
|
-
getLedgerId() {
|
78
|
-
return this.ledgerId;
|
79
|
-
}
|
80
|
-
async getNetwork() {
|
81
|
-
return this.wrappedRequest({
|
82
|
-
topic: this.topic,
|
83
|
-
request: {
|
84
|
-
method: "getNetwork",
|
85
|
-
params: {
|
86
|
-
accountId: this.accountId.toString()
|
87
|
-
}
|
88
|
-
},
|
89
|
-
chainId: getChainByLedgerId(this.ledgerId)
|
90
|
-
});
|
91
|
-
}
|
92
|
-
async getMirrorNetwork() {
|
93
|
-
return this.wrappedRequest({
|
94
|
-
topic: this.topic,
|
95
|
-
request: {
|
96
|
-
method: "getMirrorNetwork",
|
97
|
-
params: {
|
98
|
-
accountId: this.accountId.toString()
|
99
|
-
}
|
100
|
-
},
|
101
|
-
chainId: getChainByLedgerId(this.ledgerId)
|
102
|
-
});
|
103
|
-
}
|
104
|
-
async sign(messages, signOptions) {
|
105
|
-
const result = await this.wrappedRequest({
|
106
|
-
topic: this.topic,
|
107
|
-
request: {
|
108
|
-
method: "sign",
|
109
|
-
params: {
|
110
|
-
accountId: this.accountId.toString(),
|
111
|
-
messages: messages.map(message => Buffer.from(message).toString("base64")),
|
112
|
-
signOptions
|
113
|
-
}
|
114
|
-
},
|
115
|
-
chainId: getChainByLedgerId(this.ledgerId)
|
116
|
-
});
|
117
|
-
return Promise.resolve(result.map(r => convertToSignerSignature(r)));
|
118
|
-
}
|
119
|
-
async extensionMethodCall(name, args) {
|
120
|
-
const result = await this.wrappedRequest({
|
121
|
-
topic: this.topic,
|
122
|
-
request: {
|
123
|
-
method: name,
|
124
|
-
params: {
|
125
|
-
args,
|
126
|
-
accountId: this.accountId.toString()
|
127
|
-
}
|
128
|
-
},
|
129
|
-
chainId: getChainByLedgerId(this.ledgerId)
|
130
|
-
});
|
131
|
-
return Promise.resolve(result);
|
132
|
-
}
|
133
|
-
getAccountBalance() {
|
134
|
-
return this.wrappedRequest({
|
135
|
-
topic: this.topic,
|
136
|
-
request: {
|
137
|
-
method: "getAccountBalance",
|
138
|
-
params: {
|
139
|
-
accountId: this.accountId.toString()
|
140
|
-
}
|
141
|
-
},
|
142
|
-
chainId: getChainByLedgerId(this.ledgerId)
|
143
|
-
});
|
144
|
-
}
|
145
|
-
getAccountInfo() {
|
146
|
-
return this.wrappedRequest({
|
147
|
-
topic: this.topic,
|
148
|
-
request: {
|
149
|
-
method: "getAccountInfo",
|
150
|
-
params: {
|
151
|
-
accountId: this.accountId.toString()
|
152
|
-
}
|
153
|
-
},
|
154
|
-
chainId: getChainByLedgerId(this.ledgerId)
|
155
|
-
});
|
156
|
-
}
|
157
|
-
getAccountRecords() {
|
158
|
-
return this.wrappedRequest({
|
159
|
-
topic: this.topic,
|
160
|
-
request: {
|
161
|
-
method: "getAccountRecords",
|
162
|
-
params: {
|
163
|
-
accountId: this.accountId.toString()
|
164
|
-
}
|
165
|
-
},
|
166
|
-
chainId: getChainByLedgerId(this.ledgerId)
|
167
|
-
});
|
168
|
-
}
|
169
|
-
async signTransaction(transaction) {
|
170
|
-
const encodedTransaction = await this.wrappedRequest({
|
171
|
-
topic: this.topic,
|
172
|
-
request: {
|
173
|
-
method: "signTransaction",
|
174
|
-
params: {
|
175
|
-
accountId: this.accountId.toString(),
|
176
|
-
executable: Buffer.from(transaction.toBytes()).toString("base64")
|
177
|
-
}
|
178
|
-
},
|
179
|
-
chainId: getChainByLedgerId(this.ledgerId)
|
180
|
-
});
|
181
|
-
return Transaction.fromBytes(Buffer.from(encodedTransaction, "base64"));
|
182
|
-
}
|
183
|
-
async checkTransaction(transaction) {
|
184
|
-
const transactionId = transaction.transactionId;
|
185
|
-
if (transactionId != null &&
|
186
|
-
transactionId.accountId != null &&
|
187
|
-
transactionId.accountId.compare(this.accountId) !== 0) {
|
188
|
-
throw new Error("transaction's ID constructed with a different account ID");
|
189
|
-
}
|
190
|
-
const nodeAccountIds = (transaction.nodeAccountIds != null ? transaction.nodeAccountIds : []).map((nodeAccountId) => nodeAccountId.toString());
|
191
|
-
const network = Object.values(await this.getNetwork()).map((nodeAccountId) => nodeAccountId.toString());
|
192
|
-
if (!nodeAccountIds.reduce((previous, current) => previous && network.includes(current), true)) {
|
193
|
-
throw new Error("Transaction already set node account IDs to values not within the current network");
|
194
|
-
}
|
195
|
-
return Promise.resolve(transaction);
|
196
|
-
}
|
197
|
-
async populateTransaction(transaction) {
|
198
|
-
transaction.setTransactionId(TransactionId.generate(this.accountId));
|
199
|
-
const network = Object.values(await this.getNetwork()).map((nodeAccountId) => typeof nodeAccountId === "string"
|
200
|
-
? AccountId.fromString(nodeAccountId)
|
201
|
-
: new AccountId(nodeAccountId));
|
202
|
-
transaction.setNodeAccountIds(network);
|
203
|
-
return Promise.resolve(transaction);
|
204
|
-
}
|
205
|
-
async call(request) {
|
206
|
-
if (!isEncodable(request)) {
|
207
|
-
throw new Error("Argument is not executable");
|
208
|
-
}
|
209
|
-
const isTransactionType = isTransaction(request);
|
210
|
-
const result = await this.wrappedRequest({
|
211
|
-
topic: this.topic,
|
212
|
-
request: {
|
213
|
-
method: "call",
|
214
|
-
params: {
|
215
|
-
accountId: this.accountId.toString(),
|
216
|
-
executable: Buffer.from(request.toBytes()).toString("base64"),
|
217
|
-
isTransaction: isTransactionType
|
218
|
-
}
|
219
|
-
},
|
220
|
-
chainId: getChainByLedgerId(this.ledgerId)
|
221
|
-
});
|
222
|
-
if (result.error) {
|
223
|
-
throw new Error(result.error);
|
224
|
-
}
|
225
|
-
if (!isTransactionType) {
|
226
|
-
// @ts-ignore
|
227
|
-
const responseTypeName = request.constructor.name.replace(/Query$/, "");
|
228
|
-
const output = await import("@hashgraph/sdk").then((module) => module[responseTypeName]);
|
229
|
-
const bytes = Buffer.from(result, "base64");
|
230
|
-
return output.fromBytes(bytes);
|
231
|
-
}
|
232
|
-
else {
|
233
|
-
return TransactionResponse.fromJSON(result);
|
234
|
-
}
|
235
|
-
}
|
236
|
-
};
|
237
|
-
WCSigner = __decorate([
|
238
|
-
CatchAll(handleSignerError, { retry: true, retryDelay: 1000 })
|
239
|
-
], WCSigner);
|
240
|
-
export { WCSigner };
|
241
|
-
//# sourceMappingURL=WCSigner.js.map
|
package/lib/esm/WCSigner.js.map
DELETED
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"WCSigner.js","sourceRoot":"","sources":["../../src/WCSigner.ts"],"names":[],"mappings":";;;;;;AACA,OAAO,EAEL,SAAS,EAIT,QAAQ,EAER,WAAW,EACX,aAAa,EACM,mBAAmB,EACvC,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAC,MAAM,EAAC,MAAM,QAAQ,CAAC;AAC9B,OAAO,EACL,wBAAwB,EACxB,kBAAkB,EAClB,WAAW,EACX,aAAa,EACb,OAAO,EACR,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAC,aAAa,EAAC,MAAM,oBAAoB,CAAC;AACjD,OAAO,EACL,UAAU,EACV,KAAK,EACL,KAAK,EAAE,MAAM,EACb,IAAI,EACJ,aAAa,EACb,SAAS,EAAE,YAAY,EACvB,OAAO,EACR,MAAM,MAAM,CAAC;AAEd,MAAM,iBAAiB,GAAG,KAAK,EAAE,KAAU,EAAE,MAAc,EAAE,EAAE;IAC7D,IAAI;QACF,MAAM,eAAe,GAAG,MAAM,aAAa,CAAC,QAAQ,CAAC,mBAAmB,EAAE,CAAC;QAC3E,IAAI,eAAe,EAAE;YACnB,MAAM,aAAa,CAAC,QAAQ,CAAC,kBAAkB,CAAC,e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,QAAQ,CAAC,QAAQ,CAAC;oBAC7D,aAAa,EAAE,iBAAiB;iBACjC;aACF;YACD,OAAO,EAAE,kBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC;SAC3C,CAAC,CAAA;QAEF,IAAI,MAAM,CAAC,KAAK,EAAE;YAChB,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;SAC/B;QAED,IAAI,CAAC,iBAAiB,EAAE;YACtB,aAAa;YACb,MAAM,gBAAgB,GAAG,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YACxE,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,gBAAgB,CAAC,CAAC,IAAI,CAAC,CAAC,MAAW,EAAE,EAAE,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC;YAC9F,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC5C,OAAO,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;SAChC;aAAM;YACL,OAAO,mBAAmB,CAAC,QAAQ,CAAC,MAAM,CAAuB,CAAC;SACnE;IACH,CAAC;CACF,CAAA;AAnPY,QAAQ;IADpB,QAAQ,CAAC,iBAAiB,EAAE,EAAC,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAC,CAAC;GAChD,QAAQ,CAmPpB;SAnPY,QAAQ","sourcesContent":["import type {Signer} from '@hashgraph/sdk';\nimport {\n AccountBalance,\n AccountId,\n AccountInfo,\n Executable,\n Key,\n LedgerId,\n SignerSignature,\n Transaction,\n TransactionId,\n TransactionRecord, TransactionResponse\n} from \"@hashgraph/sdk\";\nimport {ISignClient} from \"@walletconnect/types\";\nimport {Buffer} from \"buffer\";\nimport {\n convertToSignerSignature,\n getChainByLedgerId,\n isEncodable,\n isTransaction,\n METHODS\n} from \"./Utils.js\";\nimport { CatchAll, HWCError } from \"./ErrorHelper.js\";\nimport {DAppConnector} from \"./DAppConnector.js\";\nimport {\n catchError,\n defer,\n delay, filter,\n from,\n lastValueFrom,\n takeUntil, throwIfEmpty,\n timeout\n} from \"rxjs\";\n\nconst handleSignerError = async (error: any, signer: Signer) => {\n try {\n const existingSession = await DAppConnector.instance.checkPersistedState();\n if (existingSession) {\n await DAppConnector.instance.onSessionConnected(existingSession);\n } else {\n const pairing = signer.client.pairing.getAll({active: true}).pop();\n await DAppConnector.instance.connect(signer.getLedgerId(), pairing?.topic);\n }\n } catch (e) {\n try {\n await DAppConnector.instance.disconnect();\n } finally {\n await DAppConnector.instance.connect(signer.getLedgerId())\n }\n }\n\n return true;\n};\n\n/**\n * Implements Hedera Signer interface.\n * https://hips.hedera.com/hip/hip-338\n */\n@CatchAll(handleSignerError, {retry: true, retryDelay: 1000})\nexport class WCSigner implements Signer {\n constructor(\n private readonly accountId: AccountId,\n private readonly client: ISignClient,\n private readonly topic: string,\n private readonly ledgerId: LedgerId = LedgerId.MAINNET,\n private extensionMethods: string[] = []\n ) {\n this.extensionMethods\n .filter(method => !Object.values(METHODS).includes(method as any))\n .forEach(method => {\n this[method] = (...args: any[]) => this.extensionMethodCall(method, args);\n });\n }\n\n private wrappedRequest<T>(params): Promise<T> {\n const cancelWithPing$ = defer(() => this.client!.ping({topic: this.topic}))\n .pipe(\n delay(5000),\n timeout(10000),\n catchError(async () => true),\n filter(error => !!error)\n );\n return lastValueFrom<T>(\n from(this.client.request<T>(params))\n .pipe(\n takeUntil(cancelWithPing$),\n throwIfEmpty(() => new HWCError(403,\"Wallet is closed or locked\", {}))\n )\n );\n }\n\n getAccountId(): AccountId {\n return this.accountId;\n }\n\n async getAccountKey(): Promise<Key> {\n return this.wrappedRequest<Key>({\n topic: this.topic,\n request: {\n method: \"getAccountKey\",\n params: {\n accountId: this.accountId.toString()\n }\n },\n chainId: getChainByLedgerId(this.ledgerId)\n });\n }\n\n getLedgerId(): LedgerId {\n return this.ledgerId;\n }\n\n async getNetwork(): Promise<{[key: string]: (string | AccountId)}> {\n return this.wrappedRequest<{[key: string]: (string | AccountId)}>({\n topic: this.topic,\n request: {\n method: \"getNetwork\",\n params: {\n accountId: this.accountId.toString()\n }\n },\n chainId: getChainByLedgerId(this.ledgerId)\n });\n }\n\n async getMirrorNetwork(): Promise<string[]> {\n return this.wrappedRequest<string[]>({\n topic: this.topic,\n request: {\n method: \"getMirrorNetwork\",\n params: {\n accountId: this.accountId.toString()\n }\n },\n chainId: getChainByLedgerId(this.ledgerId)\n });\n }\n\n async sign(messages: Uint8Array[], signOptions?: Record<string, any>): Promise<SignerSignature[]> {\n const result = await this.wrappedRequest<SignerSignature[]>({\n topic: this.topic,\n request: {\n method: \"sign\",\n params: {\n accountId: this.accountId.toString(),\n messages: messages.map(message => Buffer.from(message).toString(\"base64\")),\n signOptions\n }\n },\n chainId: getChainByLedgerId(this.ledgerId)\n });\n\n return Promise.resolve(result.map(r => convertToSignerSignature(r)));\n }\n\n private async extensionMethodCall<T>(name, args: Record<any, any>): Promise<T> {\n const result = await this.wrappedRequest<T>({\n topic: this.topic,\n request: {\n method: name,\n params: {\n args,\n accountId: this.accountId.toString()\n }\n },\n chainId: getChainByLedgerId(this.ledgerId)\n })\n return Promise.resolve(result);\n }\n\n getAccountBalance(): Promise<AccountBalance> {\n return this.wrappedRequest<AccountBalance>({\n topic: this.topic,\n request: {\n method: \"getAccountBalance\",\n params: {\n accountId: this.accountId.toString()\n }\n },\n chainId: getChainByLedgerId(this.ledgerId)\n });\n }\n\n getAccountInfo(): Promise<AccountInfo> {\n return this.wrappedRequest<AccountInfo>({\n topic: this.topic,\n request: {\n method: \"getAccountInfo\",\n params: {\n accountId: this.accountId.toString()\n }\n },\n chainId: getChainByLedgerId(this.ledgerId)\n });\n }\n\n getAccountRecords(): Promise<TransactionRecord[]> {\n return this.wrappedRequest<TransactionRecord[]>({\n topic: this.topic,\n request: {\n method: \"getAccountRecords\",\n params: {\n accountId: this.accountId.toString()\n }\n },\n chainId: getChainByLedgerId(this.ledgerId)\n });\n }\n\n async signTransaction<T extends Transaction>(transaction: T): Promise<T> {\n const encodedTransaction = await this.wrappedRequest<string>({\n topic: this.topic,\n request: {\n method: \"signTransaction\",\n params: {\n accountId: this.accountId.toString(),\n executable: Buffer.from(transaction.toBytes()).toString(\"base64\")\n }\n },\n chainId: getChainByLedgerId(this.ledgerId)\n });\n\n return Transaction.fromBytes(Buffer.from(encodedTransaction, \"base64\")) as T;\n }\n\n async checkTransaction<T extends Transaction>(transaction: T): Promise<T> {\n const transactionId = transaction.transactionId;\n if (\n transactionId != null &&\n transactionId.accountId != null &&\n transactionId.accountId.compare(this.accountId) !== 0\n ) {\n throw new Error(\n \"transaction's ID constructed with a different account ID\"\n );\n }\n\n const nodeAccountIds = (\n transaction.nodeAccountIds != null ? transaction.nodeAccountIds : []\n ).map((nodeAccountId) => nodeAccountId.toString());\n const network = Object.values(await this.getNetwork()).map(\n (nodeAccountId) => nodeAccountId.toString()\n );\n\n if (\n !nodeAccountIds.reduce(\n (previous, current) => previous && network.includes(current),\n true\n )\n ) {\n throw new Error(\n \"Transaction already set node account IDs to values not within the current network\"\n );\n }\n\n return Promise.resolve(transaction);\n }\n\n async populateTransaction<T extends Transaction>(transaction: T): Promise<T> {\n transaction.setTransactionId(TransactionId.generate(this.accountId));\n const network = Object.values(await this.getNetwork()).map(\n (nodeAccountId) =>\n typeof nodeAccountId === \"string\"\n ? AccountId.fromString(nodeAccountId)\n : new AccountId(nodeAccountId)\n );\n transaction.setNodeAccountIds(network);\n return Promise.resolve(transaction);\n }\n\n async call<RequestT, ResponseT, OutputT>(request: Executable<RequestT, ResponseT, OutputT>): Promise<OutputT> {\n if (!isEncodable(request)) {\n throw new Error(\"Argument is not executable\");\n }\n const isTransactionType = isTransaction(request);\n const result = await this.wrappedRequest<any>({\n topic: this.topic,\n request: {\n method: \"call\",\n params: {\n accountId: this.accountId.toString(),\n executable: Buffer.from(request.toBytes()).toString(\"base64\"),\n isTransaction: isTransactionType\n }\n },\n chainId: getChainByLedgerId(this.ledgerId)\n })\n\n if (result.error) {\n throw new Error(result.error);\n }\n\n if (!isTransactionType) {\n // @ts-ignore\n const responseTypeName = request.constructor.name.replace(/Query$/, \"\");\n const output = await import(\"@hashgraph/sdk\").then((module: any) => module[responseTypeName]);\n const bytes = Buffer.from(result, \"base64\");\n return output.fromBytes(bytes);\n } else {\n return TransactionResponse.fromJSON(result) as unknown as OutputT;\n }\n }\n}\n"]}
|