Skip to content

Instantly share code, notes, and snippets.

@sbddesign
Created March 18, 2023 14:02
Show Gist options
  • Save sbddesign/ccacfd0731b4248441e0f99b325068e1 to your computer and use it in GitHub Desktop.
Save sbddesign/ccacfd0731b4248441e0f99b325068e1 to your computer and use it in GitHub Desktop.
Using Nostr Tools in a Typescript NextJS project
import Head from 'next/head'
import Image from 'next/image'
import { Inter } from 'next/font/google'
import { generatePrivateKey, getPublicKey, validateEvent, verifySignature, signEvent, getEventHash, UnsignedEvent } from 'nostr-tools'
import React from 'react'
export default function Home() {
const [privKey, setPrivKey] = React.useState('')
const [pubKey, setPubKey] = React.useState('')
const [event, setEvent] = React.useState(JSON.stringify({}))
const handlePrivKeyClick = () => {
if(privKey === '') setPrivKey( generatePrivateKey() )
console.log(privKey)
}
const handlePubKeyClick = () => {
if(pubKey === '' && privKey !== '') setPubKey( getPublicKey(privKey) )
console.log(pubKey)
}
const handleResetKeysClick = () => {
setPrivKey('')
setPubKey('')
}
// let event = {
// kind: 1,
// created_at: Math.floor(Date.now() / 1000),
// tags: [],
// content: 'hello',
// pubKey: pubKey
// }
const createEvent = ():UnsignedEvent => {
return {
kind: 1,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: 'hello',
pubkey: getPublicKey(privKey)
}
}
const handleEventClick = ()=>{
let unsignedEvent:UnsignedEvent = createEvent()
console.log(unsignedEvent)
setEvent(JSON.stringify(unsignedEvent))
let eventId:string = getEventHash(unsignedEvent)
console.log(eventId)
let eventSig = signEvent(unsignedEvent, privKey)
console.log(eventSig)
let signedEvent = {...unsignedEvent, id: eventId, sig:eventSig}
console.log(signedEvent)
console.log(validateEvent(signedEvent))
console.log(verifySignature(signedEvent))
}
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<div>
<h3>Your private key</h3>
<code>{privKey}</code>
<h3>Your public key</h3>
<code>{pubKey}</code>
<h3>Your event</h3>
<code>{event}</code>
<hr />
<button onClick={handlePrivKeyClick}>
Generate Priv Key
</button>
<button onClick={handlePubKeyClick}>
Generate Pub Key
</button>
<button onClick={handleResetKeysClick}>
Reset Keys
</button>
<button onClick={handleEventClick}>
Event Thing
</button>
</div>
</main>
</>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment