Skip to content

Commit 1dfa6d6

Browse files
committed
wip: update
1 parent e856374 commit 1dfa6d6

File tree

7 files changed

+91
-32
lines changed

7 files changed

+91
-32
lines changed

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

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ export async function getChannels(publicKey: string, address: string) {
4545
payload: {
4646
requester: getParticipantByAddressAndPubkey(address, publicKey),
4747
},
48-
}) as ControllerResponse<{ channels: { actorIdxs: (0|1)[], states: any[] } }>
48+
}) as ControllerResponse<{ channels: { actorIdxs: (0 | 1)[], states: any[] } }>
4949
if (!isSuccessResponse(actionRes)) {
5050
return []
5151
}
@@ -95,20 +95,35 @@ export async function getChannels(publicKey: string, address: string) {
9595
return channels;
9696
}
9797

98-
export async function openChannel(publicKey: string, address: string, peerUser: PeerUser, payload: [TradePayload, TradePayload], challengeDuration: number) {
98+
export async function openChannel(publicKey: string, address: string, peerUser: PerunAPI.PeerUser, payload: [TradePayload, TradePayload], challengeDuration: number) {
9999
// open channel request will return after both peer user signed transaction
100100
return perunServiceAction({
101101
type: 'open',
102+
// payload: {
103+
// me: getParticipantByAddressAndPubkey(address, publicKey),
104+
// peer: getParticipantByAddressAndPubkey(peerUser.address, peerUser.publicKey),
105+
// // todo move TradePayload process to main progress
106+
// balances: [
107+
// bytes.bytify(equalNumPaddedHex(BigInt(payload[0].amount * 1e8))),
108+
// bytes.bytify(equalNumPaddedHex(BigInt(payload[1].amount * 1e8))),
109+
// ],
110+
// challengeDuration: Number(challengeDuration),
111+
// },
102112
payload: {
103-
me: getParticipantByAddressAndPubkey(address, publicKey),
104-
peer: getParticipantByAddressAndPubkey(peerUser.address, peerUser.publicKey),
105-
// todo move TradePayload process to main progress
113+
me: { publicKey, address },
114+
peer: peerUser,
106115
balances: [
107-
bytes.bytify(equalNumPaddedHex(BigInt(payload[0].amount * 1e8))),
108-
bytes.bytify(equalNumPaddedHex(BigInt(payload[1].amount * 1e8))),
116+
{
117+
type: null,
118+
balances: [
119+
BigInt(payload[0].amount * 1e8).toString(),
120+
BigInt(payload[1].amount * 1e8).toString(),
121+
]
122+
},
123+
// { type: null, balances: [1, 2] }, // udt
109124
],
110125
challengeDuration: Number(challengeDuration),
111-
},
126+
}
112127
})
113128
}
114129

