-
Notifications
You must be signed in to change notification settings - Fork 392
Expand file tree
/
Copy pathJsonRpcContext.tsx
More file actions
1946 lines (1763 loc) · 56.7 KB
/
JsonRpcContext.tsx
File metadata and controls
1946 lines (1763 loc) · 56.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { BigNumber, utils } from "ethers";
import { createContext, ReactNode, useContext, useState } from "react";
import * as encoding from "@walletconnect/encoding";
import { Transaction as EthTransaction } from "@ethereumjs/tx";
import { recoverTransaction } from "@celo/wallet-base";
import * as bitcoin from "bitcoinjs-lib";
import { ApiPromise, WsProvider } from "@polkadot/api";
import {
formatDirectSignDoc,
stringifySignDocValues,
verifyAminoSignature,
verifyDirectSignature,
} from "cosmos-wallet";
import bs58 from "bs58";
import { verifyMessageSignature } from "solana-wallet";
import {
Connection,
Keypair,
SystemProgram,
Transaction as SolanaTransaction,
clusterApiUrl,
} from "@solana/web3.js";
// @ts-expect-error
import TronWeb from "tronweb";
import {
IPactCommand,
PactCommand,
createWalletConnectQuicksign,
createWalletConnectSign,
} from "@kadena/client";
import { PactNumber } from "@kadena/pactjs";
import {
IUTXO,
KadenaAccount,
eip712,
formatTestBatchCall,
formatTestTransaction,
getLocalStorageTestnetFlag,
getProviderUrl,
hashPersonalMessage,
hashTypedDataMessage,
verifySignature,
} from "../helpers";
import { useWalletConnectClient } from "./ClientContext";
import {
DEFAULT_COSMOS_METHODS,
DEFAULT_EIP155_METHODS,
DEFAULT_SOLANA_METHODS,
DEFAULT_POLKADOT_METHODS,
DEFAULT_NEAR_METHODS,
DEFAULT_MULTIVERSX_METHODS,
DEFAULT_TRON_METHODS,
DEFAULT_TEZOS_METHODS,
DEFAULT_KADENA_METHODS,
DEFAULT_EIP155_OPTIONAL_METHODS,
DEFAULT_EIP5792_METHODS,
SendCallsParams,
GetCapabilitiesResult,
GetCallsResult,
DEFAULT_BIP122_METHODS,
DEFAULT_EIP7715_METHODS,
WalletGrantPermissionsParameters,
WalletGrantPermissionsReturnType,
} from "../constants";
import { useChainData } from "./ChainDataContext";
import { rpcProvidersByChainId } from "../../src/helpers/api";
import { signatureVerify, cryptoWaitReady } from "@polkadot/util-crypto";
import {
Transaction as MultiversxTransaction,
TransactionPayload,
Address,
SignableMessage,
} from "@multiversx/sdk-core";
import { UserVerifier } from "@multiversx/sdk-wallet/out/userVerifier";
import { parseEther } from "ethers/lib/utils";
import {
apiGetAddressUtxos,
calculateChange,
getAvailableBalanceFromUtxos,
isBip122Testnet,
isOrdinalAddress,
isValidBip122Signature,
} from "../helpers/bip122";
import { getAddressFromAccount } from "@walletconnect/utils";
import { BIP122_DUST_LIMIT } from "../chains/bip122";
import { PolkadotChainData } from "../chains/polkadot";
/**
* Types
*/
interface IFormattedRpcResponse {
method?: string;
address?: string;
valid: boolean;
result: string;
}
type TRpcRequestCallback = (
chainId: string,
address: string,
message?: string
) => Promise<void>;
interface IContext {
ping: () => Promise<void>;
ethereumRpc: {
testSendTransaction: TRpcRequestCallback;
testSignTransaction: TRpcRequestCallback;
testEthSign: TRpcRequestCallback;
testSignPersonalMessage: TRpcRequestCallback;
testSignTypedData: TRpcRequestCallback;
testSignTypedDatav4: TRpcRequestCallback;
testWalletGetCapabilities: TRpcRequestCallback;
testWalletSendCalls: TRpcRequestCallback;
testWalletGrantPermissions: TRpcRequestCallback;
testWalletGetCallsStatus: TRpcRequestCallback;
};
cosmosRpc: {
testSignDirect: TRpcRequestCallback;
testSignAmino: TRpcRequestCallback;
};
solanaRpc: {
testSignMessage: TRpcRequestCallback;
testSignTransaction: TRpcRequestCallback;
};
polkadotRpc: {
testSignMessage: TRpcRequestCallback;
testSignTransaction: TRpcRequestCallback;
};
nearRpc: {
testSignAndSendTransaction: TRpcRequestCallback;
testSignAndSendTransactions: TRpcRequestCallback;
};
multiversxRpc: {
testSignMessage: TRpcRequestCallback;
testSignTransaction: TRpcRequestCallback;
testSignTransactions: TRpcRequestCallback;
};
tronRpc: {
testSignMessage: TRpcRequestCallback;
testSignTransaction: TRpcRequestCallback;
};
tezosRpc: {
testGetAccounts: TRpcRequestCallback;
testSignMessage: TRpcRequestCallback;
testSignTransaction: TRpcRequestCallback;
};
kadenaRpc: {
testGetAccounts: TRpcRequestCallback;
testSign: TRpcRequestCallback;
testQuicksign: TRpcRequestCallback;
};
bip122Rpc: {
testGetAccountAddresses: TRpcRequestCallback;
testSignMessage: TRpcRequestCallback;
testSendTransaction: TRpcRequestCallback;
testSignPsbt: TRpcRequestCallback;
};
rpcResult?: IFormattedRpcResponse | null;
isRpcRequestPending: boolean;
isTestnet: boolean;
setIsTestnet: (isTestnet: boolean) => void;
}
/**
* Context
*/
export const JsonRpcContext = createContext<IContext>({} as IContext);
/**
* Provider
*/
export function JsonRpcContextProvider({
children,
}: {
children: ReactNode | ReactNode[];
}) {
const [pending, setPending] = useState(false);
const [result, setResult] = useState<IFormattedRpcResponse | null>();
const [isTestnet, setIsTestnet] = useState(getLocalStorageTestnetFlag());
const [lastTxId, setLastTxId] = useState<`0x${string}`>();
const [kadenaAccount, setKadenaAccount] = useState<KadenaAccount | null>(
null
);
const { client, session, accounts, balances, solanaPublicKeys, setAccounts } =
useWalletConnectClient();
const { chainData } = useChainData();
const _createJsonRpcRequestHandler =
(
rpcRequest: (
chainId: string,
address: string
) => Promise<IFormattedRpcResponse>
) =>
async (chainId: string, address: string) => {
if (typeof client === "undefined") {
throw new Error("WalletConnect is not initialized");
}
if (typeof session === "undefined") {
throw new Error("Session is not connected");
}
try {
setPending(true);
const result = await rpcRequest(chainId, address);
setResult(result);
} catch (err: any) {
console.error("RPC request failed: ", err);
setResult({
address,
valid: false,
result: err?.message ?? err,
});
} finally {
setPending(false);
}
};
const _verifyEip155MessageSignature = (
message: string,
signature: string,
address: string
) =>
utils.verifyMessage(message, signature).toLowerCase() ===
address.toLowerCase();
const ping = async () => {
if (typeof client === "undefined") {
throw new Error("WalletConnect is not initialized");
}
if (typeof session === "undefined") {
throw new Error("Session is not connected");
}
try {
setPending(true);
let valid = false;
try {
await client.ping({ topic: session.topic });
valid = true;
} catch (e) {
valid = false;
}
// display result
setResult({
method: "ping",
valid,
result: valid ? "Ping succeeded" : "Ping failed",
});
} catch (e) {
console.error(e);
setResult(null);
} finally {
setPending(false);
}
};
// -------- ETHEREUM/EIP155 RPC METHODS --------
const ethereumRpc = {
testSendTransaction: _createJsonRpcRequestHandler(
async (chainId: string, address: string) => {
const caipAccountAddress = `${chainId}:${address}`;
const account = accounts.find(
(account) => account === caipAccountAddress
);
if (account === undefined)
throw new Error(`Account for ${caipAccountAddress} not found`);
const tx = await formatTestTransaction(account);
const balance = BigNumber.from(balances[account][0].balance || "0");
if (balance.lt(BigNumber.from(tx.gasPrice).mul(tx.gasLimit))) {
return {
method: DEFAULT_EIP155_METHODS.ETH_SEND_TRANSACTION,
address,
valid: false,
result: "Insufficient funds for intrinsic transaction cost",
};
}
const result = await client!.request<string>({
topic: session!.topic,
chainId,
request: {
method: DEFAULT_EIP155_METHODS.ETH_SEND_TRANSACTION,
params: [tx],
},
});
// format displayed result
return {
method: DEFAULT_EIP155_METHODS.ETH_SEND_TRANSACTION,
address,
valid: true,
result,
};
}
),
testSignTransaction: _createJsonRpcRequestHandler(
async (chainId: string, address: string) => {
const caipAccountAddress = `${chainId}:${address}`;
const account = accounts.find(
(account) => account === caipAccountAddress
);
if (account === undefined)
throw new Error(`Account for ${caipAccountAddress} not found`);
const tx = await formatTestTransaction(account);
const signedTx = await client!.request<string>({
topic: session!.topic,
chainId,
request: {
method: DEFAULT_EIP155_OPTIONAL_METHODS.ETH_SIGN_TRANSACTION,
params: [tx],
},
});
const CELO_ALFAJORES_CHAIN_ID = 44787;
const CELO_MAINNET_CHAIN_ID = 42220;
let valid = false;
const [, reference] = chainId.split(":");
if (
reference === CELO_ALFAJORES_CHAIN_ID.toString() ||
reference === CELO_MAINNET_CHAIN_ID.toString()
) {
const [, signer] = recoverTransaction(signedTx);
valid = signer.toLowerCase() === address.toLowerCase();
} else {
valid = EthTransaction.fromSerializedTx(
signedTx as any
).verifySignature();
}
return {
method: DEFAULT_EIP155_OPTIONAL_METHODS.ETH_SIGN_TRANSACTION,
address,
valid,
result: signedTx,
};
}
),
testSignPersonalMessage: _createJsonRpcRequestHandler(
async (chainId: string, address: string) => {
// test message
const message = `My email is john@doe.com - ${Date.now()}`;
// encode message (hex)
const hexMsg = encoding.utf8ToHex(message, true);
// personal_sign params
const params = [hexMsg, address];
// send message
const signature = await client!.request<string>({
topic: session!.topic,
chainId,
request: {
method: DEFAULT_EIP155_METHODS.PERSONAL_SIGN,
params,
},
});
// split chainId
const [namespace, reference] = chainId.split(":");
const rpc = rpcProvidersByChainId[Number(reference)];
if (typeof rpc === "undefined") {
throw new Error(
`Missing rpcProvider definition for chainId: ${chainId}`
);
}
const hashMsg = hashPersonalMessage(message);
const valid = await verifySignature(
address,
signature,
hashMsg,
rpc.baseURL
);
// format displayed result
return {
method: DEFAULT_EIP155_METHODS.PERSONAL_SIGN,
address,
valid,
result: signature,
};
}
),
testEthSign: _createJsonRpcRequestHandler(
async (chainId: string, address: string) => {
// test message
const message = `My email is john@doe.com - ${Date.now()}`;
// encode message (hex)
const hexMsg = encoding.utf8ToHex(message, true);
// eth_sign params
const params = [address, hexMsg];
// send message
const signature = await client!.request<string>({
topic: session!.topic,
chainId,
request: {
method: DEFAULT_EIP155_OPTIONAL_METHODS.ETH_SIGN,
params,
},
});
// split chainId
const [namespace, reference] = chainId.split(":");
const rpc = rpcProvidersByChainId[Number(reference)];
if (typeof rpc === "undefined") {
throw new Error(
`Missing rpcProvider definition for chainId: ${chainId}`
);
}
const hashMsg = hashPersonalMessage(message);
const valid = await verifySignature(
address,
signature,
hashMsg,
rpc.baseURL
);
// format displayed result
return {
method: DEFAULT_EIP155_OPTIONAL_METHODS.ETH_SIGN + " (standard)",
address,
valid,
result: signature,
};
}
),
testSignTypedData: _createJsonRpcRequestHandler(
async (chainId: string, address: string) => {
const message = JSON.stringify(eip712.example);
// eth_signTypedData params
const params = [address, message];
// send message
const signature = await client!.request<string>({
topic: session!.topic,
chainId,
request: {
method: DEFAULT_EIP155_OPTIONAL_METHODS.ETH_SIGN_TYPED_DATA,
params,
},
});
// split chainId
const [namespace, reference] = chainId.split(":");
const rpc = rpcProvidersByChainId[Number(reference)];
if (typeof rpc === "undefined") {
throw new Error(
`Missing rpcProvider definition for chainId: ${chainId}`
);
}
const hashedTypedData = hashTypedDataMessage(message);
const valid = await verifySignature(
address,
signature,
hashedTypedData,
rpc.baseURL
);
return {
method: DEFAULT_EIP155_OPTIONAL_METHODS.ETH_SIGN_TYPED_DATA,
address,
valid,
result: signature,
};
}
),
testSignTypedDatav4: _createJsonRpcRequestHandler(
async (chainId: string, address: string) => {
const message = JSON.stringify(eip712.example);
console.log("eth_signTypedData_v4");
// eth_signTypedData_v4 params
const params = [address, message];
// send message
const signature = await client!.request<string>({
topic: session!.topic,
chainId,
request: {
method: DEFAULT_EIP155_OPTIONAL_METHODS.ETH_SIGN_TYPED_DATA_V4,
params,
},
});
// split chainId
const [namespace, reference] = chainId.split(":");
const rpc = rpcProvidersByChainId[Number(reference)];
if (typeof rpc === "undefined") {
throw new Error(
`Missing rpcProvider definition for chainId: ${chainId}`
);
}
const hashedTypedData = hashTypedDataMessage(message);
const valid = await verifySignature(
address,
signature,
hashedTypedData,
rpc.baseURL
);
return {
method: DEFAULT_EIP155_OPTIONAL_METHODS.ETH_SIGN_TYPED_DATA,
address,
valid,
result: signature,
};
}
),
testWalletGetCapabilities: _createJsonRpcRequestHandler(
async (chainId: string, address: string) => {
// split chainId
const [namespace, reference] = chainId.split(":");
const rpc = rpcProvidersByChainId[Number(reference)];
if (typeof rpc === "undefined") {
throw new Error(
`Missing rpcProvider definition for chainId: ${chainId}`
);
}
// The wallet_getCapabilities "caching" should ultimately move into the provider.
// check the session.sessionProperties first for capabilities
const capabilitiesJson = session?.sessionProperties?.["capabilities"];
const walletCapabilities =
capabilitiesJson && JSON.parse(capabilitiesJson);
let capabilities = walletCapabilities[address] as
| GetCapabilitiesResult
| undefined;
// send request for wallet_getCapabilities
if (!capabilities)
capabilities = await client!.request<GetCapabilitiesResult>({
topic: session!.topic,
chainId,
request: {
method: DEFAULT_EIP5792_METHODS.WALLET_GET_CAPABILITIES,
params: [address],
},
});
// format displayed result
return {
method: DEFAULT_EIP5792_METHODS.WALLET_GET_CAPABILITIES,
address,
valid: true,
result: JSON.stringify(capabilities),
};
}
),
testWalletGetCallsStatus: _createJsonRpcRequestHandler(
async (chainId: string, address: string) => {
// split chainId
const [namespace, reference] = chainId.split(":");
const rpc = rpcProvidersByChainId[Number(reference)];
if (typeof rpc === "undefined") {
throw new Error(
`Missing rpcProvider definition for chainId: ${chainId}`
);
}
if (lastTxId === undefined)
throw new Error(
`Last transaction ID is undefined, make sure previous call to sendCalls returns successfully. `
);
const params = [lastTxId];
// send request for wallet_getCallsStatus
const getCallsStatusResult = await client!.request<GetCallsResult>({
topic: session!.topic,
chainId,
request: {
method: DEFAULT_EIP5792_METHODS.WALLET_GET_CALLS_STATUS,
params: params,
},
});
// format displayed result
return {
method: DEFAULT_EIP5792_METHODS.WALLET_GET_CALLS_STATUS,
address,
valid: true,
result: JSON.stringify(getCallsStatusResult),
};
}
),
testWalletSendCalls: _createJsonRpcRequestHandler(
//Sample test call - batch multiple native send tx
async (chainId: string, address: string) => {
const caipAccountAddress = `${chainId}:${address}`;
const account = accounts.find(
(account) => account === caipAccountAddress
);
if (account === undefined)
throw new Error(`Account for ${caipAccountAddress} not found`);
const balance = BigNumber.from(balances[account][0].balance || "0");
if (balance.lt(parseEther("0.0002"))) {
return {
method: DEFAULT_EIP5792_METHODS.WALLET_SEND_CALLS,
address,
valid: false,
result:
"Insufficient funds for batch call [minimum 0.0002ETH required excluding gas].",
};
}
// split chainId
const [namespace, reference] = chainId.split(":");
const rpc = rpcProvidersByChainId[Number(reference)];
if (typeof rpc === "undefined") {
throw new Error(
`Missing rpcProvider definition for chainId: ${chainId}`
);
}
const sendCallsRequestParams: SendCallsParams =
await formatTestBatchCall(account);
// send batch Tx
const txId = await client!.request<string>({
topic: session!.topic,
chainId,
request: {
method: DEFAULT_EIP5792_METHODS.WALLET_SEND_CALLS,
params: [sendCallsRequestParams],
},
});
// store the last transactionId to use it for wallet_getCallsReceipt
setLastTxId(
txId && txId.startsWith("0x") ? (txId as `0x${string}`) : undefined
);
// format displayed result
return {
method: DEFAULT_EIP5792_METHODS.WALLET_SEND_CALLS,
address,
valid: true,
result: txId,
};
}
),
testWalletGrantPermissions: _createJsonRpcRequestHandler(
async (chainId: string, address: string) => {
const caipAccountAddress = `${chainId}:${address}`;
const account = accounts.find(
(account) => account === caipAccountAddress
);
if (account === undefined)
throw new Error(`Account for ${caipAccountAddress} not found`);
// split chainId
const [namespace, reference] = chainId.split(":");
const rpc = rpcProvidersByChainId[Number(reference)];
if (typeof rpc === "undefined") {
throw new Error(
`Missing rpcProvider definition for chainId: ${chainId}`
);
}
const walletGrantPermissionsParameters: WalletGrantPermissionsParameters =
{
signer: {
type: "key",
data: {
id: "0xc3cE257B5e2A2ad92747dd486B38d7b4B36Ac7C9",
},
},
permissions: [
{
type: "native-token-limit",
data: {
amount: parseEther("0.5"),
},
policies: [],
required: true,
},
],
expiry: 1716846083638,
} as WalletGrantPermissionsParameters;
// send wallet_grantPermissions rpc request
const issuePermissionResponse =
await client!.request<WalletGrantPermissionsReturnType>({
topic: session!.topic,
chainId,
request: {
method: DEFAULT_EIP7715_METHODS.WALLET_GRANT_PERMISSIONS,
params: [walletGrantPermissionsParameters],
},
});
// format displayed result
return {
method: DEFAULT_EIP7715_METHODS.WALLET_GRANT_PERMISSIONS,
address,
valid: true,
result: JSON.stringify(issuePermissionResponse),
};
}
),
};
// -------- COSMOS RPC METHODS --------
const cosmosRpc = {
testSignDirect: _createJsonRpcRequestHandler(
async (chainId: string, address: string) => {
// test direct sign doc inputs
const inputs = {
fee: [{ amount: "2000", denom: "ucosm" }],
pubkey: "AgSEjOuOr991QlHCORRmdE5ahVKeyBrmtgoYepCpQGOW",
gasLimit: 200000,
accountNumber: 1,
sequence: 1,
bodyBytes:
"0a90010a1c2f636f736d6f732e62616e6b2e763162657461312e4d736753656e6412700a2d636f736d6f7331706b707472653766646b6c366766727a6c65736a6a766878686c63337234676d6d6b38727336122d636f736d6f7331717970717870713971637273737a673270767871367273307a716733797963356c7a763778751a100a0575636f736d120731323334353637",
authInfoBytes:
"0a500a460a1f2f636f736d6f732e63727970746f2e736563703235366b312e5075624b657912230a21034f04181eeba35391b858633a765c4a0c189697b40d216354d50890d350c7029012040a020801180112130a0d0a0575636f736d12043230303010c09a0c",
};
// split chainId
const [namespace, reference] = chainId.split(":");
// format sign doc
const signDoc = formatDirectSignDoc(
inputs.fee,
inputs.pubkey,
inputs.gasLimit,
inputs.accountNumber,
inputs.sequence,
inputs.bodyBytes,
reference
);
// cosmos_signDirect params
const params = {
signerAddress: address,
signDoc: stringifySignDocValues(signDoc),
};
// send message
const result = await client!.request<{ signature: string }>({
topic: session!.topic,
chainId,
request: {
method: DEFAULT_COSMOS_METHODS.COSMOS_SIGN_DIRECT,
params,
},
});
const targetChainData = chainData[namespace][reference];
if (typeof targetChainData === "undefined") {
throw new Error(`Missing chain data for chainId: ${chainId}`);
}
const valid = await verifyDirectSignature(
address,
result.signature,
signDoc
);
// format displayed result
return {
method: DEFAULT_COSMOS_METHODS.COSMOS_SIGN_DIRECT,
address,
valid,
result: result.signature,
};
}
),
testSignAmino: _createJsonRpcRequestHandler(
async (chainId: string, address: string) => {
// split chainId
const [namespace, reference] = chainId.split(":");
// test amino sign doc
const signDoc = {
msgs: [],
fee: { amount: [], gas: "23" },
chain_id: "foochain",
memo: "hello, world",
account_number: "7",
sequence: "54",
};
// cosmos_signAmino params
const params = { signerAddress: address, signDoc };
// send message
const result = await client!.request<{ signature: string }>({
topic: session!.topic,
chainId,
request: {
method: DEFAULT_COSMOS_METHODS.COSMOS_SIGN_AMINO,
params,
},
});
const targetChainData = chainData[namespace][reference];
if (typeof targetChainData === "undefined") {
throw new Error(`Missing chain data for chainId: ${chainId}`);
}
const valid = await verifyAminoSignature(
address,
result.signature,
signDoc
);
// format displayed result
return {
method: DEFAULT_COSMOS_METHODS.COSMOS_SIGN_AMINO,
address,
valid,
result: result.signature,
};
}
),
};
// -------- SOLANA RPC METHODS --------
const solanaRpc = {
testSignTransaction: _createJsonRpcRequestHandler(
async (
chainId: string,
address: string
): Promise<IFormattedRpcResponse> => {
if (!solanaPublicKeys) {
throw new Error("Could not find Solana PublicKeys.");
}
const senderPublicKey = solanaPublicKeys[address];
// rpc.walletconnect.com doesn't support solana testnet yet
const connection = new Connection(
isTestnet ? clusterApiUrl("testnet") : getProviderUrl(chainId)
);
// Using deprecated `getRecentBlockhash` over `getLatestBlockhash` here, since `mainnet-beta`
// cluster only seems to support `connection.getRecentBlockhash` currently.
const { blockhash } = await connection.getRecentBlockhash();
const transaction = new SolanaTransaction({
feePayer: senderPublicKey,
recentBlockhash: blockhash,
}).add(
SystemProgram.transfer({
fromPubkey: senderPublicKey,
toPubkey: Keypair.generate().publicKey,
lamports: 1,
})
);
const result = await client!.request<{ signature: string }>({
chainId,
topic: session!.topic,
request: {
method: DEFAULT_SOLANA_METHODS.SOL_SIGN_TRANSACTION,
params: {
feePayer: transaction.feePayer!.toBase58(),
recentBlockhash: transaction.recentBlockhash!,
instructions: transaction.instructions.map((instruction) => ({
programId: instruction.programId.toBase58(),
keys: instruction.keys.map((key) => ({
...key,
pubkey: key.pubkey.toBase58(),
})),
data: bs58.encode(instruction.data),
})),
partialSignatures: transaction.signatures.map((sign) => ({
pubkey: sign.publicKey.toBase58(),
signature: bs58.encode(sign.signature!),
})),
transaction: transaction
.serialize({ verifySignatures: false })
.toString("base64"),
},
},
});
// We only need `Buffer.from` here to satisfy the `Buffer` param type for `addSignature`.
// The resulting `UInt8Array` is equivalent to just `bs58.decode(...)`.
transaction.addSignature(
senderPublicKey,
Buffer.from(bs58.decode(result.signature))
);
const valid = transaction.verifySignatures();
return {
method: DEFAULT_SOLANA_METHODS.SOL_SIGN_TRANSACTION,
address,
valid,
result: result.signature,
};
}
),
testSignMessage: _createJsonRpcRequestHandler(
async (
chainId: string,
address: string
): Promise<IFormattedRpcResponse> => {
if (!solanaPublicKeys) {
throw new Error("Could not find Solana PublicKeys.");
}
const senderPublicKey = solanaPublicKeys[address];
// Encode message to `UInt8Array` first via `TextEncoder` so we can pass it to `bs58.encode`.
const message = bs58.encode(
new TextEncoder().encode(
`This is an example message to be signed - ${Date.now()}`
)
);
const result = await client!.request<{ signature: string }>({
chainId,
topic: session!.topic,
request: {
method: DEFAULT_SOLANA_METHODS.SOL_SIGN_MESSAGE,
params: {
pubkey: senderPublicKey.toBase58(),
message,
},
},
});
const valid = verifyMessageSignature(
senderPublicKey.toBase58(),
result.signature,
message
);
return {
method: DEFAULT_SOLANA_METHODS.SOL_SIGN_MESSAGE,
address,
valid,
result: result.signature,
};
}
),
};
// -------- POLKADOT RPC METHODS --------
const polkadotRpc = {
testSignTransaction: _createJsonRpcRequestHandler(
async (
chainId: string,
address: string
): Promise<IFormattedRpcResponse> => {
// Initialize API
const [namespace, reference] = chainId.split(":");
const targetChainData = chainData[namespace][reference];
const wsProvider = new WsProvider(targetChainData.rpc);
const api = await ApiPromise.create({ provider: wsProvider });
const call = api.tx.balances.transfer(address, 1000000000000); // 1 DOT
const runtime = await api.rpc.state.getRuntimeVersion();
const blockHash = await api.rpc.chain.getBlockHash();
const blockNumber = await api.rpc.chain.getHeader();
const transactionPayload = {
specVersion: runtime.specVersion.toHex(),
transactionVersion: runtime.transactionVersion.toHex(),
address: `${address}`,
blockHash: blockHash.toHex(),
blockNumber: blockNumber.number.toHex(),
era: "0xc501",
genesisHash: api.genesisHash.toHex(),
method: call.method.toHex(),
nonce: "0x00000000",
signedExtensions: [
"CheckNonZeroSender",
"CheckSpecVersion",
"CheckTxVersion",
"CheckGenesis",
"CheckMortality",
"CheckNonce",