@hashgraph/hedera-wallet-connect 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- package/.editorconfig +19 -0
- package/.github/workflows/npm-publish.yml +18 -0
- package/LICENSE +21 -0
- package/README.md +119 -0
- package/lib/esm/Connector.js +81 -0
- package/lib/esm/Connector.js.map +1 -0
- package/lib/esm/DAppConnector.js +118 -0
- package/lib/esm/DAppConnector.js.map +1 -0
- package/lib/esm/ErrorHelper.js +97 -0
- package/lib/esm/ErrorHelper.js.map +1 -0
- package/lib/esm/Utils.js +99 -0
- package/lib/esm/Utils.js.map +1 -0
- package/lib/esm/WCSigner.js +241 -0
- package/lib/esm/WCSigner.js.map +1 -0
- package/lib/esm/WalletConnector.js +203 -0
- package/lib/esm/WalletConnector.js.map +1 -0
- package/lib/esm/index.js +4 -0
- package/lib/esm/index.js.map +1 -0
- package/lib/esm/types/Connector.d.ts +18 -0
- package/lib/esm/types/Connector.d.ts.map +1 -0
- package/lib/esm/types/DAppConnector.d.ts +27 -0
- package/lib/esm/types/DAppConnector.d.ts.map +1 -0
- package/lib/esm/types/ErrorHelper.d.ts +15 -0
- package/lib/esm/types/ErrorHelper.d.ts.map +1 -0
- package/lib/esm/types/Utils.d.ts +39 -0
- package/lib/esm/types/Utils.d.ts.map +1 -0
- package/lib/esm/types/WCSigner.d.ts +33 -0
- package/lib/esm/types/WCSigner.d.ts.map +1 -0
- package/lib/esm/types/WalletConnector.d.ts +21 -0
- package/lib/esm/types/WalletConnector.d.ts.map +1 -0
- package/lib/esm/types/index.d.ts +4 -0
- package/lib/esm/types/index.d.ts.map +1 -0
- package/package.json +41 -0
@@ -0,0 +1,241 @@
|
|
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
|
@@ -0,0 +1 @@
|
|
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,aA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K,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"]}
|
@@ -0,0 +1,203 @@
|
|
1
|
+
import { Query, Transaction } from "@hashgraph/sdk";
|
2
|
+
import { formatJsonRpcError, formatJsonRpcResult } from "@json-rpc-tools/utils";
|
3
|
+
import { SignClient } from "@walletconnect/sign-client";
|
4
|
+
import { getSdkError } from "@walletconnect/utils";
|
5
|
+
import { Connector } from "./Connector.js";
|
6
|
+
import { getExtensionMethodsFromSession } from "./Utils.js";
|
7
|
+
export class WalletConnector extends Connector {
|
8
|
+
onProposalReceive;
|
9
|
+
constructor(metadata) {
|
10
|
+
super(metadata);
|
11
|
+
}
|
12
|
+
async init(onProposalReceive) {
|
13
|
+
this.onProposalReceive = onProposalReceive;
|
14
|
+
try {
|
15
|
+
this.isInitializing = true;
|
16
|
+
this.client = await SignClient.init({
|
17
|
+
relayUrl: "wss://relay.walletconnect.com",
|
18
|
+
projectId: "ce06497abf4102004138a10edd29c921",
|
19
|
+
metadata: this.dAppMetadata
|
20
|
+
});
|
21
|
+
this.subscribeToEvents();
|
22
|
+
await this.checkPersistedState();
|
23
|
+
}
|
24
|
+
finally {
|
25
|
+
this.isInitializing = false;
|
26
|
+
}
|
27
|
+
}
|
28
|
+
async pair(uri) {
|
29
|
+
if (!this.initialized) {
|
30
|
+
throw new Error("WC not initialized");
|
31
|
+
}
|
32
|
+
return await this.client.pair({ uri });
|
33
|
+
}
|
34
|
+
subscribeToEvents() {
|
35
|
+
if (!this.client) {
|
36
|
+
throw new Error("WC is not initialized");
|
37
|
+
}
|
38
|
+
this.client.on("session_proposal", this.onSessionProposal.bind(this));
|
39
|
+
this.client.on("session_request", this.onSessionRequest.bind(this));
|
40
|
+
this.client.on("session_delete", this.destroySession.bind(this));
|
41
|
+
this.client.on("session_expire", this.destroySession.bind(this));
|
42
|
+
}
|
43
|
+
async destroySession(event) {
|
44
|
+
this.session = null;
|
45
|
+
}
|
46
|
+
async onSessionRequest(requestEvent) {
|
47
|
+
const { id, topic, params } = requestEvent;
|
48
|
+
const { request, chainId } = params;
|
49
|
+
const accountId = request.params.accountId;
|
50
|
+
const signer = this.signers.find(s => s.getAccountId().toString() === accountId);
|
51
|
+
if (!signer) {
|
52
|
+
const formattedResult = formatJsonRpcError(id, "Signer is not available anymore");
|
53
|
+
await this.client.respond({
|
54
|
+
topic,
|
55
|
+
response: formattedResult
|
56
|
+
});
|
57
|
+
return;
|
58
|
+
}
|
59
|
+
try {
|
60
|
+
let formattedResult;
|
61
|
+
switch (request.method) {
|
62
|
+
case "getLedgerId": {
|
63
|
+
const result = await signer.getLedgerId();
|
64
|
+
formattedResult = formatJsonRpcResult(id, result);
|
65
|
+
break;
|
66
|
+
}
|
67
|
+
case "getAccountId": {
|
68
|
+
const result = await signer.getAccountId();
|
69
|
+
formattedResult = formatJsonRpcResult(id, result);
|
70
|
+
break;
|
71
|
+
}
|
72
|
+
case "getAccountKey": {
|
73
|
+
const result = await signer.getAccountKey();
|
74
|
+
formattedResult = formatJsonRpcResult(id, result);
|
75
|
+
break;
|
76
|
+
}
|
77
|
+
case "getNetwork": {
|
78
|
+
const result = await signer.getNetwork();
|
79
|
+
formattedResult = formatJsonRpcResult(id, result);
|
80
|
+
break;
|
81
|
+
}
|
82
|
+
case "getMirrorNetwork": {
|
83
|
+
const result = await signer.getMirrorNetwork();
|
84
|
+
formattedResult = formatJsonRpcResult(id, result);
|
85
|
+
break;
|
86
|
+
}
|
87
|
+
case "sign": {
|
88
|
+
const signatures = await signer.sign(request.params.messages, request.params.signOptions);
|
89
|
+
formattedResult = formatJsonRpcResult(id, signatures);
|
90
|
+
break;
|
91
|
+
}
|
92
|
+
case "getAccountBalance": {
|
93
|
+
const result = await signer.getAccountBalance();
|
94
|
+
formattedResult = formatJsonRpcResult(id, result);
|
95
|
+
break;
|
96
|
+
}
|
97
|
+
case "getAccountInfo": {
|
98
|
+
const result = await signer.getAccountInfo();
|
99
|
+
formattedResult = formatJsonRpcResult(id, result);
|
100
|
+
break;
|
101
|
+
}
|
102
|
+
case "getAccountRecords": {
|
103
|
+
const result = await signer.getAccountRecords();
|
104
|
+
formattedResult = formatJsonRpcResult(id, result);
|
105
|
+
break;
|
106
|
+
}
|
107
|
+
case "signTransaction": {
|
108
|
+
const transaction = await Transaction.fromBytes(Buffer.from(request.params.executable, "base64"));
|
109
|
+
const signedTransaction = await signer.signTransaction(transaction);
|
110
|
+
const encodedTransaction = Buffer.from(signedTransaction.toBytes()).toString("base64");
|
111
|
+
formattedResult = formatJsonRpcResult(id, encodedTransaction);
|
112
|
+
break;
|
113
|
+
}
|
114
|
+
case "checkTransaction": {
|
115
|
+
const transaction = await Transaction.fromBytes(Buffer.from(request.params.executable, "base64"));
|
116
|
+
const checkedTransaction = await signer.checkTransaction(transaction);
|
117
|
+
const encodedTransaction = Buffer.from(checkedTransaction.toBytes()).toString("base64");
|
118
|
+
formattedResult = formatJsonRpcResult(id, encodedTransaction);
|
119
|
+
break;
|
120
|
+
}
|
121
|
+
case "populateTransaction": {
|
122
|
+
const transaction = await Transaction.fromBytes(Buffer.from(request.params.executable, "base64"));
|
123
|
+
const populatedTransaction = await signer.populateTransaction(transaction);
|
124
|
+
const encodedTransaction = Buffer.from(populatedTransaction.toBytes()).toString("base64");
|
125
|
+
formattedResult = formatJsonRpcResult(id, encodedTransaction);
|
126
|
+
break;
|
127
|
+
}
|
128
|
+
case "call": {
|
129
|
+
const encodedExecutable = request.params.executable;
|
130
|
+
const isTransaction = request.params.isTransaction;
|
131
|
+
const bytes = Buffer.from(encodedExecutable, "base64");
|
132
|
+
let result;
|
133
|
+
if (isTransaction) {
|
134
|
+
const transaction = Transaction.fromBytes(bytes);
|
135
|
+
result = (await signer.call(transaction)).toJSON();
|
136
|
+
}
|
137
|
+
else {
|
138
|
+
const query = Query.fromBytes(bytes);
|
139
|
+
const queryResult = await signer.call(query);
|
140
|
+
result = Buffer.from(queryResult.toBytes()).toString("base64");
|
141
|
+
}
|
142
|
+
formattedResult = formatJsonRpcResult(id, result);
|
143
|
+
break;
|
144
|
+
}
|
145
|
+
default: {
|
146
|
+
const extensionMethods = getExtensionMethodsFromSession(this.session);
|
147
|
+
if (extensionMethods.includes(request.method)) {
|
148
|
+
const result = await signer[request.method](...request.params.args);
|
149
|
+
formattedResult = formatJsonRpcResult(id, result);
|
150
|
+
}
|
151
|
+
else {
|
152
|
+
throw new Error(getSdkError("INVALID_METHOD").message);
|
153
|
+
}
|
154
|
+
}
|
155
|
+
}
|
156
|
+
await this.client.respond({
|
157
|
+
topic,
|
158
|
+
response: formattedResult
|
159
|
+
});
|
160
|
+
}
|
161
|
+
catch (e) {
|
162
|
+
const formattedResult = formatJsonRpcError(id, e);
|
163
|
+
await this.client.respond({
|
164
|
+
topic,
|
165
|
+
response: formattedResult
|
166
|
+
});
|
167
|
+
}
|
168
|
+
}
|
169
|
+
async onSessionProposal(proposal) {
|
170
|
+
await this.onProposalReceive(proposal);
|
171
|
+
}
|
172
|
+
async approveSessionProposal(data, signers) {
|
173
|
+
const accountConfigs = Object.values(data.namespaces).flatMap(ns => ns.accounts.map(acc => {
|
174
|
+
const [network, chainId, accountId] = acc.split(":");
|
175
|
+
return { network, chainId, accountId };
|
176
|
+
}));
|
177
|
+
const signerAccounts = signers.map(signer => signer.getAccountId().toString());
|
178
|
+
const hasValidSigners = accountConfigs.every(config => signerAccounts.includes(config.accountId));
|
179
|
+
if (!hasValidSigners) {
|
180
|
+
throw new Error("Required signers are missing");
|
181
|
+
}
|
182
|
+
this.signers = signers;
|
183
|
+
const { acknowledged } = await this.client.approve(data);
|
184
|
+
this.session = await acknowledged();
|
185
|
+
return this.session;
|
186
|
+
}
|
187
|
+
async rejectSessionProposal(data) {
|
188
|
+
return this.client.reject(data);
|
189
|
+
}
|
190
|
+
async sendEvent(name, data) {
|
191
|
+
if (!this.session) {
|
192
|
+
throw new Error("No connection session exist!");
|
193
|
+
}
|
194
|
+
const chainId = Object.values(this.session.namespaces)
|
195
|
+
.flatMap(ns => ns.accounts.map(acc => acc.split(":").slice(0, 2).join(":")))[0];
|
196
|
+
const allowedEvents = Object.values(this.session.namespaces)
|
197
|
+
.flatMap(ns => ns.events);
|
198
|
+
if (allowedEvents.includes(name)) {
|
199
|
+
await this.client.emit({ topic: this.session.topic, chainId, event: { name, data } });
|
200
|
+
}
|
201
|
+
}
|
202
|
+
}
|
203
|
+
//# sourceMappingURL=WalletConnector.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"WalletConnector.js","sourceRoot":"","sources":["../../src/WalletConnector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,KAAK,EAA2B,WAAW,EAAC,MAAM,gBAAgB,CAAC;AAC3E,OAAO,EAAC,kBAAkB,EAAE,mBAAmB,EAAC,MAAM,uBAAuB,CAAC;AAC9E,OAAO,EAAC,UAAU,EAAC,MAAM,4BAA4B,CAAC;AAEtD,OAAO,EAAC,WAAW,EAAC,MAAM,sBAAsB,CAAC;AACjD,O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AC,CAAC,CAAC,CAAC,CAAC,CAAC;QACjF,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC;aACzD,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC;QAC5B,IAAI,aAAa,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;YAChC,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,EAAC,IAAI,EAAE,IAAI,EAAC,EAAC,CAAC,CAAC;SACnF;IACH,CAAC;CACF","sourcesContent":["import {Query, Signer, SignerSignature, Transaction} from \"@hashgraph/sdk\";\nimport {formatJsonRpcError, formatJsonRpcResult} from \"@json-rpc-tools/utils\";\nimport {SignClient} from \"@walletconnect/sign-client\";\nimport {EngineTypes, PairingTypes, SessionTypes, SignClientTypes} from \"@walletconnect/types\";\nimport {getSdkError} from \"@walletconnect/utils\";\nimport {Connector} from \"./Connector.js\";\nimport ApproveParams = EngineTypes.ApproveParams;\nimport RejectParams = EngineTypes.RejectParams;\nimport { getExtensionMethodsFromSession } from \"./Utils.js\";\n\ntype ProposalCallback = (proposal: SignClientTypes.EventArguments[\"session_proposal\"]) => Promise<void>;\n\nexport class WalletConnector extends Connector {\n public onProposalReceive: ProposalCallback;\n\n constructor(metadata?: SignClientTypes.Metadata) {\n super(metadata);\n }\n\n public async init(onProposalReceive: ProposalCallback) {\n this.onProposalReceive = onProposalReceive;\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 await this.checkPersistedState();\n } finally {\n this.isInitializing = false;\n }\n }\n\n public async pair(uri: string): Promise<PairingTypes.Struct> {\n if (!this.initialized) {\n throw new Error(\"WC not initialized\");\n }\n\n return await this.client.pair({uri});\n }\n\n private subscribeToEvents() {\n if (!this.client) {\n throw new Error(\"WC is not initialized\");\n }\n this.client.on(\"session_proposal\", this.onSessionProposal.bind(this));\n this.client.on(\"session_request\", this.onSessionRequest.bind(this));\n this.client.on(\"session_delete\", this.destroySession.bind(this));\n this.client.on(\"session_expire\", this.destroySession.bind(this));\n }\n\n private async destroySession(event: SignClientTypes.EventArguments[\"session_expire\"] | SignClientTypes.EventArguments[\"session_delete\"]) {\n this.session = null;\n }\n\n private async onSessionRequest(requestEvent: SignClientTypes.EventArguments[\"session_request\"]) {\n const {id, topic, params} = requestEvent;\n const {request, chainId} = params;\n const accountId = request.params.accountId;\n const signer = this.signers.find(s => s.getAccountId().toString() === accountId);\n\n if (!signer) {\n const formattedResult = formatJsonRpcError(id, \"Signer is not available anymore\");\n await this.client.respond({\n topic,\n response: formattedResult\n });\n return;\n }\n\n try {\n let formattedResult;\n switch (request.method) {\n case \"getLedgerId\": {\n const result = await signer.getLedgerId();\n formattedResult = formatJsonRpcResult(id, result);\n break;\n }\n case \"getAccountId\": {\n const result = await signer.getAccountId();\n formattedResult = formatJsonRpcResult(id, result);\n break;\n }\n case \"getAccountKey\": {\n const result = await signer.getAccountKey();\n formattedResult = formatJsonRpcResult(id, result);\n break;\n }\n case \"getNetwork\": {\n const result = await signer.getNetwork();\n formattedResult = formatJsonRpcResult(id, result);\n break;\n }\n case \"getMirrorNetwork\": {\n const result = await signer.getMirrorNetwork();\n formattedResult = formatJsonRpcResult(id, result);\n break;\n }\n case \"sign\": {\n const signatures: SignerSignature[] = await signer.sign(request.params.messages, request.params.signOptions)\n formattedResult = formatJsonRpcResult(id, signatures);\n break;\n }\n case \"getAccountBalance\": {\n const result = await signer.getAccountBalance();\n formattedResult = formatJsonRpcResult(id, result);\n break;\n }\n case \"getAccountInfo\": {\n const result = await signer.getAccountInfo();\n formattedResult = formatJsonRpcResult(id, result);\n break;\n }\n case \"getAccountRecords\": {\n const result = await signer.getAccountRecords();\n formattedResult = formatJsonRpcResult(id, result);\n break;\n }\n case \"signTransaction\": {\n const transaction = await Transaction.fromBytes(Buffer.from(request.params.executable, \"base64\"))\n const signedTransaction = await signer.signTransaction(transaction);\n const encodedTransaction = Buffer.from(signedTransaction.toBytes()).toString(\"base64\");\n formattedResult = formatJsonRpcResult(id, encodedTransaction);\n break;\n }\n case \"checkTransaction\": {\n const transaction = await Transaction.fromBytes(Buffer.from(request.params.executable, \"base64\"))\n const checkedTransaction = await signer.checkTransaction(transaction);\n const encodedTransaction = Buffer.from(checkedTransaction.toBytes()).toString(\"base64\");\n formattedResult = formatJsonRpcResult(id, encodedTransaction);\n break;\n }\n case \"populateTransaction\": {\n const transaction = await Transaction.fromBytes(Buffer.from(request.params.executable, \"base64\"))\n const populatedTransaction = await signer.populateTransaction(transaction);\n const encodedTransaction = Buffer.from(populatedTransaction.toBytes()).toString(\"base64\");\n formattedResult = formatJsonRpcResult(id, encodedTransaction);\n break;\n }\n case \"call\": {\n const encodedExecutable = request.params.executable;\n const isTransaction = request.params.isTransaction;\n const bytes = Buffer.from(encodedExecutable, \"base64\");\n let result;\n if (isTransaction) {\n const transaction = Transaction.fromBytes(bytes);\n result = (await signer.call(transaction)).toJSON();\n } else {\n const query = Query.fromBytes(bytes);\n const queryResult: any = await signer.call(query);\n result = Buffer.from(queryResult.toBytes()).toString(\"base64\");\n }\n formattedResult = formatJsonRpcResult(id, result);\n break;\n }\n default: {\n const extensionMethods = getExtensionMethodsFromSession(this.session);\n if (extensionMethods.includes(request.method)) {\n const result = await signer[request.method](...request.params.args)\n formattedResult = formatJsonRpcResult(id, result);\n } else {\n throw new Error(getSdkError(\"INVALID_METHOD\").message);\n }\n }\n }\n await this.client.respond({\n topic,\n response: formattedResult\n });\n } catch (e: any) {\n const formattedResult = formatJsonRpcError(id, e);\n await this.client.respond({\n topic,\n response: formattedResult\n });\n }\n }\n\n private async onSessionProposal(proposal: SignClientTypes.EventArguments[\"session_proposal\"]): Promise<void> {\n await this.onProposalReceive(proposal)\n }\n\n public async approveSessionProposal<T extends Signer>(data: ApproveParams, signers: T[]): Promise<SessionTypes.Struct> {\n const accountConfigs = Object.values(data.namespaces).flatMap(ns => ns.accounts.map(acc => {\n const [network, chainId, accountId] = acc.split(\":\");\n return {network, chainId, accountId};\n }));\n const signerAccounts = signers.map(signer => signer.getAccountId().toString());\n const hasValidSigners = accountConfigs.every(config => signerAccounts.includes(config.accountId));\n\n if (!hasValidSigners) {\n throw new Error(\"Required signers are missing\");\n }\n\n this.signers = signers;\n const {acknowledged} = await this.client.approve(data);\n this.session = await acknowledged();\n return this.session;\n }\n\n public async rejectSessionProposal(data: RejectParams): Promise<void> {\n return this.client.reject(data);\n }\n\n public async sendEvent(name: string, data: any): Promise<void> {\n if (!this.session) {\n throw new Error(\"No connection session exist!\");\n }\n\n const chainId = Object.values(this.session.namespaces)\n .flatMap(ns => ns.accounts.map(acc => acc.split(\":\").slice(0,2).join(\":\")))[0];\n const allowedEvents = Object.values(this.session.namespaces)\n .flatMap(ns => ns.events);\n if (allowedEvents.includes(name)) {\n await this.client.emit({topic: this.session.topic, chainId, event: {name, data}});\n }\n }\n}\n"]}
|
package/lib/esm/index.js
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAC;AACnC,cAAc,sBAAsB,CAAC;AACrC,cAAc,YAAY,CAAA","sourcesContent":["export * from \"./DAppConnector.js\";\nexport * from \"./WalletConnector.js\";\nexport * from \"./Utils.js\"\n"]}
|
@@ -0,0 +1,18 @@
|
|
1
|
+
import SignClient from "@walletconnect/sign-client";
|
2
|
+
import { Signer } from "@hashgraph/sdk";
|
3
|
+
import { SessionTypes, SignClientTypes } from "@walletconnect/types";
|
4
|
+
declare type Client = SignClient.default;
|
5
|
+
export declare class Connector {
|
6
|
+
protected readonly dAppMetadata: SignClientTypes.Metadata;
|
7
|
+
protected isInitializing: boolean;
|
8
|
+
protected client: Client | null;
|
9
|
+
protected session: SessionTypes.Struct | null;
|
10
|
+
protected signers: Signer[];
|
11
|
+
protected constructor(metadata?: SignClientTypes.Metadata);
|
12
|
+
checkPersistedState(): Promise<SessionTypes.Struct>;
|
13
|
+
disconnect(): Promise<void>;
|
14
|
+
private reset;
|
15
|
+
get initialized(): boolean;
|
16
|
+
}
|
17
|
+
export {};
|
18
|
+
//# sourceMappingURL=Connector.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"Connector.d.ts","sourceRoot":"","sources":["../../../src/Connector.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,MAAM,4BAA4B,CAAC;AAEpD,OAAO,EAAC,MAAM,EAAC,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAC,YAAY,EAAE,eAAe,EAAC,MAAM,sBAAsB,CAAC;AAGnE,OAAO,MAAM,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC;AAEzC,qBAAa,SAAS;IACpB,SAAS,CAAC,QAAQ,CAAC,YAAY,EAAE,eAAe,CAAC,QAAQ,CAAC;IAC1D,SAAS,CAAC,cAAc,EAAE,OAAO,CAAS;IAC1C,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAQ;IACvC,SAAS,CAAC,OAAO,EAAE,YAAY,CAAC,MAAM,GAAG,IAAI,CAAQ;IACrD,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,CAAM;IAEjC,SAAS,aAAa,QAAQ,CAAC,EAAE,eAAe,CAAC,QAAQ;IAInD,mBAAmB;IAqDnB,UAAU;IAgBhB,OAAO,CAAC,KAAK;IAKb,IAAI,WAAW,IAAI,OAAO,CAEzB;CACF"}
|
@@ -0,0 +1,27 @@
|
|
1
|
+
import { LedgerId } from "@hashgraph/sdk";
|
2
|
+
import { SessionTypes, SignClientTypes } from "@walletconnect/types";
|
3
|
+
import { Subject } from "rxjs";
|
4
|
+
import { Connector } from "./Connector.js";
|
5
|
+
type WalletEvent = {
|
6
|
+
name: string;
|
7
|
+
data: any;
|
8
|
+
};
|
9
|
+
export type DAppMetadata = SignClientTypes.Metadata;
|
10
|
+
export declare class DAppConnector extends Connector {
|
11
|
+
private allowedEvents;
|
12
|
+
private extensionMethods;
|
13
|
+
static instance: DAppConnector;
|
14
|
+
$events: Subject<WalletEvent>;
|
15
|
+
constructor(metadata?: DAppMetadata);
|
16
|
+
init(events?: string[], methods?: string[]): Promise<void>;
|
17
|
+
private subscribeToEvents;
|
18
|
+
connect(ledgerId?: LedgerId, activeTopic?: string): Promise<void>;
|
19
|
+
prepareConnectURI(ledgerId?: LedgerId, activeTopic?: string): Promise<{
|
20
|
+
uri?: string;
|
21
|
+
approval: () => Promise<SessionTypes.Struct>;
|
22
|
+
}>;
|
23
|
+
onSessionConnected(session: SessionTypes.Struct): Promise<void>;
|
24
|
+
getSigners(): Signer[];
|
25
|
+
}
|
26
|
+
export {};
|
27
|
+
//# sourceMappingURL=DAppConnector.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"DAppConnector.d.ts","sourceRoot":"","sources":["../../../src/DAppConnector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,QAAQ,EAAC,MAAM,gBAAgB,CAAC;AAGnD,OAAO,EAAC,YAAY,EAAE,eAAe,EAAC,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAC,OAAO,EAAC,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAC,SAAS,EAAC,MAAM,gBAAgB,CAAC;AASzC,KAAK,WAAW,GAAG;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,GAAG,CAAA;CACV,CAAA;AAED,MAAM,MAAM,YAAY,GAAG,eAAe,CAAC,QAAQ,CAAC;AAEpD,qBAAa,aAAc,SAAQ,SAAS;IAC1C,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,gBAAgB,CAAgB;IACxC,MAAM,CAAC,QAAQ,EAAE,aAAa,CAAC;IACxB,OAAO,EAAE,OAAO,CAAC,WAAW,CAAC,CAA8B;gBAEtD,QAAQ,CAAC,EAAE,YAAY;IAK7B,IAAI,CAAC,MAAM,GAAE,MAAM,EAAO,EAAE,OAAO,GAAE,MAAM,EAAO;IAoBxD,OAAO,CAAC,iBAAiB;IAkBnB,OAAO,CAAC,QAAQ,GAAE,QAA2B,EAAE,WAAW,CAAC,EAAE,MAAM;IAwCnE,iBAAiB,CAAC,QAAQ,GAAE,QAA2B,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;QAC5F,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,MAAM,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;KAC9C,CAAC;IAqBI,kBAAkB,CAAC,OAAO,EAAE,YAAY,CAAC,MAAM;IAYrD,UAAU;CAGX"}
|
@@ -0,0 +1,15 @@
|
|
1
|
+
type HandlerFunction = (error: Error, ctx: any) => Promise<boolean> | boolean;
|
2
|
+
type CatchOptions = {
|
3
|
+
retry?: boolean;
|
4
|
+
retryDelay?: number;
|
5
|
+
};
|
6
|
+
export declare class HWCError extends Error {
|
7
|
+
readonly code: number;
|
8
|
+
readonly description: string;
|
9
|
+
readonly error: Error | {};
|
10
|
+
constructor(code: number, description: string, error: Error | {});
|
11
|
+
}
|
12
|
+
export declare const Catch: (errorType: any, handler: HandlerFunction, options?: CatchOptions) => any;
|
13
|
+
export declare const CatchAll: (handler: HandlerFunction, options?: CatchOptions) => any;
|
14
|
+
export {};
|
15
|
+
//# sourceMappingURL=ErrorHelper.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"ErrorHelper.d.ts","sourceRoot":"","sources":["../../../src/ErrorHelper.ts"],"names":[],"mappings":"AAAA,KAAK,eAAe,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;AAC9E,KAAK,YAAY,GAAG;IAClB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB,CAAA;AAED,qBAAa,QAAS,SAAQ,KAAK;aAEf,IAAI,EAAE,MAAM;aACZ,WAAW,EAAE,MAAM;aACnB,KAAK,EAAE,KAAK,GAAG,EAAE;gBAFjB,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE,KAAK,GAAG,EAAE;CAIpC;AAMD,eAAO,MAAM,KAAK,cAAe,GAAG,WAAW,eAAe,YAAY,YAAY,KAAG,GA0FxF,CAAC;AAEF,eAAO,MAAM,QAAQ,YAAa,eAAe,YAAY,YAAY,KAAG,GAAqC,CAAC"}
|
@@ -0,0 +1,39 @@
|
|
1
|
+
import { LedgerId, PublicKey } from "@hashgraph/sdk";
|
2
|
+
import { ProposalTypes, SessionTypes } from "@walletconnect/types";
|
3
|
+
export declare enum METHODS {
|
4
|
+
SIGN_TRANSACTION = "signTransaction",
|
5
|
+
CALL = "call",
|
6
|
+
GET_ACCOUNT_BALANCE = "getAccountBalance",
|
7
|
+
GET_ACCOUNT_INFO = "getAccountInfo",
|
8
|
+
GET_LEDGER_ID = "getLedgerId",
|
9
|
+
GET_ACCOUNT_ID = "getAccountId",
|
10
|
+
GET_ACCOUNT_KEY = "getAccountKey",
|
11
|
+
GET_NETWORK = "getNetwork",
|
12
|
+
GET_MIRROR_NETWORK = "getMirrorNetwork",
|
13
|
+
SIGN = "sign",
|
14
|
+
GET_ACCOUNT_RECORDS = "getAccountRecords",
|
15
|
+
CHECK_TRANSACTION = "checkTransaction",
|
16
|
+
POPULATE_TRANSACTION = "populateTransaction"
|
17
|
+
}
|
18
|
+
export declare enum EVENTS {
|
19
|
+
ACCOUNTS_CHANGED = "accountsChanged"
|
20
|
+
}
|
21
|
+
export declare const getChainByLedgerId: (ledgerId: LedgerId) => string;
|
22
|
+
export declare const getLedgerIdByChainId: (chainId: string) => string;
|
23
|
+
export declare const getRequiredNamespaces: (ledgerId: LedgerId) => ProposalTypes.RequiredNamespaces;
|
24
|
+
export declare const getLedgerIDsFromSession: (session: SessionTypes.Struct) => LedgerId[];
|
25
|
+
export declare const getAccountLedgerPairsFromSession: (session: SessionTypes.Struct) => {
|
26
|
+
network: LedgerId;
|
27
|
+
account: string;
|
28
|
+
}[];
|
29
|
+
export declare const getExtensionMethodsFromSession: (session: SessionTypes.Struct) => string[];
|
30
|
+
type Encodable = {
|
31
|
+
toBytes(): Uint8Array;
|
32
|
+
};
|
33
|
+
export declare const isEncodable: (obj: any) => obj is Encodable;
|
34
|
+
export declare const isTransaction: (obj: any) => obj is Transaction;
|
35
|
+
export declare const evmAddressFromObject: (data: any) => string | null;
|
36
|
+
export declare const publicKeyFromObject: (data: any) => PublicKey | null;
|
37
|
+
export declare const convertToSignerSignature: (data: any) => SignerSignature;
|
38
|
+
export {};
|
39
|
+
//# sourceMappingURL=Utils.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"Utils.d.ts","sourceRoot":"","sources":["../../../src/Utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,QAAQ,EAAE,SAAS,EAA+B,MAAM,gBAAgB,CAAC;AAC5F,OAAO,EAAC,aAAa,EAAE,YAAY,EAAC,MAAM,sBAAsB,CAAC;AAQjE,oBAAY,OAAO;IACjB,gBAAgB,oBAAoB;IACpC,IAAI,SAAS;IACb,mBAAmB,sBAAsB;IACzC,gBAAgB,mBAAmB;IACnC,aAAa,gBAAgB;IAC7B,cAAc,iBAAiB;IAC/B,eAAe,kBAAkB;IACjC,WAAW,eAAe;IAC1B,kBAAkB,qBAAqB;IACvC,IAAI,SAAS;IACb,mBAAmB,sBAAsB;IACzC,iBAAiB,qBAAqB;IACtC,oBAAoB,wBAAwB;CAC7C;AAED,oBAAY,MAAM;IAChB,gBAAgB,oBAAoB;CACrC;AAED,eAAO,MAAM,kBAAkB,0BAAyB,MAEvD,CAAA;AAED,eAA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