packages/neuron-ui/src/types/Controller/index.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ declare namespace Controller {
219219
type PerunServiceActionParams =
220220
| { type: "startup", payload: PerunChannelServiceRunnerStartupsParams }
221221
| { type: "shutdown" }
222-
| { type: "open", payload: OpenChannelParams }
222+
| { type: "open", payload: PerunAPI.OpenChannelParams }
223223
| { type: "update", payload: UpdateChannelParams }
224224
| { type: "close", payload: CloseChannelParams }
225225
| { type: "get", payload: GetChannelParams }

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

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,20 @@ import { bytes } from '@ckb-lumos/codec'
1515
import { Allocation, Balances } from '../utils/perun-wallet-wrapper/wire'
1616
// import PerunPersistorService from '../services/perun/persistor'
1717
// import PerunChannelEntity from '../database/chain/entities/perun-channel'
18-
import { mol } from "@ckb-ccc/core"
18+
import { ccc, mol } from "@ckb-ccc/core"
19+
import participant from 'src/services/perun/tools/participant'
1920

2021
const defaultAddressEncoder: AddressEncoder = (add: Uint8Array | string) => {
2122
if (typeof add === 'string') {
2223
return bytes.bytify(add)
2324
}
2425
return add
2526
}
27+
const equalNumPaddedHex = (num: bigint) => {
28+
const hex = num.toString(16)
29+
const res = hex.length % 2 === 0 ? hex : `0${hex}`
30+
return `0x${res}`
31+
}
2632

2733
export default class PerunController {
2834
static emiter = new EventEmitter()
@@ -137,21 +143,34 @@ export default class PerunController {
137143
} as Controller.Response
138144
}
139145

140-
async openChannel(params: Controller.Params.OpenChannelParams): Promise<Controller.Response> {
146+
async openChannel(params: PerunAPI.OpenChannelParams): Promise<Controller.Response> {
141147
logger.info('PerunController: openChannel----------')
148+
const { me, peer, balances, challengeDuration } = params;
149+
const meRequestId = await participant.encode(me.publicKey, me.address);
150+
const peerRequestId = await participant.encode(peer.publicKey, peer.address);
151+
const { assets, balances: iBalances } = balances.reduce((obj, item) => {
152+
obj.assets.push(item.type ? ccc.Script.from(item.type).toBytes() : new Uint8Array(0))
153+
obj.balances.push(
154+
item.balances.map(balance => bytes.bytify(equalNumPaddedHex(BigInt(balance)))),
155+
)
156+
return obj;
157+
}, { assets: [] as Uint8Array[], balances: [] as Uint8Array[][] })
142158
const alloc = Allocation.create({
143-
assets: [new Uint8Array(1)],
159+
assets: assets,
144160
balances: Balances.create({
145-
balances: [
146-
{
147-
balance: params.balances,
148-
},
149-
],
161+
balances: iBalances.map(balance => ({
162+
balance
163+
}))
164+
// balances: [
165+
// {
166+
// balance: params.balances,
167+
// },
168+
// ],
150169
}),
151170
})
152171

153172
const res = await PerunController.serviceClient
154-
.openChannel(params.me, params.peer, alloc, params.challengeDuration, mol.Uint32.encode(123))
173+
.openChannel(meRequestId, peerRequestId, alloc, challengeDuration, mol.Uint32.encode(123))
155174
.catch(e => {
156175
logger.info('PerunController: openChannel-----error-----', e)
157176
return {
@@ -169,8 +188,8 @@ export default class PerunController {
169188
}
170189
}
171190
const channelId = channelIdToString(new Uint8Array(res.channelId!))
172-
logger.log('Controler Buffer channelId', res.channelId!)
173-
logger.log('Controler channelID', channelId)
191+
// logger.log('Controler Buffer channelId', res.channelId!)
192+
// logger.log('Controler channelID', channelId)
174193
return {
175194
status: ResponseCode.Success,
176195
result: {

packages/neuron-wallet/src/services/perun/fetchCell.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,10 @@ const networkMap = {
99
} as const
1010

1111
const testnetService = new ccc.ClientPublicTestnet({ url: networkMap.testnet })
12+
const mainnetService = new ccc.ClientPublicMainnet({ url: networkMap.mainnet })
1213

13-
export async function fetchTargetCell(txhash: string, outputIndex: number) {
14-
const txResponse = await testnetService.getTransaction(txhash);
14+
export async function fetchTargetCell(network: "testnet" | "mainnet", txhash: string, outputIndex: number) {
15+
const txResponse = await (network === "testnet" ? testnetService : mainnetService).getTransaction(txhash);
1516
const tx = txResponse?.transaction;
1617
if (!tx) {
1718
return null;

packages/neuron-wallet/src/services/perun/tools/parser.sign-transaction.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,22 @@ import Transaction from '../../../models/chain/transaction'
77
// import RpcService from '../../../services/rpc-service'
88
import NetworksService from '../../networks'
99
import { fetchTargetCell } from '../fetchCell'
10-
import { ccc, ClientPublicTestnet, ScriptLike } from '@ckb-ccc/core'
11-
import { NetworkType } from '../../../models/network'
10+
import { ccc, ClientPublicMainnet, ClientPublicTestnet, ScriptLike } from '@ckb-ccc/core'
11+
// import { NetworkType } from '../../../models/network'
12+
import { LIGHT_CLIENT_TESTNET } from '../../../utils/const'
1213

1314
export async function parseSignTransactionRequest(serializedRequest: Perun.SerializedMessage.SignTransactionRequest) {
1415

1516
const network = NetworksService.getInstance().getCurrent()
16-
const isLightClient = network.type === NetworkType.Light
17+
// const isLightClient = network.type === NetworkType.Light
18+
const isTestnet = network.chain === LIGHT_CLIENT_TESTNET
1719
// const rpcService = new RpcService(network.remote, network.type)
1820
console.log("network:", network);
1921

2022
const scriptStr = new TextDecoder("utf-8").decode(Buffer.from(serializedRequest.identifier.data))
2123
const sdkScript = JSON.parse(scriptStr, snakeCaseToCamelCase) as ScriptLike;
2224
// todo
23-
const address = ccc.Address.fromScript(sdkScript, new ClientPublicTestnet()).toString();
25+
const address = ccc.Address.fromScript(sdkScript, isTestnet ? new ClientPublicTestnet() : new ClientPublicMainnet()).toString();
2426

2527
const txStr = new TextDecoder("utf-8").decode(Buffer.from(serializedRequest.transaction.data));
2628
// TODO: The transaction here has unresolved inputs, which are only referenced by their outpoints.
@@ -32,7 +34,7 @@ export async function parseSignTransactionRequest(serializedRequest: Perun.Seria
3234
// logger.info('PerunServiceRunner received signTransactionRequest:sdkTx', sdkTx)
3335
// Fetch live cells from txs input-outpoints.
3436
let resolvedInputs = []
35-
37+
3638
for (const [idx, input] of sdkTx.txView.inputs.entries()) {
3739
let typedInput = input as { previousOutput: { txHash: string; index: string }; since: string }
3840
// logger.info('Fetching live cell', input.previousOutput)
@@ -60,8 +62,8 @@ export async function parseSignTransactionRequest(serializedRequest: Perun.Seria
6062
// : await rpcService.getTransaction(input.previousOutput.txHash)
6163
// const targetCell = rpcTx?.transaction?.outputs[Number(input.previousOutput.index)]
6264
// logger.info('RPC-TX:', rpcTx)
63-
// todo testnet only for now
64-
const targetCell = await fetchTargetCell(input.previousOutput.txHash, input.previousOutput.index);
65+
// todo Full Node Use RPC Service
66+
const targetCell = await fetchTargetCell(isTestnet ? "testnet" : "mainnet", input.previousOutput.txHash, input.previousOutput.index);
6567
// console.log("iCell", targetCell);
6668

6769
if (targetCell) {

packages/neuron-wallet/src/types/controller.d.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,10 +77,16 @@ declare namespace Controller {
7777
message: string
7878
}
7979
interface OpenChannelParams {
80-
me: Uint8Array
81-
peer: Uint8Array
82-
balances: [Uint8Array, Uint8Array]
80+
// me: Uint8Array
81+
// peer: Uint8Array
82+
// balances: [Uint8Array, Uint8Array]
8383
challengeDuration: number
84+
me: { publicKey: string, address: string },
85+
peer: { publicKey: string, address: string },
86+
balances: Array<{
87+
type: null | { codeHash: string, hashType: string, args: string }
88+
balances: [string, string]
89+
}>
8490
}
8591
interface UpdateChannelParams {
8692
channelId: string

types/perun.d.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,4 +252,20 @@ declare namespace Perun {
252252

253253
}
254254

255+
}
256+
257+
258+
declare namespace PerunAPI {
259+
type PeerUser = Perun.ReadableMessage.PeerUser;
260+
type Script = { codeHash: string, hashType: string, args: string }
261+
262+
type OpenChannelParams = {
263+
me: PeerUser,
264+
peer: PeerUser,
265+
balances: Array<{
266+
type: null | Script
267+
balances: [string, string]
268+
}>
269+
challengeDuration: number
270+
}
255271
}

0 commit comments

Comments
 (0)