Complete buy flow

This commit is contained in:
Kieran 2023-01-12 21:36:31 +00:00
parent bcdf035063
commit 192877c5d2
Signed by: Kieran
GPG Key ID: DE71CEB3925BE941
7 changed files with 170 additions and 27 deletions

View File

@ -0,0 +1,27 @@
import { useState } from "react"
export default function AsyncButton(props: any) {
const [loading, setLoading] = useState<boolean>(false);
async function handle(e : any) {
if(loading) return;
setLoading(true);
try {
if (typeof props.onClick === "function") {
let f = props.onClick(e);
if (f instanceof Promise) {
await f;
}
}
}
finally {
setLoading(false);
}
}
return (
<div {...props} className={`btn ${props.className}${loading ? "disabled" : ""}`} onClick={(e) => handle(e)}>
{props.children}
</div>
)
}

View File

@ -19,7 +19,7 @@ export default function LNURLTip(props) {
const [success, setSuccess] = useState(null);
useEffect(() => {
if (show && invoice === null) {
if (show && !props.invoice) {
loadService()
.then(a => setPayService(a))
.catch(() => setError("Failed to load LNURL service"));
@ -204,7 +204,7 @@ export default function LNURLTip(props) {
return (
<Modal onClose={() => onClose()}>
<div className="lnurl-tip" onClick={(e) => e.stopPropagation()}>
<h2> Send sats</h2>
<h2>{props.title || "⚡️ Send sats"}</h2>
{invoiceForm()}
{error ? <p className="error">{error}</p> : null}
{payInvoice()}

View File

@ -1,24 +1,52 @@
import { useEffect, useMemo, useState } from "react";
import { useSelector } from "react-redux";
import { ServiceProvider, ServiceConfig, ServiceError, HandleAvailability, ServiceErrorCode } from "../nip05/ServiceProvider";
import { useDispatch, useSelector } from "react-redux";
import {
ServiceProvider,
ServiceConfig,
ServiceError,
HandleAvailability,
ServiceErrorCode,
HandleRegisterResponse,
CheckRegisterResponse
} from "../nip05/ServiceProvider";
import AsyncButton from "./AsyncButton";
// @ts-ignore
import LNURLTip from "./LNURLTip";
// @ts-ignore
import Copy from "./Copy";
// @ts-ignore
import useProfile from "../feed/ProfileFeed";
// @ts-ignore
import useEventPublisher from "../feed/EventPublisher";
// @ts-ignore
import { resetProfile } from "../state/Users";
import { useNavigate } from "react-router-dom";
type Nip05ServiceProps = {
name: string,
service: URL | string,
about: JSX.Element,
link: string
link: string,
supportLink: string
};
type ReduxStore = any;
export default function Nip5Service(props: Nip05ServiceProps) {
const dispatch = useDispatch();
const navigate = useNavigate();
const pubkey = useSelector<ReduxStore, string>(s => s.login.publicKey);
const user: any = useProfile(pubkey);
const publisher = useEventPublisher();
const svc = new ServiceProvider(props.service);
const [serviceConfig, setServiceConfig] = useState<ServiceConfig>();
const [error, setError] = useState<ServiceError>();
const [handle, setHandle] = useState<string>("");
const [domain, setDomain] = useState<string>("");
const [availabilityResponse, setAvailabilityResponse] = useState<HandleAvailability>();
const [registerResponse, setRegisterResponse] = useState<HandleRegisterResponse>();
const [showInvoice, setShowInvoice] = useState<boolean>(false);
const [registerStatus, setRegisterStatus] = useState<CheckRegisterResponse>();
const domainConfig = useMemo(() => serviceConfig?.domains.find(a => a.name === domain), [domain]);
@ -38,11 +66,12 @@ export default function Nip5Service(props: Nip05ServiceProps) {
}, [props]);
useEffect(() => {
if(handle.length === 0) {
if (handle.length === 0) {
setAvailabilityResponse(undefined);
}
if (handle && domain) {
if (!domainConfig?.regex[0].match(handle)) {
let rx = new RegExp(domainConfig?.regex[0] ?? "", domainConfig?.regex[1] ?? "");
if (!rx.test(handle)) {
setAvailabilityResponse({ available: false, why: "REGEX" });
return;
}
@ -58,6 +87,28 @@ export default function Nip5Service(props: Nip05ServiceProps) {
}
}, [handle, domain]);
useEffect(() => {
if (registerResponse && showInvoice) {
let t = setInterval(async () => {
let status = await svc.CheckRegistration(registerResponse.token);
if ('error' in status) {
setError(status);
setRegisterResponse(undefined);
setShowInvoice(false);
} else {
let result: CheckRegisterResponse = status;
if (result.available && result.paid) {
setShowInvoice(false);
setRegisterStatus(status);
setRegisterResponse(undefined);
setError(undefined);
}
}
}, 2_000);
return () => clearInterval(t);
}
}, [registerResponse, showInvoice])
function mapError(e: ServiceErrorCode, t: string | null): string | undefined {
let whyMap = new Map([
["TOO_SHORT", "name too short"],
@ -69,30 +120,72 @@ export default function Nip5Service(props: Nip05ServiceProps) {
]);
return whyMap.get(e === "DISALLOWED" ? `${e}_${t}` : e);
}
async function startBuy(handle: string, domain: string) {
if (registerResponse) {
setShowInvoice(true);
return;
}
let rsp = await svc.RegisterHandle(handle, domain, pubkey);
if ('error' in rsp) {
setError(rsp);
} else {
setRegisterResponse(rsp);
setShowInvoice(true);
}
}
async function updateProfile(handle: string, domain: string) {
let newProfile = {
...user,
nip05: `${handle}@${domain}`
};
debugger;
delete newProfile["loaded"];
delete newProfile["fromEvent"];
delete newProfile["pubkey"];
let ev = await publisher.metadata(newProfile);
dispatch(resetProfile(pubkey));
publisher.broadcast(ev);
navigate("/settings");
}
return (
<>
<h3>{props.name}</h3>
{props.about}
<p>Find out more info about {props.name} at <a href={props.link} target="_blank" rel="noreferrer">{props.link}</a></p>
{error && <b className="error">{error.error}</b>}
<div className="flex mb10">
{!registerStatus && <div className="flex mb10">
<input type="text" placeholder="Handle" value={handle} onChange={(e) => setHandle(e.target.value)} />
&nbsp;@&nbsp;
<select value={domain} onChange={(e) => setDomain(e.target.value)}>
{serviceConfig?.domains.map(a => <option selected={a.default}>{a.name}</option>)}
{serviceConfig?.domains.map(a => <option key={a.name}>{a.name}</option>)}
</select>
</div>
{availabilityResponse?.available && <div className="flex">
<div>
{availabilityResponse.quote?.price.toLocaleString()} sats
&nbsp;
</div>}
{availabilityResponse?.available && !registerStatus && <div className="flex">
<div className="mr10">
{availabilityResponse.quote?.price.toLocaleString()} sats<br />
<small>{availabilityResponse.quote?.data.type}</small>
</div>
<input type="text" className="f-grow mr10" placeholder="pubkey" value={pubkey} disabled={pubkey ? true : false} />
<div className="btn">Buy Now</div>
<AsyncButton onClick={() => startBuy(handle, domain)}>Buy Now</AsyncButton>
</div>}
{availabilityResponse?.available === false && <div className="flex">
{availabilityResponse?.available === false && !registerStatus && <div className="flex">
<b className="error">Not available: {mapError(availabilityResponse.why!, availabilityResponse.reasonTag || null)}</b>
</div>}
<LNURLTip invoice={registerResponse?.invoice} show={showInvoice} onClose={() => setShowInvoice(false)} title={`Buying ${handle}@${domain}`} />
{registerStatus?.paid && <div className="flex f-col">
<h4>Order Paid!</h4>
Your new NIP-05 handle is: <code>{handle}@{domain}</code>
<h3>Account Support</h3>
Please make sure to save the following password in order to manage your handle in the future
<Copy text={registerStatus.password} />
<p>Go to <a href={props.supportLink} target="_blank" rel="noreferrer">account page</a></p>
<h4>Activate Now</h4>
<AsyncButton onClick={() => updateProfile(handle, domain)}>Add to Profile</AsyncButton>
</div>}
</>
)
}

View File

@ -91,6 +91,10 @@ code {
font-weight: bold;
}
.btn.disabled {
color: var(--gray-light);
}
.btn:hover {
background-color: var(--gray);
}

View File

@ -25,7 +25,11 @@ export type HandleAvailability = {
export type HandleQuote = {
price: number,
data: any
data: HandleData
}
export type HandleData = {
type: string | "premium" | "short"
}
export type HandleRegisterResponse = {
@ -35,6 +39,12 @@ export type HandleRegisterResponse = {
token: string
}
export type CheckRegisterResponse = {
available: boolean,
paid: boolean,
password: string
}
export class ServiceProvider {
readonly url: URL | string
@ -54,7 +64,7 @@ export class ServiceProvider {
return await this._GetJson("/registration/register", "PUT", { name: handle, domain, pk: pubkey });
}
async CheckRegistration(token: string): Promise<any> {
async CheckRegistration(token: string): Promise<CheckRegisterResponse | ServiceError> {
return await this._GetJson("/registration/register/check", "POST", undefined, {
authorization: token
});

View File

@ -70,7 +70,11 @@ export default class Connection {
for (let p of this.Pending) {
this._SendJson(p);
}
this.Pending = [];
for (let s of Object.values(this.Subscriptions)) {
this._SendSubscription(s, s.ToObject());
}
this._UpdateState();
}
@ -159,15 +163,7 @@ export default class Connection {
return;
}
let req = ["REQ", sub.Id, subObj];
if (sub.OrSubs.length > 0) {
req = [
...req,
...sub.OrSubs.map(o => o.ToObject())
];
}
sub.Started[this.Address] = new Date().getTime();
this._SendJson(req);
this._SendSubscription(sub, subObj);
this.Subscriptions[sub.Id] = sub;
}
@ -227,6 +223,18 @@ export default class Connection {
}
}
_SendSubscription(sub, subObj) {
let req = ["REQ", sub.Id, subObj];
if (sub.OrSubs.length > 0) {
req = [
...req,
...sub.OrSubs.map(o => o.ToObject())
];
}
sub.Started[this.Address] = new Date().getTime();
this._SendJson(req);
}
_SendJson(obj) {
if (this.Socket?.readyState !== WebSocket.OPEN) {
this.Pending.push(obj);

View File

@ -12,6 +12,7 @@ export default function VerificationPage() {
name: "Nostr Plebs",
service: "https://nostrplebs.com/api/v1",
link: "https://nostrplebs.com/",
supportLink: "https://nostrplebs.com/manage",
about: <>
<p>Nostr Plebs is one of the first NIP-05 providers in the space and offers a good collection of domains at reasonable prices</p>
</>