js-waku/examples/eth-pm/src/BroadcastPublicKey.tsx

80 lines
2.3 KiB
TypeScript
Raw Normal View History

2021-06-29 15:46:07 +10:00
import { Button } from '@material-ui/core';
import React, { useState } from 'react';
import { createPublicKeyMessage, KeyPair } from './crypto';
import { PublicKeyMessage } from './messaging/wire';
2021-06-29 15:46:07 +10:00
import { WakuMessage, Waku } from 'js-waku';
import { Signer } from '@ethersproject/abstract-signer';
import { PublicKeyContentTopic } from './waku';
2021-06-29 15:46:07 +10:00
interface Props {
EncryptionKeyPair: KeyPair | undefined;
2021-06-29 15:46:07 +10:00
waku: Waku | undefined;
signer: Signer | undefined;
}
export default function BroadcastPublicKey({
signer,
EncryptionKeyPair,
2021-06-29 15:46:07 +10:00
waku,
}: Props) {
const [publicKeyMsg, setPublicKeyMsg] = useState<PublicKeyMessage>();
const broadcastPublicKey = () => {
if (!EncryptionKeyPair) return;
2021-06-29 15:46:07 +10:00
if (!signer) return;
if (!waku) return;
if (publicKeyMsg) {
2021-07-09 11:39:31 +10:00
encodePublicKeyWakuMessage(publicKeyMsg)
.then((wakuMsg) => {
waku.lightPush.push(wakuMsg).catch((e) => {
console.error('Failed to send Public Key Message', e);
});
})
.catch(() => {
2021-07-09 11:39:31 +10:00
console.log('Failed to encode Public Key Message in Waku Message');
});
2021-06-29 15:46:07 +10:00
} else {
createPublicKeyMessage(signer, EncryptionKeyPair.publicKey)
2021-06-29 15:46:07 +10:00
.then((msg) => {
setPublicKeyMsg(msg);
2021-07-09 11:39:31 +10:00
encodePublicKeyWakuMessage(msg)
.then((wakuMsg) => {
2021-07-12 17:10:05 +10:00
waku.lightPush
.push(wakuMsg)
.then((res) => console.log('Public Key Message pushed', res))
.catch((e) => {
console.error('Failed to send Public Key Message', e);
});
2021-07-09 11:39:31 +10:00
})
.catch(() => {
2021-07-09 11:39:31 +10:00
console.log(
'Failed to encode Public Key Message in Waku Message'
);
});
2021-06-29 15:46:07 +10:00
})
.catch((e) => {
2021-06-29 16:34:26 +10:00
console.error('Failed to create public key message', e);
2021-06-29 15:46:07 +10:00
});
}
};
return (
<Button
variant="contained"
color="primary"
onClick={broadcastPublicKey}
disabled={!EncryptionKeyPair || !waku}
2021-06-29 15:46:07 +10:00
>
Broadcast Encryption Public Key
2021-06-29 15:46:07 +10:00
</Button>
);
}
2021-07-09 11:39:31 +10:00
async function encodePublicKeyWakuMessage(
publicKeyMessage: PublicKeyMessage
2021-07-09 11:39:31 +10:00
): Promise<WakuMessage> {
const payload = publicKeyMessage.encode();
return await WakuMessage.fromBytes(payload, PublicKeyContentTopic);
2021-06-29 15:46:07 +10:00
}