-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIntro.tsx
More file actions
743 lines (699 loc) · 22 KB
/
Copy pathIntro.tsx
File metadata and controls
743 lines (699 loc) · 22 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
import React, { createFactory, useCallback, useEffect, useState } from "react"
import { useRef } from "react"
import { useNostrEvents, dateToUnix, useProfile } from "nostr-react"
import { Event as NostrEvent } from "nostr-tools"
import logo from "./assets/logo-dark.svg"
import { initiateOrdSnap } from "./services/metamask"
import { SnapIdentity } from "@astrox/ord-snap-adapter"
import {
SignMessageResponse,
UTXO,
TXSendBTC,
ErrorPayload,
Delegation,
GetSnapsResponse,
} from "@astrox/ord-snap-types"
import { Avatar, Switch } from "antd"
import { UserOutlined } from "@ant-design/icons"
import BulletScreen, { StyledBullet } from "rc-bullets-ts"
export function ProfileWidget({ pubkey }: { pubkey: string }) {
const { data: userData } = useProfile({
pubkey,
})
const [npub, setNpub] = useState<string | undefined>(undefined)
useEffect(() => {
const length = userData?.npub.length ?? 63
const prefix = userData?.npub.substring(0, 6)
const endFix = userData?.npub.substring(length - 6, length)
setNpub(`${prefix}...${endFix}`)
}, [userData])
return (
<>
<div>
<div
style={{
display: "flex",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
}}
>
<div
style={{
display: "flex",
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
}}
>
<div>
{userData?.picture ? (
<Avatar src={userData?.picture} size={32} />
) : (
<Avatar size={32} icon={<UserOutlined />} />
)}
</div>
<div
style={{
wordBreak: "break-all",
marginLeft: 8,
fontSize: 16,
}}
>
{userData?.name}
</div>
</div>
<p
style={{
wordBreak: "break-all",
marginLeft: 8,
fontSize: 12,
}}
>
{npub}
</p>
</div>
</div>
</>
)
}
export default function Demo({ feed = [] }: { feed: NostrEvent[] }) {
// 弹幕屏幕
console.log(feed.length)
const [screen, setScreen] = useState(null)
// 弹幕内容
const [enabled, setEnabled] = useState<boolean>(false)
const [index, setIndex] = useState(0)
useEffect(() => {
if (enabled === true) {
if (!screen) {
// 给页面中某个元素初始化弹幕屏幕,一般为一个大区块。此处的配置项全局生效
let s = new BulletScreen(".screen", { duration: 20 })
// or
// let s=new BulletScreen(document.querySelector('.screen));
setScreen(s)
sendList(s)
} else {
sendList(screen)
}
}
}, [enabled, index])
function sendList(s: BulletScreen) {
setTimeout(() => {
;(s! as any).push(
<>
<p>{feed[index].content}</p>
</>,
)
if (index === feed.length - 1) {
setScreen(new BulletScreen(".screen", { duration: 20 }))
setIndex(0)
} else {
setIndex(index + 1)
}
}, 3000)
}
// 发送弹幕
const handleEnabled = () => {
setEnabled(!enabled)
}
return (
<main>
<div
className="screen"
style={{
width: "100%",
height: "100%",
position: "fixed",
top: 0,
left: 0,
zIndex: enabled ? 999 : -1,
}}
></div>
<Switch
checkedChildren="ON"
unCheckedChildren="OFF"
onClick={handleEnabled}
style={{ position: "fixed", top: 32, right: 32, zIndex: 999 }}
/>
</main>
)
}
// import ReactTimeAgo from "react-time-ago"
// import { canisterId, createActor } from "./services"
export function Intro() {
const now = useRef(new Date(Date.now() - 24 * 60 * 60 * 1000))
const { events } = useNostrEvents({
filter: {
since: dateToUnix(now.current), // all new events from now
kinds: [1],
"#t": ["ordinals", "bitcoin", "nft", "nostr"],
limit: 10,
},
// enabled: true,
})
const [ago, setAgo] = useState<Date | undefined>(undefined)
const [appInfo, setAppInfo] = useState<GetSnapsResponse[string] | undefined>(
undefined,
)
const [publicKey, setPublicKey] = useState<string | undefined>(undefined)
const [nPub, setNPub] = useState<string | undefined>(undefined)
const [nProfile, setNProfile] = useState<string | undefined>(undefined)
const [installed, setInstalled] = useState<boolean>(false)
const [message, setMessage] = useState<string | undefined>(undefined)
const [toEncryptMessage, setToEncryptMessage] = useState<string | undefined>(
undefined,
)
const [toDecryptMessage, setToDecryptMessage] = useState<string | undefined>(
undefined,
)
const [theirPublicKey, setTheirPublicKey] = useState<string | undefined>(
undefined,
)
const [theirDecryptPublicKey, setTheirDecryptPublicKey] = useState<
string | undefined
>(undefined)
const [messageEncrypted, setMessageEncrypted] = useState<string | undefined>(
undefined,
)
const [messageDecrypted, setMessageDecrypted] = useState<string | undefined>(
undefined,
)
const [signedMessage, setSignedMessage] = useState<
SignMessageResponse | undefined
>(undefined)
const [delegated, setDelegated] = useState<string | undefined>(undefined)
const [delegatedObject, setDelegatedObject] = useState<
Delegation | undefined
>(undefined)
const [snapIdentity, setSnapIdentity] = useState<SnapIdentity | undefined>(
undefined,
)
const [accs, setAccs] = useState<string | undefined>(undefined)
const [host, setHost] = useState<string | undefined>("https://unisat.io/api")
const [utxoAddress, setUtxoAddress] = useState<string | undefined>(undefined)
// to: string, amount: number, utxos: UTXO[], autoAdjust: boolean, feeRate: number
const [sendTo, setSendTo] = useState<string | undefined>(undefined)
const [sendAmount, setSendAmount] = useState<number | undefined>(undefined)
const [sendAutoAdjust, setAutoAdjust] = useState<boolean>(false)
const [sendFeeRate, setSendFeeRate] = useState<number | undefined>(undefined)
const [queryDomain, setQueryDomain] = useState<string | undefined>(undefined)
const installSnap = useCallback(async () => {
const installResult = await initiateOrdSnap("nostr") //mainnet, local, nostr
if (!installResult.isSnapInstalled) {
setInstalled(false)
} else {
setInstalled(true)
setSnapIdentity(await installResult.snap?.createSnapIdentity())
}
}, [])
const getPublicKey = async () => {
console.log(snapIdentity?.api.getAppInfo())
setPublicKey(snapIdentity?.publicKey)
setAppInfo(await snapIdentity?.api.getAppInfo())
setNPub(await snapIdentity?.api.nostr.getNPub())
setNProfile(await snapIdentity?.api.nostr.getNProfile())
}
const delegate = async () => {
const dele = await snapIdentity?.api.nostr.delegate(delegated!)
setDelegatedObject(dele)
}
const signMessage = async () => {
const signed = await snapIdentity?.api.nostr.sign(message!)
setSignedMessage(signed!)
}
const encryptMessage = async () => {
const encrypted = await snapIdentity?.api.nostr.encryptMessage(
theirPublicKey!,
toEncryptMessage!,
)
setMessageEncrypted(JSON.stringify(encrypted))
}
const decryptMessage = async () => {
const encrypted = await snapIdentity?.api.nostr.decryptMessage(
theirDecryptPublicKey!,
toDecryptMessage!,
)
setMessageDecrypted(JSON.stringify(encrypted))
}
const getAddress = async () => {
console.log(snapIdentity?.api)
const ad = await snapIdentity?.api.ord.getAddress()
setAccs(ad)
}
const addNextAccount = async () => {
console.log(snapIdentity?.api)
const ad = await snapIdentity?.api.ord.addNextAccount()
console.log(ad)
}
const getSatsDomainInfo = async () => {
const ad = await snapIdentity?.api.ord.getSatsDomainInfo(queryDomain!)
console.log(ad)
}
const sendBTC = async () => {
const account = await snapIdentity?.api.ord.getAddress()
const sendUtxos = await snapIdentity?.api.ord.getAddressUtxo(account!)
console.log({
sendTo,
sendAmount,
sendUtxos: JSON.parse(sendUtxos!) as UTXO[],
sendAutoAdjust,
sendFeeRate,
})
try {
const tx = await snapIdentity?.api.ord.sendBTC(
sendTo!,
sendAmount!,
JSON.parse(sendUtxos!) as UTXO[],
sendAutoAdjust!,
sendFeeRate!,
)
console.log(tx)
} catch (error) {
throw error
// console.log(
// (JSON.parse((error as Error).message) as ErrorPayload).message,
// )
}
}
const initWallet = async () => {
console.log(snapIdentity?.api)
await snapIdentity?.api.ord.initWallet(host, {
"X-Client": "UniSat Wallet",
"X-Version": "1.1.12",
"Content-Type": "application/json;charset=utf-8",
})
}
const getAddressUtxos = async () => {
console.log(snapIdentity?.api)
const utxos = await snapIdentity?.api.ord.getAddressUtxo(
utxoAddress ?? accs!,
)
console.log(utxos)
}
const getAddressBalance = async () => {
console.log(snapIdentity?.api)
const balance = await snapIdentity?.api.ord.getAddressBalance(
utxoAddress ?? accs!,
)
console.log(balance)
}
useEffect(() => {
;(async () => {
if (!snapIdentity) {
await installSnap()
} else {
await getPublicKey()
await initWallet()
await getAddress()
}
})()
}, [snapIdentity])
return (
<>
<header className="App-header">
<Demo feed={events} />
<img src={logo} className="App-logo" alt="logo" />
<p style={{ fontSize: "2em", marginBottom: "0.5em" }}>
OrdSnap: Bitcoin in MetaMask
</p>
<h1>AppInfo</h1>
<div
style={{
display: "flex",
fontSize: "0.7em",
textAlign: "left",
padding: "2em",
borderRadius: "30px",
flexDirection: "column",
background: "rgb(220 218 224 / 25%)",
flex: 1,
width: "32em",
}}
>
{installed ? (
<>
<div
style={{
wordBreak: "break-all",
maxWidth: "100%",
margin: "1em 0",
}}
>
<code>App Info </code>
<p>{JSON.stringify(appInfo)}</p>
</div>
</>
) : null}
</div>
<h1>Wallet</h1>
<div
style={{
display: "flex",
fontSize: "0.7em",
textAlign: "left",
padding: "2em",
borderRadius: "30px",
flexDirection: "column",
background: "rgb(220 218 224 / 25%)",
flex: 1,
width: "32em",
}}
>
{installed ? (
<>
<div
style={{
wordBreak: "break-all",
maxWidth: "100%",
margin: "1em 0",
}}
>
<code>Current Accounts: </code>
<p>{accs}</p>
</div>
<button className="demo-button-2" onClick={addNextAccount}>
Add Account
</button>
<label style={{ marginBottom: 16, marginTop: 16 }}>
Input Http Host
</label>
<input
aria-label="Initialized http service"
style={{ padding: "1em" }}
onChange={async (e) => {
setHost(e.target.value)
}}
defaultValue={"https://unisat.io/api"}
/>
<button className="demo-button-2" onClick={initWallet}>
Init Wallet
</button>
<label style={{ marginBottom: 16, marginTop: 16 }}>
Get SatsDomain
</label>
<input
aria-label="Get UTXO"
style={{ padding: "1em" }}
onChange={async (e) => {
setQueryDomain(e.target.value)
}}
/>
<button className="demo-button-2" onClick={getSatsDomainInfo}>
Get SatsDomain
</button>
<label style={{ marginBottom: 16, marginTop: 16 }}>
Get UTXO
</label>
<input
aria-label="Get UTXO"
style={{ padding: "1em" }}
onChange={async (e) => {
setUtxoAddress(e.target.value)
}}
defaultValue={utxoAddress ?? accs}
/>
<button className="demo-button-2" onClick={getAddressUtxos}>
Get UTXOS
</button>
<button className="demo-button-2" onClick={getAddressBalance}>
Get Balance
</button>
<label style={{ marginBottom: 16, marginTop: 16 }}>
Send BTC To
</label>
<input
aria-label="to"
style={{ padding: "1em" }}
onChange={async (e) => {
setSendTo(e.target.value)
}}
/>
<label style={{ marginBottom: 16, marginTop: 16 }}>
Send BTC Amount
</label>
<input
aria-label="amount"
style={{ padding: "1em" }}
type="number"
onChange={async (e) => {
setSendAmount(Number.parseInt(e.target.value, 10))
}}
/>
<label style={{ marginBottom: 16, marginTop: 16 }}>
Send BTC Fee Rate
</label>
<input
aria-label="feeRate"
style={{ padding: "1em" }}
type="number"
onChange={async (e) => {
setSendFeeRate(Number.parseInt(e.target.value, 10))
}}
/>
<label style={{ marginBottom: 16, marginTop: 16 }}>
Send BTC AutoAdjust?
</label>
<select
aria-label="autoAdust"
name="autoAdust"
id="autoAdust"
style={{ marginBottom: 16, marginTop: 16, fontSize: 16 }}
onChange={(e) => {
const sel = e.target.value === "true" ? true : false
setAutoAdjust(sel)
}}
defaultValue={"true"}
>
<option value="true" style={{ padding: 8 }}>
true
</option>
<option value="false" style={{ padding: 8 }}>
false
</option>
</select>
<button className="demo-button-2" onClick={sendBTC}>
Send BTC
</button>
</>
) : null}
</div>
<h1>Nostr</h1>
<div
style={{
display: "flex",
fontSize: "0.7em",
textAlign: "left",
padding: "2em",
borderRadius: "30px",
flexDirection: "column",
background: "rgb(220 218 224 / 25%)",
flex: 1,
width: "32em",
}}
>
{installed ? (
<>
<div style={{ width: "100%", minWidth: "100%" }}>
<code>PublicKey is:</code>
<p style={{ fontSize: 16 }}>{publicKey ?? "...loading"}</p>
</div>
<div style={{ width: "100%", minWidth: "100%" }}>
<code>NPub is:</code>
<p style={{ fontSize: 16 }}>{nPub ?? "...loading"}</p>
</div>
<div style={{ width: "100%", minWidth: "100%" }}>
<code>NProfile is:</code>
<p style={{ fontSize: 16 }}>{nProfile ?? "...loading"}</p>
</div>
</>
) : (
<button className="demo-button" onClick={installSnap}>
Install Snap
</button>
)}
{installed ? (
<>
<h2>Delegate To</h2>
<label style={{ marginBottom: 16 }}>
Input nPub or nProfile To Delegate
</label>
<input
aria-label="To delegate a publickey"
style={{ padding: "1em" }}
onChange={(e) => {
setDelegated(e.target.value)
}}
/>
{delegatedObject !== undefined ? (
<div
style={{
wordBreak: "break-all",
maxWidth: "100%",
margin: "1em 0",
}}
>
<code>delegate object is : </code>
<p>{JSON.stringify(delegatedObject)}</p>
</div>
) : null}
<button className="demo-button" onClick={delegate}>
Delegate a pubkey
</button>
</>
) : null}
{installed ? (
<>
<h2>Sign Message</h2>
<label style={{ marginBottom: 16 }}>Input Messsage To Sign</label>
<input
aria-label="To Sign a message"
style={{ padding: "1em" }}
onChange={(e) => {
setMessage(e.target.value)
}}
/>
<button className="demo-button" onClick={signMessage}>
Sign Message
</button>
</>
) : null}
{signedMessage?.signature !== undefined ? (
<div
style={{
wordBreak: "break-all",
maxWidth: "100%",
margin: "1em 0",
}}
>
<code>Signature is : </code>
<p>{signedMessage?.signature}</p>
</div>
) : null}
<h2>Encrypt Message</h2>
{installed ? (
<>
<label style={{ marginBottom: 16 }}>
Input Message To Encrypt
</label>
<input
aria-label="To Encrypt a message"
style={{ padding: "1em" }}
onChange={(e) => {
setToEncryptMessage(e.target.value)
}}
/>
<label style={{ marginBottom: 16 }}>Input Their PublicKey</label>
<input
aria-label="We need their publicKey"
style={{ padding: "1em" }}
onChange={(e) => {
setTheirPublicKey(e.target.value)
}}
/>
<button className="demo-button" onClick={encryptMessage}>
Encrypt Message
</button>
</>
) : null}
{messageEncrypted !== undefined ? (
<div
style={{
wordBreak: "break-all",
maxWidth: "100%",
margin: "1em 0",
}}
>
<code>Encrypted Message is : </code>
<p>{messageEncrypted}</p>
</div>
) : null}
<h2>Decrypt Message</h2>
{installed ? (
<>
<label style={{ marginBottom: 16 }}>
Input CipherText To Decrypt
</label>
<input
aria-label="To Decrypt a message"
style={{ padding: "1em" }}
onChange={(e) => {
setToDecryptMessage(e.target.value)
}}
/>
<label style={{ marginBottom: 16 }}>Input Their PublicKey</label>
<input
aria-label="We need their publicKey"
style={{ padding: "1em" }}
onChange={(e) => {
setTheirDecryptPublicKey(e.target.value)
}}
/>
<button className="demo-button" onClick={decryptMessage}>
Decrypt Message
</button>
</>
) : null}
{messageDecrypted !== undefined ? (
<div
style={{
wordBreak: "break-all",
maxWidth: "100%",
margin: "1em 0",
}}
>
<code>Decrypted Message is : </code>
<p>{messageDecrypted}</p>
</div>
) : null}
<>
{events.map((event) => (
<div
key={event.id}
style={{ margin: 16, borderBottom: "1px solid #333" }}
>
<ProfileWidget pubkey={event.pubkey} />
<p
style={{
wordBreak: "break-all",
width: "100%",
}}
>
{/* <ReactTimeAgo
date={new Date(event.created_at)}
locale="en-US"
/> */}
<div style={{ fontSize: 16 }}>{event.content}</div>
</p>
</div>
))}
</>
</div>
<p style={{ fontSize: "0.6em" }}>Documentations are WIP</p>
</header>
<footer>
<div
style={{ textAlign: "center", fontSize: "0.8em", marginTop: "2em" }}
>
<a
className="App-link"
href="https://vitejs.dev/guide/features.html"
target="_blank"
rel="noopener noreferrer"
>
Vite Docs
</a>
{" | "}
<a
className="App-link"
href="https://docs.metamask.io/guide/snaps.html"
target="_blank"
rel="noopener noreferrer"
>
Snap Docs
</a>
</div>
</footer>
</>
)
}