-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #24 from perun-network/add-ckb-example
Add CKB Payment Channel Example
- Loading branch information
Showing
91 changed files
with
17,907 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
# Binaries for programs and plugins | ||
*.exe | ||
*.exe~ | ||
*.dll | ||
*.so | ||
*.dylib | ||
|
||
# Test binary, built with `go test -c` | ||
*.test | ||
|
||
# Output of the go coverage tool, specifically when used with LiteIDE | ||
*.out | ||
|
||
# log files | ||
*.log | ||
|
||
perun-ckb-demo | ||
|
||
# Dependency directories (remove the comment below to include it) | ||
# vendor/ | ||
devnet/accounts | ||
devnet/data | ||
devnet/specs | ||
devnet/ckb-miner.toml | ||
devnet/ckb.toml | ||
devnet/default.db-options | ||
devnet/system_scripts | ||
.vscode/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
[submodule "devnet/contracts"] | ||
path = devnet/contracts | ||
url = [email protected]:perun-network/perun-ckb-contract |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
// Copyright 2024 PolyCrypt GmbH | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package client | ||
|
||
import ( | ||
"context" | ||
"encoding/binary" | ||
"fmt" | ||
"log" | ||
"math" | ||
"math/big" | ||
"strconv" | ||
"time" | ||
|
||
"github.com/nervosnetwork/ckb-sdk-go/v2/indexer" | ||
"github.com/nervosnetwork/ckb-sdk-go/v2/types" | ||
"perun.network/perun-ckb-backend/wallet/address" | ||
) | ||
|
||
type BalanceExtractor func(*indexer.LiveCell) *big.Int | ||
|
||
func ckbBalanceExtractor(cell *indexer.LiveCell) *big.Int { | ||
return new(big.Int).SetUint64(cell.Output.Capacity) | ||
} | ||
|
||
func sudtBalanceExtractor(cell *indexer.LiveCell) *big.Int { | ||
if len(cell.OutputData) != 16 { | ||
return big.NewInt(0) | ||
} | ||
return new(big.Int).SetUint64(binary.LittleEndian.Uint64(cell.OutputData)) | ||
} | ||
|
||
func (p *PaymentClient) PollBalances() { | ||
pollingInterval := time.Second | ||
searchKey := &indexer.SearchKey{ | ||
Script: address.AsParticipant(p.Account.Address()).PaymentScript, | ||
ScriptType: types.ScriptTypeLock, | ||
ScriptSearchMode: types.ScriptSearchModeExact, | ||
Filter: nil, | ||
WithData: true, | ||
} | ||
updateBalance := func() { | ||
ctx, _ := context.WithTimeout(context.Background(), pollingInterval) | ||
|
||
cells, err := p.rpcClient.GetCells(ctx, searchKey, indexer.SearchOrderDesc, math.MaxUint32, "") | ||
if err != nil { | ||
log.Println("balance poll error: ", err) | ||
return | ||
} | ||
ckbBalance := big.NewInt(0) | ||
sudtBalance := big.NewInt(0) | ||
for _, cell := range cells.Objects { | ||
ckbBalance = new(big.Int).Add(ckbBalance, ckbBalanceExtractor(cell)) | ||
sudtBalance = new(big.Int).Add(sudtBalance, sudtBalanceExtractor(cell)) | ||
} | ||
|
||
p.balanceMutex.Lock() | ||
if ckbBalance.Cmp(p.balance) != 0 || sudtBalance.Cmp(p.sudtBalance) != 0 { | ||
// Update ckb balance. | ||
p.balance = ckbBalance | ||
|
||
// Update sudt balance. | ||
p.sudtBalance = sudtBalance | ||
|
||
p.balanceMutex.Unlock() | ||
} else { | ||
p.balanceMutex.Unlock() | ||
} | ||
} | ||
updateBalance() | ||
|
||
} | ||
|
||
func FormatBalance(ckbBal, sudtBal *big.Int) string { | ||
balCKByte, _ := ShannonToCKByte(ckbBal).Float64() | ||
return fmt.Sprintf("[green]%s\t[yellow]%s[white]", | ||
strconv.FormatFloat(balCKByte, 'f', 2, 64)+" CKByte", | ||
fmt.Sprintf("%v", sudtBal.Int64())+" SUDT") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
// Copyright 2024 PolyCrypt GmbH | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package client | ||
|
||
import ( | ||
"context" | ||
"math/big" | ||
|
||
"perun.network/go-perun/channel" | ||
"perun.network/go-perun/client" | ||
) | ||
|
||
type PaymentChannel struct { | ||
ch *client.Channel | ||
assets []channel.Asset | ||
} | ||
|
||
// newPaymentChannel creates a new payment channel. | ||
func newPaymentChannel(ch *client.Channel, assets []channel.Asset) *PaymentChannel { | ||
return &PaymentChannel{ | ||
ch: ch, | ||
assets: assets, | ||
} | ||
} | ||
|
||
func (c PaymentChannel) State() *channel.State { | ||
return c.ch.State().Clone() | ||
} | ||
|
||
func (c PaymentChannel) SendPayment(amounts map[channel.Asset]float64) { | ||
// Transfer the given amount from us to peer. | ||
// Use UpdateBy to update the channel state. | ||
err := c.ch.Update(context.TODO(), func(state *channel.State) { | ||
actor := c.ch.Idx() | ||
peer := 1 - actor | ||
for a, amount := range amounts { | ||
|
||
if amount < 0 { | ||
continue | ||
} | ||
|
||
shannonAmount := CKByteToShannon(big.NewFloat(amount)) | ||
state.Allocation.TransferBalance(actor, peer, a, shannonAmount) | ||
|
||
} | ||
|
||
}) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
} | ||
|
||
// Settle settles the payment channel and withdraws the funds. | ||
func (c PaymentChannel) Settle() { | ||
// Finalize the channel to enable fast settlement. | ||
if !c.ch.State().IsFinal { | ||
err := c.ch.Update(context.TODO(), func(state *channel.State) { | ||
state.IsFinal = true | ||
}) | ||
if err != nil { | ||
panic(err) | ||
} | ||
} | ||
|
||
// Settle concludes the channel and withdraws the funds. | ||
err := c.ch.Settle(context.TODO()) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
// Close frees up channel resources. | ||
c.ch.Close() | ||
} |
Oops, something went wrong.