Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connect Contracts Websocket On App Startup #215

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion components/BitcoinBrowser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const BitcoinBrowser = () => {

const navigate = (txid: string) => {
router.prefetch(`/${txid}`);
window.location.replace(`/${txid}`)
router.push(`/${txid}`)
};

const handleKeyUp = (e: any) => {
Expand Down
10 changes: 5 additions & 5 deletions components/BoostpowButton/BoostPopup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,14 @@ const BoostPopup = ({ content, onClose, tagList, defaultTag }: BoostPopupProps)
};

const handleChangeDifficulty = (e: React.ChangeEvent<HTMLInputElement>) => {
e.preventDefault()
setDifficulty(parseFloat(e.target.value))
setPosition(0.5)
e.preventDefault();
setDifficulty(parseFloat((e.target as any).value));
setPosition(0.5);
}

const handleChangePosition = (e: React.ChangeEvent<HTMLInputElement>) => {
e.preventDefault()
setPosition(parseFloat(e.target.value))
e.preventDefault();
setPosition(parseFloat((e.target as any).value));
}

const wallet = useWallet()
Expand Down
2 changes: 1 addition & 1 deletion components/ChatComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ const ChatComposer = ({

const handleChange = (event: React.FormEvent<HTMLTextAreaElement>) => {
event.preventDefault();
setInputValue((event.target as HTMLTextAreaElement).value);
setInputValue((event.target as any).value);
};

return (
Expand Down
4 changes: 2 additions & 2 deletions components/IssueCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ useEffect(() => {

{addingBounty ? (
<div className="flex space-x-2">
<input type="number" onChange={(e) => setSatoshis(Number(e.target.value))} className="border p-2 rounded" placeholder="Enter Satoshis" />
<input type="number" onChange={(e) => setSatoshis(Number((e.target as any).value))} className="border p-2 rounded" placeholder="Enter Satoshis" />
<button className="bg-blue-500 text-white px-4 py-2 rounded" onClick={handleConfirmClick}>Confirm</button>
</div>
) : (
Expand All @@ -284,7 +284,7 @@ useEffect(() => {
<div className="fixed inset-0 bg-gray-500 bg-opacity-50 flex justify-center items-center">
<div className="bg-white p-4 rounded shadow-lg">
<label htmlFor="publicKey" className="block text-sm font-medium text-gray-600">Enter BSV Public Key:</label>
<input type="text" id="publicKey" value={publicKeyInput} onChange={(e) => setPublicKeyInput(e.target.value)} className="mt-1 p-2 w-full border rounded-md"/>
<input type="text" id="publicKey" value={publicKeyInput} onChange={(e) => setPublicKeyInput((e.target as any).value)} className="mt-1 p-2 w-full border rounded-md"/>
<button onClick={handleAssignSubmit} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mt-2">
Submit
</button>
Expand Down
10 changes: 5 additions & 5 deletions components/NewIssueForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ const NewIssueForm: React.FC<NewIssueFormProps> = ({ onSubmit }) => {

return (
<div className="border p-4 rounded-md space-y-2">
<input type="text" onChange={(e) => setOrganization(e.target.value)} className="border p-2 w-full rounded" placeholder="Organization" />
<input type="text" onChange={(e) => setRepo(e.target.value)} className="border p-2 w-full rounded" placeholder="Repository" />
<input type="text" onChange={(e) => setTitle(e.target.value)} className="border p-2 w-full rounded" placeholder="Title" />
<textarea onChange={(e) => setDescription(e.target.value)} className="border p-2 w-full rounded" placeholder="Description"></textarea>
<input type="number" onChange={(e) => setBounty(e.target.value)} className="border p-2 w-full rounded" placeholder="Bounty in Satoshis" />
<input type="text" onChange={(e: any) => setOrganization(e.target.value)} className="border p-2 w-full rounded" placeholder="Organization" />
<input type="text" onChange={(e: any) => setRepo(e.target.value)} className="border p-2 w-full rounded" placeholder="Repository" />
<input type="text" onChange={(e: any) => setTitle(e.target.value)} className="border p-2 w-full rounded" placeholder="Title" />
<textarea onChange={(e: any) => setDescription(e.target.value)} className="border p-2 w-full rounded" placeholder="Description"></textarea>
<input type="number" onChange={(e: any) => setBounty(e.target.value)} className="border p-2 w-full rounded" placeholder="Bounty in Satoshis" />
<button className="bg-blue-500 text-white px-4 py-2 rounded" onClick={handleSubmit}>Submit</button>
</div>
);
Expand Down
2 changes: 2 additions & 0 deletions components/SocialEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,15 @@ export const SocialEditor: FC<PropsWithChildren<SocialEditorProps>> = ({

// Limit the number of files to 4
if (files.length > 4) {
// @ts-ignore
alert('Please select up to 4 images.');
return;
}

for (let i = 0; i < files.length; i++) {
const file = files[i];
if (!file.type.startsWith('image/')) {
// @ts-ignore
alert('Please select only image files.');
return;
}
Expand Down
43 changes: 33 additions & 10 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,54 @@
/* eslint-disable react/jsx-props-no-spreading */
import type { AppProps } from 'next/app';
import Head from 'next/head';
import Script from 'next/script';
import { SensiletProvider } from '../context/SensiletContext'

import { GetServerSideProps } from 'next'

import '../styles/globals.css';
import 'react-tooltip/dist/react-tooltip.css';

import Head from 'next/head';

import { ThemeProvider } from 'next-themes';
import { Toaster } from 'react-hot-toast';
import { init } from '@socialgouv/matomo-next';
import { useEffect } from 'react';
import { config } from '../template_config';
import { RelayProvider } from '../context/RelayContext';
import { HandCashProvider } from '../context/HandCashContext';
import { TuneProvider } from '../context/TuningContext';
import Locales from '../context/LocalContext';
import { BitcoinProvider } from '../context/BitcoinContext';
import { TwetchProvider } from '../context/TwetchContext';
import { LocalWalletProvider } from '../context/LocalWalletContext';
import 'react-tooltip/dist/react-tooltip.css';

import { useSubdomain } from '../hooks/subdomain'
import { SensiletProvider } from '../context/SensiletContext';

import { useContractsWebSocket } from '../services/contracts/websocket';

export default function App({ Component, pageProps }: AppProps) {
//const { openGraphData = [] } = pageProps;
const { subdomain } = useSubdomain()

const { socket, subscribeContract, unsubscribeContract } = useContractsWebSocket();

/*
The following is an example of how to subscribe and unsubscribe to a contract
via the contracts websocket connection. This may be done in any page or component
that calls useContractsWebSocket(), and each component should call unsubscribe
when it is unmounted, as in the example below.
*/
useEffect(() => {

if (socket?.readyState === WebSocket.OPEN) {

const exampleOrigin = '41eccb6160786c94fe4ca2c29f933a8014af9dc723a210870c5a69b9172ca90a_0';

subscribeContract({ origin: exampleOrigin });

return () => {

unsubscribeContract({ origin: exampleOrigin });

};

}
}, [socket?.readyState]);

const openGraphData = [
{
Expand Down Expand Up @@ -70,7 +93,7 @@ export default function App({ Component, pageProps }: AppProps) {
content: "website",
key: "website",
},
]
];

useEffect(() => {
const MATOMO_URL = String(process.env.NEXT_PUBLIC_MATOMO_URL);
Expand Down
10 changes: 5 additions & 5 deletions pages/interests/[txid].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -184,13 +184,13 @@ function PersonalInterestsPage() {

console.log('interest.remove', interest)

const result = await interest.methods.remove((sigResponses: any) => {
return findSig(sigResponses, new bsv.PublicKey(sensiletPublicKey))
})
const publicKey = new bsv.PublicKey(sensiletPublicKey as string);

const result = await interest.methods.remove((sigResponses: any) => findSig(sigResponses, publicKey));

console.log('interest.remove.result', result)
console.log('interest.remove.result', result);

setInterestRemoved(true)
setInterestRemoved(true);

try {

Expand Down
52 changes: 52 additions & 0 deletions services/contracts/websocket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@

import { useState } from 'react';
import useWebSocket from 'react-use-websocket';

const CONTRACTS_WEBSOCKET_URL = 'wss://hls.pow.co/websockets/contracts';

export function useContractsWebSocket() {
const [socket, setSocket] = useState<WebSocket | null>(null);

const hook = useWebSocket(CONTRACTS_WEBSOCKET_URL, {
onOpen: async () => {
console.log('ws.contracts.onOpen');
},
onMessage: async (message) => {
console.log('ws.contracts.onMessage', message);
},
onClose: async () => {
console.log('ws.contracts.onClose');
},
});

if (!socket && hook.getWebSocket()) {
setSocket(hook.getWebSocket() as WebSocket);
}

function subscribeContract({ origin }: { origin: string }) {
if (socket) {
(socket as WebSocket).send(JSON.stringify({
method: 'contract.subscribe',
params: { origin },
}));
}
}


function unsubscribeContract({ origin }: { origin: string }) {
if (socket) {
(socket as WebSocket).send(JSON.stringify({
method: 'contract.subscribe',
params: { origin },
}));
}
}

return {
hook,
socket,
subscribeContract,
unsubscribeContract,
};

}
2 changes: 1 addition & 1 deletion wallets/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default class LocalWallet extends Wallet {

this.seed = seed

const hdPrivateKey = bsv.HDPrivateKey.fromSeed(this.seed.toString('hex'))
const hdPrivateKey = bsv.HDPrivateKey.fromSeed(this.seed.toString('hex'), bsv.Networks.mainnet);

const derivationPaths = {
sensiletDefault: `m/44'/0'/0'/0/0`,
Expand Down