Files
ark/pkg/client-sdk/example/covenantless/alice_to_bob.go
Dusan Sekulic b1c9261f14 [SDK] Persist tx history, vtxos & Provide transaction feed (#354)
* SDK - GetTransactionsStream add to rest/grpc

no session, pattern or user messages provided

* SDK - AppDataRepository added, store refactor

This patch introduces a significant refactor of the Ark SDK codebase. The primary changes involve:

1. **Domain Package Introduction**: A new `domain` package has been created under `store`, encapsulating core data structures and interfaces such as `ConfigData`, `Transaction`, `SdkRepository`, and various repository interfaces. This enhances modularity and separation of concerns.

2. **Replacement of Store with Domain Objects**: All references to the `store` package's `StoreData` have been replaced with `domain.ConfigData`. This change reflects a shift towards using domain-driven design, where the core business logic is represented by domain objects.

3. **Repository Pattern Implementation**: The code has been refactored to use repositories for accessing and managing data. `ConfigRepository` and `TransactionRepository` interfaces are introduced, providing methods for managing configuration data and transactions, respectively.

4. **New Storage Implementations**: New storage implementations using BadgerDB are introduced for persisting transactions (`transaction_repository.go`). This change indicates a move towards more robust and scalable data storage solutions.

5. **Service Layer Introduction**: A service layer (`service.go`) is introduced, which acts as a facade for the underlying data repositories. This layer abstracts the data access logic and provides a unified interface for interacting with configuration and transaction data.

6. **Code Simplification and Cleanup**: The patch removes redundant code and simplifies the existing codebase by consolidating store-related logic and enhancing the overall structure of the code.

7. **Testing Enhancements**: Test cases are updated to reflect the changes in the data access layer, ensuring that the new repository pattern and domain objects are properly tested.

Overall, this refactor aims to improve the maintainability, scalability, and testability of the codebase by adopting best practices such as domain-driven design, repository pattern, and separation of concerns.

* 'SDK listen for tx stream

This diff represents a substantial refactor and enhancement of the `ark-sdk` client, which involves modifications to multiple files, primarily in the `pkg/client-sdk` and `server/internal/core/application` directories. Here's a summary of the key changes:

1. **Configuration and Initialization**:
   - Refactor to replace file-based configuration store with a domain-based approach.
   - Introduced `ListenTransactionStream` configuration to allow real-time transaction event listening.

2. **Client SDK Enhancements**:
   - The client SDK now supports asynchronous transaction streaming and handling.
   - Introduced methods to get transaction event channels and stop the client gracefully.
   - Expanded the `ArkClient` interface to include these new functionalities.

3. **Transaction Handling**:
   - Added support for listening to and processing transaction events in real-time.
   - Implemented methods to handle different types of transactions, including boarding, redeem, and round transactions.
   - Expanded the `Transaction` struct to include more metadata, such as `BoardingVOut`.

4. **Repository Changes**:
   - Introduced `VtxoRepository` for managing VTXO-related operations.
   - Modified `AppDataRepository` to include `VtxoRepository`.

5. **Example and Test Adjustments**:
   - Updated example code to utilize the new transaction streaming capabilities.
   - Adjusted tests to reflect changes in client initialization and configuration handling.

6. **Dependency Updates**:
   - Updated `go.mod` and `go.sum` to include new dependencies such as `badger` for data storage and potentially updated versions of existing packages.

These changes collectively enhance the functionality of the `ark-sdk` client by enabling real-time transaction handling, improving configuration management, and providing a more robust and scalable client architecture. This update seems to be aimed at improving the efficiency and responsiveness of the client application, likely in response to increased demands for real-time data processing and analysis.'

* merge

* go work sync

* test fix

* Tiny refactor (#2)

* tiny refactor

* renaming

* Renamings

* Fixes (#3)

---------

Co-authored-by: Pietralberto Mazza <18440657+altafan@users.noreply.github.com>
2024-10-17 17:36:48 +02:00

285 lines
6.4 KiB
Go

package main
import (
"context"
"fmt"
"io"
"os/exec"
"path"
"strings"
"sync"
"time"
"github.com/ark-network/ark/common"
arksdk "github.com/ark-network/ark/pkg/client-sdk"
"github.com/ark-network/ark/pkg/client-sdk/store"
"github.com/ark-network/ark/pkg/client-sdk/types"
log "github.com/sirupsen/logrus"
)
var (
aspUrl = "localhost:7070"
clientType = arksdk.GrpcClient
password = "password"
walletType = arksdk.SingleKeyWallet
)
func main() {
var (
ctx = context.Background()
err error
aliceArkClient arksdk.ArkClient
bobArkClient arksdk.ArkClient
)
defer func() {
if aliceArkClient != nil {
if err := bobArkClient.Stop(); err != nil {
log.Error(err)
}
}
if bobArkClient != nil {
if err := aliceArkClient.Stop(); err != nil {
log.Error(err)
}
}
}()
log.Info("alice is setting up her ark wallet...")
aliceArkClient, err = setupArkClient("alice")
if err != nil {
log.Fatal(err)
}
logTxEvents("alice", aliceArkClient)
if err := aliceArkClient.Unlock(ctx, password); err != nil {
log.Fatal(err)
}
//nolint:all
defer aliceArkClient.Lock(ctx, password)
log.Info("alice is acquiring onchain funds...")
_, boardingAddress, err := aliceArkClient.Receive(ctx)
if err != nil {
log.Fatal(err)
}
if _, err := runCommand("nigiri", "faucet", boardingAddress); err != nil {
log.Fatal(err)
}
time.Sleep(5 * time.Second)
onboardAmount := uint64(1_0000_0000) // 1 BTC
log.Infof("alice is onboarding with %d sats offchain...", onboardAmount)
aliceBalance, err := aliceArkClient.Balance(ctx, false)
if err != nil {
log.Fatal(err)
}
log.Infof("alice onchain balance: %d", aliceBalance.OnchainBalance.SpendableAmount)
log.Infof("alice offchain balance: %d", aliceBalance.OffchainBalance.Total)
log.Infof("alice claiming onboarding funds...")
txid, err := aliceArkClient.Claim(ctx)
if err != nil {
log.Fatal(err)
}
log.Infof("alice claimed onboarding funds in round %s", txid)
fmt.Println("")
log.Info("bob is setting up his ark wallet...")
bobArkClient, err = setupArkClient("bob")
if err != nil {
log.Fatal(err)
}
logTxEvents("bob", bobArkClient)
if err := bobArkClient.Unlock(ctx, password); err != nil {
log.Fatal(err)
}
//nolint:all
defer bobArkClient.Lock(ctx, password)
bobOffchainAddr, _, err := bobArkClient.Receive(ctx)
if err != nil {
log.Fatal(err)
}
bobBalance, err := bobArkClient.Balance(ctx, false)
if err != nil {
log.Fatal(err)
}
log.Infof("bob onchain balance: %d", bobBalance.OnchainBalance.SpendableAmount)
log.Infof("bob offchain balance: %d", bobBalance.OffchainBalance.Total)
amount := uint64(1000)
receivers := []arksdk.Receiver{
arksdk.NewBitcoinReceiver(bobOffchainAddr, amount),
}
fmt.Println("")
log.Infof("alice is sending %d sats to bob offchain...", amount)
if _, err = aliceArkClient.SendAsync(ctx, false, receivers); err != nil {
log.Fatal(err)
}
log.Info("payment completed out of round")
if err := generateBlock(); err != nil {
log.Fatal(err)
}
time.Sleep(5 * time.Second)
aliceBalance, err = aliceArkClient.Balance(ctx, false)
if err != nil {
log.Fatal(err)
}
fmt.Println("")
log.Infof("alice onchain balance: %d", aliceBalance.OnchainBalance.SpendableAmount)
log.Infof("alice offchain balance: %d", aliceBalance.OffchainBalance.Total)
bobBalance, err = bobArkClient.Balance(ctx, false)
if err != nil {
log.Fatal(err)
}
log.Infof("bob onchain balance: %d", bobBalance.OnchainBalance.SpendableAmount)
log.Infof("bob offchain balance: %d", bobBalance.OffchainBalance.Total)
fmt.Println("")
log.Info("bob is claiming the incoming payment...")
roundTxid, err := bobArkClient.Claim(ctx)
if err != nil {
log.Fatal(err)
}
log.Infof("bob claimed the incoming payment in round %s", roundTxid)
time.Sleep(500 * time.Second)
}
func setupArkClient(wallet string) (arksdk.ArkClient, error) {
dbDir := common.AppDataDir(path.Join("ark-example", wallet), false)
appDataStore, err := store.NewStore(store.Config{
ConfigStoreType: types.FileStore,
AppDataStoreType: types.KVStore,
BaseDir: dbDir,
})
if err != nil {
return nil, fmt.Errorf("failed to setup app data store: %s", err)
}
client, err := arksdk.NewCovenantlessClient(appDataStore)
if err != nil {
return nil, fmt.Errorf("failed to setup ark client: %s", err)
}
if err := client.Init(context.Background(), arksdk.InitArgs{
WalletType: walletType,
ClientType: clientType,
AspUrl: aspUrl,
Password: password,
ListenTransactionStream: true,
}); err != nil {
return nil, fmt.Errorf("failed to initialize wallet: %s", err)
}
return client, nil
}
func runCommand(name string, arg ...string) (string, error) {
errb := new(strings.Builder)
cmd := newCommand(name, arg...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return "", err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return "", err
}
if err := cmd.Start(); err != nil {
return "", err
}
output := new(strings.Builder)
errorb := new(strings.Builder)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
if _, err := io.Copy(output, stdout); err != nil {
fmt.Fprintf(errb, "error reading stdout: %s", err)
}
}()
go func() {
defer wg.Done()
if _, err := io.Copy(errorb, stderr); err != nil {
fmt.Fprintf(errb, "error reading stderr: %s", err)
}
}()
wg.Wait()
if err := cmd.Wait(); err != nil {
if errMsg := errorb.String(); len(errMsg) > 0 {
return "", fmt.Errorf("%s", errMsg)
}
if outMsg := output.String(); len(outMsg) > 0 {
return "", fmt.Errorf("%s", outMsg)
}
return "", err
}
if errMsg := errb.String(); len(errMsg) > 0 {
return "", fmt.Errorf("%s", errMsg)
}
return strings.Trim(output.String(), "\n"), nil
}
func newCommand(name string, arg ...string) *exec.Cmd {
cmd := exec.Command(name, arg...)
return cmd
}
func generateBlock() error {
if _, err := runCommand("nigiri", "rpc", "generatetoaddress", "1", "bcrt1qgqsguk6wax7ynvav4zys5x290xftk49h5agg0l"); err != nil {
return err
}
time.Sleep(6 * time.Second)
return nil
}
func logTxEvents(wallet string, client arksdk.ArkClient) {
txsChan := client.GetTransactionEventChannel()
go func() {
for txEvent := range txsChan {
msg := fmt.Sprintf("[EVENT]%s: tx event: %s, %d", wallet, txEvent.Event, txEvent.Tx.Amount)
if txEvent.Tx.IsBoarding() {
msg += fmt.Sprintf(", boarding tx: %s", txEvent.Tx.BoardingTxid)
}
log.Infoln(msg)
}
}()
log.Infof("%s tx event listener started", wallet)
}