Skip to content

Commit

Permalink
Index: getChannels
Browse files Browse the repository at this point in the history
-> save response channel in channels map
  • Loading branch information
sophia1ch committed Dec 19, 2023
1 parent b3ed963 commit 2073ead
Show file tree
Hide file tree
Showing 5 changed files with 125 additions and 97 deletions.
87 changes: 74 additions & 13 deletions packages/neuron-ui/src/components/Perun/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ import PageContainer from 'components/PageContainer'
import { Form, Container, Button, Modal } from 'react-bootstrap'
import { BiPlus, BiX } from 'react-icons/bi'
import {
ChannelState,
SerializeOffChainParticipant,
SerializeSEC1EncodedPubKey,
} from '@polycrypt/perun-wallet-wrapper/ckb/serialization'
import { channelIdToString, channelIdFromString } from '@polycrypt/perun-wallet-wrapper/translator'
import * as wire from '@polycrypt/perun-wallet-wrapper/wire'

import { ChannelState } from './types'
import styles from './perun.module.scss'
import { ControllerResponse } from 'services/remote/remoteApiWrapper'
import {
Expand All @@ -33,6 +33,7 @@ import { addressToScript, bytesToHex, scriptToAddress } from '@nervosnetwork/ckb
import { ErrorCode, errorFormatter, isSuccessResponse } from 'utils'
import { showErrorMessage } from 'services/remote'
import { PasswordDialog } from 'components/SignAndVerify'
import { State } from '@polycrypt/perun-wallet-wrapper/wire'

const Perun = () => {
const { wallet } = useGlobalState()
Expand All @@ -42,12 +43,12 @@ const Perun = () => {
const [peerAddress, setPeerAddress] = useState('')
const [challengeDuration, setChallengeDuration] = useState<number>()
const [validInputs, setValidInputs] = useState(false)
const [channels] = useState(new Map<string, ChannelState>())
const [channels] = useState(new Map<string, State>())
const [showRejectionModal, setShowRejectionModal] = useState(false)
const [rejectionReason, setRejectionReason] = useState('')
const [updateChannelDialog, setUpdateChannelDialog] = useState(false)
const [channelID, setChannelID] = useState<Uint8Array>()
const [showState, setShowState] = useState<ChannelState>()
const [showState, setShowState] = useState<State>()
const [showInfo, setShowInfo] = useState(false)
const [perunState, setPerunState] = useState<Subject.PerunState>({ type: 'SignMessage' })

Expand Down Expand Up @@ -88,7 +89,7 @@ const Perun = () => {
}

const handleRejected = (reason: React.SetStateAction<string>) => {
console.log("HANDLE REJECTED REASON: ", reason)
console.log('HANDLE REJECTED REASON: ', reason)
setRejectionReason(reason)
setShowRejectionModal(true)
}
Expand Down Expand Up @@ -334,11 +335,21 @@ const Perun = () => {
const appData = new Uint8Array()
const isFinal = false
console.log('channelId', channelId)
channels.set(channelId, new ChannelState(channelIdFromString(channelId), version, appId, alloc, appData, isFinal))
channels.set(
channelId,
State.create({
id: channelIdFromString(channelId),
version: version,
app: appId,
allocation: alloc,
data: appData,
isFinal: isFinal,
})
)
}

const handleUpdateChannel = async (channelId: Uint8Array, amount: bigint) => {
console.log("HANDLE UPDATE CHANNEL")
console.log('HANDLE UPDATE CHANNEL')
const res = await perunServiceAction({
type: 'update',
payload: {
Expand All @@ -347,7 +358,7 @@ const Perun = () => {
amount: amount,
},
})
console.log("HANDLE UPDATE CHANNEL RES: ", res)
console.log('HANDLE UPDATE CHANNEL RES: ', res)
if (!isSuccessResponse(res)) {
handleRejected(res.message as string)
return
Expand Down Expand Up @@ -380,6 +391,50 @@ const Perun = () => {
channels.delete(channelIdToString(res.result.channelId))
}

const getChannels = async () => {
console.log("Getting channels")
const myAddress = wallet.addresses[0].address
const res = await getCurrentWalletAccountExtendedPubKey({ type: 0, index: 0 })
if (!isSuccessResponse(res)) {
handleRejected((res.message as any).content)
return
}
const myPubKey = res.result
const actionRes = await perunServiceAction({
type: 'get',
payload: {
requester: meAsParticipant(myAddress, myPubKey),
},
})
if (!isSuccessResponse(actionRes)) {
return
}
const channelBytes = actionRes.result.channels as Uint8Array
if (channelBytes == new Uint8Array()) {
console.log("empty result")
return
}
console.log("Channel bytes received: ", channelBytes)
const channelView = new DataView(channelBytes.buffer)
const channelState = new ChannelState({ reader: { view: channelView } })
const state = State.create({
id: new Uint8Array(channelState.getChannelId().raw()),
version: new Number(channelState.getVersion().raw()) as number,
app: new Uint8Array(),
allocation: wire.Allocation.create({
assets: undefined,
balances: undefined,
locked: undefined,
}),
data: undefined,
isFinal: Boolean(channelState.getIsFinal().value()) as boolean
})

channels.set(channelIdToString(state.id), state)
}
const intervalId = setInterval(getChannels, 5000);
console.log("IntervalID", intervalId)

const rejectPerunRequest = async (type: 'SignMessage' | 'SignTransaction' | 'UpdateNotification', reason: string) => {
await respondPerunRequest({
type,
Expand Down Expand Up @@ -559,8 +614,10 @@ const Perun = () => {
className={`${styles['info-button']}`}
variant="light"
size="sm"
onClick={() => {console.log("Before setShowState: ", channels.get(channelIdToString(channel[1].id)));
setShowState(channels.get(channelIdToString(channel[1].id)))}}
onClick={() => {
console.log('Before setShowState: ', channels.get(channelIdToString(channel[1].id)))
setShowState(channels.get(channelIdToString(channel[1].id)))
}}
>
<BiPlus />
</Button>
Expand All @@ -570,7 +627,7 @@ const Perun = () => {
className={`${styles['channel-button']} ${styles['channel-update-button']}`}
type="button"
onClick={() => {
console.log("Before setChannelID: ", channel[1].id);
console.log('Before setChannelID: ', channel[1].id)
setChannelID(channel[1].id)
setUpdateChannelDialog(true)
}}
Expand Down Expand Up @@ -630,7 +687,7 @@ const Perun = () => {
className={styles.updateButton}
onClick={() => {
setUpdateChannelDialog(false)
console.log("Before handleUpdateChannel: ", channelID, updateAmount)
console.log('Before handleUpdateChannel: ', channelID, updateAmount)
handleUpdateChannel(channelID, BigInt(updateAmount! * 1e8))
setChannelID(undefined)
}}
Expand All @@ -653,8 +710,12 @@ const Perun = () => {
<BiX />
</Button>
<p>{t(`perun.state`)}:</p>
<p>{() => {console.log(showState);
return JSON.stringify(showState)}}</p>
<p>
{() => {
console.log(showState)
return JSON.stringify(showState)
}}
</p>
</div>
)}
</div>
Expand Down
62 changes: 0 additions & 62 deletions packages/neuron-ui/src/components/Perun/types.ts

This file was deleted.

7 changes: 5 additions & 2 deletions packages/neuron-ui/src/types/Controller/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,12 @@ declare namespace Controller {
interface CloseChannelParams {
channelId: Uint8Array
}
interface GetChannelParams {
requester: Uint8Array
}
interface PerunServiceActionParams {
type: 'open' | 'update' | 'close'
payload: OpenChannelParams | UpdateChannelParams | CloseChannelParams
type: 'open' | 'update' | 'close' | 'get'
payload: OpenChannelParams | UpdateChannelParams | CloseChannelParams | GetChannelParams
}
interface RespondPerunRequestParams {
type: 'SignMessage' | 'SignTransaction' | 'UpdateNotification'
Expand Down
59 changes: 41 additions & 18 deletions packages/neuron-wallet/src/controllers/perun/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ export default class PerunController {
return PerunController.instance
}


public async start() {
return PerunService.getInstance().start()
}
Expand Down Expand Up @@ -62,18 +61,20 @@ export default class PerunController {
return this.updateChannel(params.payload as Controller.Params.UpdateChannelParams)
case 'close':
return this.closeChannel(params.payload as Controller.Params.CloseChannelParams)
case 'get':
return this.getChannels(params.payload as Controller.Params.GetChannelsParams)
default:
return Promise.reject(new Error('Invalid perun service action type'))
}
}

// Create a new client for each call, in case the connection break for some reason.
private static mkClient(): SimpleChannelServiceClient {
const rpcEndpoint = 'http://localhost:42025'
return mkSimpleChannelServiceClient(defaultAddressEncoder, rpcEndpoint)
}

async openChannel(params: Controller.Params.OpenChannelParams): Promise<Controller.Response> {

const alloc = Allocation.create({
assets: [new Uint8Array(32)],
balances: Balances.create({
Expand All @@ -84,14 +85,16 @@ export default class PerunController {
],
}),
})
const res = await PerunController.serviceClient.openChannel(params.me, params.peer, alloc, params.challengeDuration).catch(e => {
return {
rejected: {
reason: e.message,
},
channelId: undefined,
}
})
const res = await PerunController.serviceClient
.openChannel(params.me, params.peer, alloc, params.challengeDuration)
.catch(e => {
return {
rejected: {
reason: e.message,
},
channelId: undefined,
}
})
if (res.rejected) {
return {
status: ResponseCode.Fail,
Expand All @@ -111,14 +114,16 @@ export default class PerunController {
}

async updateChannel(params: Controller.Params.UpdateChannelParams): Promise<Controller.Response> {
const res = await PerunController.serviceClient.updateChannel(channelIdFromString(params.channelId), params.index, params.amount).catch(e => {
return {
rejected: {
reason: e.message,
},
update: undefined,
}
})
const res = await PerunController.serviceClient
.updateChannel(channelIdFromString(params.channelId), params.index, params.amount)
.catch(e => {
return {
rejected: {
reason: e.message,
},
update: undefined,
}
})

if (res.rejected) {
return {
Expand Down Expand Up @@ -154,4 +159,22 @@ export default class PerunController {
},
}
}

async getChannels(params: Controller.Params.GetChannelsParams): Promise<Controller.Response> {
const res = await PerunController.serviceClient.getChannels(params.requester)

if (res.rejected) {
return {
status: ResponseCode.Fail,
message: res.rejected.reason,
}
}

return {
status: ResponseCode.Success,
result: {
channels: res.channels,
},
}
}
}
7 changes: 5 additions & 2 deletions packages/neuron-wallet/src/types/controller.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,12 @@ declare namespace Controller {
interface CloseChannelParams {
channelId: Uint8Array
}
interface GetChannelsParams {
requester: Uint8Array
}
interface PerunServiceActionParams {
type: 'open' | 'update' | 'close'
payload: OpenChannelParams | UpdateChannelParams | CloseChannelParams
type: 'open' | 'update' | 'close' | 'get'
payload: OpenChannelParams | UpdateChannelParams | CloseChannelParams | GetChannelParams
}

interface RespondPerunRequestParams {
Expand Down

0 comments on commit 2073ead

Please sign in to comment.