Skip to content

Commit 608e6cd

Browse files
committed
wip: update
1 parent 2a5830b commit 608e6cd

File tree

16 files changed

+279
-110
lines changed

16 files changed

+279
-110
lines changed

packages/neuron-ui/src/components/PaymentChannel/api.ts

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,6 @@ export type ChannelState = {
1919
// // state?: wire.State;
2020
// myPayloadIndex: 0 | 1;
2121
// }
22-
export async function startupChannelServiceRunner(publicKey: string) {
23-
const actionRes = await perunServiceAction({
24-
type: 'startup',
25-
payload: {
26-
network: "testnet",
27-
publicKey,
28-
},
29-
})
30-
if (!isSuccessResponse(actionRes)) {
31-
return []
32-
}
33-
}
3422
export async function getChannels(publicKey: string, address: string) {
3523
const actionRes = await perunServiceAction({
3624
type: 'get',

packages/neuron-ui/src/components/PaymentChannel/components/ChannelCard/index.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ export default function ChannelCard(props: ChannelCardProps) {
9999
</div>
100100
{dialogType === DialogType.send && (
101101
<PerunSendPayment
102+
maxAmount={channelState.state.allocation?.balances?.balances[0].balance[channelState.actorIdx] ?? "0"}
102103
onConfirm={async (swapAmount) => {
103104
updateChannel(channelState.id, 0, BigInt(swapAmount! * 1e8))
104105
// close

packages/neuron-ui/src/components/PaymentChannel/components/Console/index.tsx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,8 @@ export default function PerunConsole(props: PerunConsoleProps) {
5656
} = useGlobalState()
5757
const [t] = useTranslation()
5858
const [dialogType, setDialogType] = useState<DialogType | undefined>(undefined)
59-
const channelInfoMap = useChannelInfoMap()
60-
59+
const channelInfoMap = useChannelInfoMap(myAddress)
60+
6161
// const [pendingChannels, setPendingChannels] = useState<ChannelInfo[]>([])
6262
// const [channelMap, setChannelMap] = useState<Record<string, ChannelInfo>>({})
6363
const { data: channelStates = [], run: syncChannels } = useRequest(async () => {
@@ -73,7 +73,7 @@ export default function PerunConsole(props: PerunConsoleProps) {
7373

7474

7575
useEffect(() => {
76-
restoreChannels()
76+
syncChannels()
7777
}, [])
7878

7979
// const assets = ['CKB']
@@ -222,7 +222,7 @@ export default function PerunConsole(props: PerunConsoleProps) {
222222
channelInfoMap={channelInfoMap}
223223
onOpenChannel={(request) => {
224224
// todo convert request.initBals to payload
225-
const payload: PerunAPI.OpenChannelParams['balances'] = [{ type: null, balances: ["1", "2"]}]
225+
const payload: PerunAPI.OpenChannelParams['balances'] = [{ type: null, balances: ["1", "2"] }]
226226
const channelInfo: ChannelInfo = {
227227
channelId: UNMATCH_CHANNEL_ID,
228228
me: {
@@ -237,7 +237,7 @@ export default function PerunConsole(props: PerunConsoleProps) {
237237
}}
238238
onUpdateChannel={(request) => {
239239
const channelId = request.state?.id as string
240-
if(channelId && !channelInfoMap.has(channelId) && channelInfoMap.has(UNMATCH_CHANNEL_ID)) {
240+
if (channelId && !channelInfoMap.has(channelId) && channelInfoMap.has(UNMATCH_CHANNEL_ID)) {
241241
const temChannelInfo = channelInfoMap.get(UNMATCH_CHANNEL_ID)
242242
const channelInfo = {
243243
...temChannelInfo,

packages/neuron-ui/src/components/PaymentChannel/hooks.ts

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,58 @@
1-
import { useState } from "react";
1+
import { useEffect, useState } from "react";
2+
import { perunServiceAction } from "services/remote";
3+
import { isSuccessResponse } from "utils";
24

35

46
export const UNMATCH_CHANNEL_ID = 'UNMATCH_CHANNEL_ID';
57

6-
export type ChannelInfo = {
7-
channelId: string;
8-
me: PerunAPI.PeerUser;
9-
peer: PerunAPI.PeerUser;
10-
payload: PerunAPI.OpenChannelParams['balances'],
11-
myPayloadIndex: 0 | 1;
12-
}
8+
export type ChannelInfo = Perun.ChannelInfo
139

14-
export function useChannelInfoMap() {
10+
export function useChannelInfoMap(address: string) {
1511
const [map, setMap] = useState<Record<string, ChannelInfo>>({})
1612
/** will update the channel info */
17-
const add = (channelId: string, info: ChannelInfo) => setMap(map => ({ ...map, [channelId]: info }))
13+
const add = (channelId: string, info: ChannelInfo) => {
14+
if (channelId !== UNMATCH_CHANNEL_ID) {
15+
perunServiceAction({
16+
type: "add-channel-info",
17+
payload: info,
18+
})
19+
}
20+
setMap(map => ({ ...map, [channelId]: info }))
21+
}
1822
const has = (channelId: string) => !!map[channelId];
19-
const iDelete = (channelId: string) => setMap(map => {
20-
const { [channelId]: _, ...rest } = map
21-
return rest
22-
})
23+
const iDelete = (channelId: string) => {
24+
setMap(map => {
25+
const { [channelId]: _, ...rest } = map
26+
return rest
27+
})
28+
perunServiceAction({
29+
type: "remove-channel-info",
30+
payload: {
31+
channelId,
32+
},
33+
})
34+
}
2335
const get = (channelId: string) => map[channelId] as ChannelInfo | undefined
2436

37+
useEffect(() => {
38+
perunServiceAction({
39+
type: "get-channel-infos",
40+
payload: {
41+
address,
42+
},
43+
}).then(res => {
44+
if (!isSuccessResponse(res)) {
45+
return
46+
}
47+
const list: ChannelInfo[] = res.result;
48+
const map = list.reduce((acc, cur) => {
49+
acc[cur.channelId] = cur
50+
return acc
51+
}, {} as Record<string, ChannelInfo>)
52+
setMap(map)
53+
})
54+
}, [])
55+
2556
return {
2657
add,
2758
has,

packages/neuron-ui/src/components/PaymentChannel/index.tsx

Lines changed: 3 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,18 @@
1-
import React, { useState, useEffect, useCallback } from 'react'
1+
import React, { useState, useEffect } from 'react'
22

33
import { useState as useGlobalState } from 'states'
4-
import { bytes } from '@ckb-lumos/codec'
5-
import { blockchain } from '@ckb-lumos/base'
6-
import Dialog from 'widgets/Dialog'
7-
import Table, { TableProps } from 'widgets/Table'
84
import PageContainer from 'components/PageContainer'
95
import {
106
PerunIcon,
11-
AddSimple,
12-
DetailIcon,
13-
CkbIcon,
14-
InfoCircleOutlined,
15-
DepositTimeSort,
16-
PerunSend,
17-
PerunClose,
18-
LineDownArrow,
197
} from 'widgets/Icons/icon'
20-
import TableNoData from 'widgets/Icons/TableNoData.png'
21-
import { type CKBComponents } from '@ckb-lumos/lumos/rpc'
22-
import {
23-
SerializeOffChainParticipant,
24-
SerializeSEC1EncodedPubKey,
25-
} from 'utils/perun-wallet-wrapper/ckb/serialization'
26-
import { channelIdToString, channelIdFromString } from 'utils/perun-wallet-wrapper/translator'
27-
import * as wire from 'utils/perun-wallet-wrapper/wire'
288

29-
import { ControllerResponse } from 'services/remote/remoteApiWrapper'
309
import {
31-
OfflineSignStatus,
32-
OfflineSignType,
33-
getCurrentWalletAccountExtendedPubKey,
3410
perunServiceAction,
35-
respondPerunRequest,
36-
signRawMessage,
37-
signTransactionOnly,
3811
showErrorMessage,
3912
} from 'services/remote'
4013
import {
41-
addressToScript,
42-
scriptToAddress,
43-
bytesToHex,
44-
ErrorCode,
45-
errorFormatter,
46-
isSuccessResponse,
47-
clsx,
48-
getParticipantByAddressAndPubkey,
4914
isMainnet,
5015
} from 'utils'
51-
import { PasswordDialog } from 'components/SignAndVerify'
5216

5317
import styles from './perun.module.scss'
5418

@@ -57,6 +21,7 @@ import Button from 'widgets/Button'
5721
import PerunConsole from './components/Console'
5822
import AddressSelector from './components/AddressSelector'
5923
import { useRequest } from 'ahooks'
24+
import { restoreChannels } from './api'
6025

6126

6227

@@ -84,6 +49,7 @@ const PaymentChannel = () => {
8449
useEffect(() => {
8550
if(!enable && runnerState.running) {
8651
setEnable(true)
52+
restoreChannels();
8753
}
8854
if (enable && !runnerState.running) {
8955
setEnable(false)

packages/neuron-ui/src/components/PerunCreationRequestList/index.tsx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ export const PerunCreationRequestList = (props: PerunRequestListProps) => {
8181
return (
8282
<>
8383
<h3 className='my-0'>Open Channel Request from {address.slice(0, 10)}...{address.slice(-10)}</h3>
84-
<p>{`Channel ID: ${request.proposalId}`}</p>
8584
<div className='flex flex-row gap-4 mt-2'>
8685
<div>
8786
<div className='text-secondary'>My Token Locked</div>

packages/neuron-ui/src/components/PerunSendPayment/index.tsx

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,26 @@ import { openExternal, MultisigConfig } from 'services/remote'
77
import { localNumberFormatter, shannonToCKBFormatter } from 'utils'
88
import Dialog from 'widgets/Dialog'
99
import styles from './perunSendPayment.module.scss'
10+
import Big from 'big.js'
1011

1112

1213
const NERVOS_DAO_RFC_URL =
1314
'https://www.github.com/nervosnetwork/rfcs/blob/master/rfcs/0023-dao-deposit-withdraw/0023-dao-deposit-withdraw.md'
1415

15-
const PerunSendPayment = ({ onClose, onConfirm }: { onClose: () => void, onConfirm: (swapAmount: number) => void }) => {
16+
type PerunSendPaymentProps = {
17+
onClose: () => void
18+
onConfirm: (amount: number) => void
19+
// bigint string
20+
maxAmount: string
21+
}
22+
const PerunSendPayment = (props: PerunSendPaymentProps) => {
23+
const { onClose, onConfirm, maxAmount } = props
1624
const [t, { language }] = useTranslation()
1725
const [errorMessage, setErrorMessage] = useState('')
1826
const [updateAmount, setUpdateAmount] = useState<number>(0)
1927

2028
const handleUpdateAmountChange = (am: string) => {
29+
setErrorMessage('')
2130
const amountNum = parseFloat(am)
2231
if (Number.isNaN(amountNum)) {
2332
return
@@ -40,6 +49,12 @@ const PerunSendPayment = ({ onClose, onConfirm }: { onClose: () => void, onConfi
4049
show
4150
title={t('perun.send-payment')} onCancel={onClose} className={styles.container}
4251
onConfirm={() => {
52+
53+
const maxAmountVal = new Big(maxAmount).div(10 ** 8)
54+
if (updateAmount > maxAmountVal.toNumber()) {
55+
setErrorMessage(t('perun.message.max-amount', { amount: `${maxAmountVal} CKB` }))
56+
return
57+
}
4358
onConfirm(updateAmount);
4459
}}
4560
>

packages/neuron-ui/src/locales/en.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -882,7 +882,10 @@
882882
"rejection-reason": "Rejection reason",
883883
"ok": "Okay",
884884
"enter-amount": "Please enter the amount you want to swap",
885-
"state": "State"
885+
"state": "State",
886+
"message": {
887+
"max-amount": "Amount cannot exceed {{amount}}"
888+
}
886889
},
887890
"lock-info-dialog": {
888891
"address-info": "Address Information",

packages/neuron-wallet/src/controllers/perun.ts

Lines changed: 51 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ import { parseState } from '../services/perun/tools/tool'
2020
import * as wire from "../utils/perun-wallet-wrapper/wire"
2121
// import PerunChannelServiceRunner from '../services/perun/channel-service-runner'
2222
import { PerunMessageReceiver } from '../services/perun/message-receiver'
23+
import { getConnection } from '../database/chain/connection'
24+
import PerunChannelInfoEntity from '../database/chain/entities/perun-channel-info'
2325

2426
const defaultAddressEncoder: AddressEncoder = (add: Uint8Array | string) => {
2527
if (typeof add === 'string') {
@@ -120,11 +122,60 @@ export default class PerunController {
120122
return this.getChannels(params.payload)
121123
case 'restore':
122124
return this.restoreChannels(params.payload)
125+
case 'get-channel-infos':
126+
return this.getChannelInfos(params.payload)
127+
case 'remove-channel-info':
128+
return this.removeChannelInfo(params.payload)
129+
case 'add-channel-info':
130+
return this.addChannelInfo(params.payload)
123131
default:
124132
return Promise.reject(new Error('Invalid perun service action type'))
125133
}
126134
}
127135

136+
async getChannelInfos(params: (Perun.ServiceActionParams & { type: "get-channel-infos" })['payload']) {
137+
const res = await getConnection().getRepository(PerunChannelInfoEntity).find({
138+
where: {
139+
meAddress: params.address,
140+
}
141+
})
142+
return {
143+
status: ResponseCode.Success,
144+
result: res.map(item => item.toModel()),
145+
}
146+
}
147+
148+
async removeChannelInfo(params: (Perun.ServiceActionParams & { type: "remove-channel-info" })['payload']) {
149+
await getConnection().getRepository(PerunChannelInfoEntity).delete({
150+
channelId: params.channelId,
151+
})
152+
return {
153+
status: ResponseCode.Success,
154+
result: true,
155+
}
156+
}
157+
158+
async addChannelInfo(params: (Perun.ServiceActionParams & { type: "add-channel-info" })['payload']) {
159+
const channelInfo = params;
160+
// if exist remove it
161+
const db = getConnection().getRepository(PerunChannelInfoEntity)
162+
const flag = await db.exist({
163+
where: {
164+
channelId: channelInfo.channelId,
165+
}
166+
})
167+
if (flag) {
168+
await db.delete({
169+
channelId: channelInfo.channelId,
170+
})
171+
}
172+
await db.insert(PerunChannelInfoEntity.fromObject(channelInfo))
173+
return {
174+
status: ResponseCode.Success,
175+
result: true,
176+
}
177+
}
178+
128179
// async getRunnerContext(): Promise<Controller.Response> {
129180
// return {
130181
// status: ResponseCode.Success,
@@ -160,11 +211,6 @@ export default class PerunController {
160211
message: message,
161212
}
162213
PerunRunnerStateSubject.next(this.runnerStatus)
163-
// if (!this.context) {
164-
// throw new Error('PerunController: Perun Not Started')
165-
// }
166-
// this.runnerStatus = { running: false }
167-
// logger.info('PerunController: stop-----PerunService-----')
168214
// todo
169215
// stop channel-service-runner
170216
// stop wallet-backend

0 commit comments

Comments
 (0)