mirror of
https://github.com/aljazceru/ark.git
synced 2025-12-17 04:04:21 +01:00
* 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>
436 lines
11 KiB
Go
436 lines
11 KiB
Go
//go:build js && wasm
|
|
// +build js,wasm
|
|
|
|
package browser
|
|
|
|
import (
|
|
"context"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strconv"
|
|
"syscall/js"
|
|
"time"
|
|
|
|
arksdk "github.com/ark-network/ark/pkg/client-sdk"
|
|
"github.com/ark-network/ark/pkg/client-sdk/wallet"
|
|
singlekeywallet "github.com/ark-network/ark/pkg/client-sdk/wallet/singlekey"
|
|
)
|
|
|
|
func ConsoleLog(msg string) {
|
|
js.Global().Get("console").Call("log", msg)
|
|
}
|
|
|
|
func ConsoleError(err error) {
|
|
js.Global().Get("console").Call("error", err.Error())
|
|
}
|
|
|
|
func LogWrapper() js.Func {
|
|
return js.FuncOf(func(this js.Value, p []js.Value) interface{} {
|
|
ConsoleLog(p[0].String())
|
|
return nil
|
|
})
|
|
}
|
|
|
|
func InitWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
// TODO: add another withTransactionFeed args to configure client listen to
|
|
// new txs from the server. Requires server to use websockets.
|
|
if len(args) != 7 {
|
|
return nil, errors.New("invalid number of args")
|
|
}
|
|
chain := args[5].String()
|
|
if chain != "bitcoin" && chain != "liquid" {
|
|
return nil, errors.New("invalid chain, select either 'bitcoin' or 'liquid'")
|
|
}
|
|
|
|
configStore := store.ConfigStore()
|
|
var walletSvc wallet.WalletService
|
|
switch args[0].String() {
|
|
case arksdk.SingleKeyWallet:
|
|
walletStore, err := getWalletStore(configStore.GetType())
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to init wallet store: %s", err)
|
|
}
|
|
if chain == "liquid" {
|
|
walletSvc, err = singlekeywallet.NewLiquidWallet(configStore, walletStore)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
} else {
|
|
walletSvc, err = singlekeywallet.NewBitcoinWallet(configStore, walletStore)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
default:
|
|
return nil, fmt.Errorf("unsupported wallet type")
|
|
}
|
|
|
|
err := arkSdkClient.InitWithWallet(context.Background(), arksdk.InitWithWalletArgs{
|
|
ClientType: args[1].String(),
|
|
Wallet: walletSvc,
|
|
AspUrl: args[2].String(),
|
|
Seed: args[3].String(),
|
|
Password: args[4].String(),
|
|
ExplorerURL: args[6].String(),
|
|
})
|
|
|
|
// Add this log message
|
|
ConsoleLog("ARK SDK client initialized successfully")
|
|
return nil, err
|
|
})
|
|
}
|
|
|
|
func IsLockedWrapper() js.Func {
|
|
return js.FuncOf(func(this js.Value, p []js.Value) interface{} {
|
|
return js.ValueOf(arkSdkClient.IsLocked(context.Background()))
|
|
})
|
|
}
|
|
|
|
func UnlockWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
if len(args) != 1 {
|
|
return nil, errors.New("invalid number of args")
|
|
}
|
|
password := args[0].String()
|
|
|
|
err := arkSdkClient.Unlock(context.Background(), password)
|
|
return nil, err
|
|
})
|
|
}
|
|
|
|
func LockWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
if len(args) != 1 {
|
|
return nil, errors.New("invalid number of args")
|
|
}
|
|
password := args[0].String()
|
|
|
|
err := arkSdkClient.Unlock(context.Background(), password)
|
|
return nil, err
|
|
})
|
|
}
|
|
|
|
func BalanceWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
if len(args) != 1 {
|
|
return nil, errors.New("invalid number of args")
|
|
}
|
|
computeExpiryDetails := args[0].Bool()
|
|
|
|
resp, err := arkSdkClient.Balance(context.Background(), computeExpiryDetails)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var (
|
|
onchainSpendableBalance int
|
|
onchainLockedBalance int
|
|
offchainBalance int
|
|
)
|
|
|
|
if resp != nil {
|
|
onchainSpendableBalance = int(resp.OnchainBalance.SpendableAmount)
|
|
for _, b := range resp.OnchainBalance.LockedAmount {
|
|
onchainLockedBalance += int(b.Amount)
|
|
}
|
|
offchainBalance = int(resp.OffchainBalance.Total)
|
|
}
|
|
|
|
result := map[string]interface{}{
|
|
"onchainBalance": map[string]interface{}{
|
|
"spendable": onchainSpendableBalance,
|
|
"locked": onchainLockedBalance,
|
|
},
|
|
"offchainBalance": offchainBalance,
|
|
}
|
|
|
|
return js.ValueOf(result), nil
|
|
})
|
|
}
|
|
|
|
func ReceiveWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
if arkSdkClient == nil {
|
|
return nil, errors.New("ARK SDK client is not initialized")
|
|
}
|
|
offchainAddr, boardingAddr, err := arkSdkClient.Receive(context.Background())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
result := map[string]interface{}{
|
|
"offchainAddr": offchainAddr,
|
|
"boardingAddr": boardingAddr,
|
|
}
|
|
return js.ValueOf(result), nil
|
|
})
|
|
}
|
|
|
|
func DumpWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
if arkSdkClient == nil {
|
|
return nil, errors.New("ARK SDK client is not initialized")
|
|
}
|
|
seed, err := arkSdkClient.Dump(context.Background())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return js.ValueOf(seed), nil
|
|
})
|
|
}
|
|
|
|
func SendOnChainWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
if len(args) != 1 {
|
|
return nil, errors.New("invalid number of args")
|
|
}
|
|
receivers := make([]arksdk.Receiver, args[0].Length())
|
|
for i := 0; i < args[0].Length(); i++ {
|
|
receiver := args[0].Index(i)
|
|
receivers[i] = arksdk.NewBitcoinReceiver(
|
|
receiver.Get("To").String(), uint64(receiver.Get("Amount").Int()),
|
|
)
|
|
}
|
|
|
|
txID, err := arkSdkClient.SendOnChain(
|
|
context.Background(), receivers,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return js.ValueOf(txID), nil
|
|
})
|
|
}
|
|
|
|
func SendOffChainWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
if len(args) != 2 {
|
|
return nil, errors.New("invalid number of args")
|
|
}
|
|
withExpiryCoinselect := args[0].Bool()
|
|
receivers := make([]arksdk.Receiver, args[1].Length())
|
|
for i := 0; i < args[1].Length(); i++ {
|
|
receiver := args[1].Index(i)
|
|
receivers[i] = arksdk.NewBitcoinReceiver(
|
|
receiver.Get("To").String(), uint64(receiver.Get("Amount").Int()),
|
|
)
|
|
}
|
|
|
|
txID, err := arkSdkClient.SendOffChain(
|
|
context.Background(), withExpiryCoinselect, receivers,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return js.ValueOf(txID), nil
|
|
})
|
|
}
|
|
|
|
func SendAsyncWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
if len(args) != 2 {
|
|
return nil, errors.New("invalid number of args")
|
|
}
|
|
withExpiryCoinselect := args[0].Bool()
|
|
receivers := make([]arksdk.Receiver, args[1].Length())
|
|
for i := 0; i < args[1].Length(); i++ {
|
|
receiver := args[1].Index(i)
|
|
receivers[i] = arksdk.NewBitcoinReceiver(
|
|
receiver.Get("To").String(), uint64(receiver.Get("Amount").Int()),
|
|
)
|
|
}
|
|
|
|
txID, err := arkSdkClient.SendAsync(
|
|
context.Background(), withExpiryCoinselect, receivers,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return js.ValueOf(txID), nil
|
|
})
|
|
}
|
|
|
|
func ClaimWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
if len(args) != 0 {
|
|
return nil, errors.New("invalid number of args")
|
|
}
|
|
|
|
resp, err := arkSdkClient.Claim(context.Background())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return js.ValueOf(resp), nil
|
|
})
|
|
}
|
|
|
|
func UnilateralRedeemWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
return nil, arkSdkClient.UnilateralRedeem(context.Background())
|
|
})
|
|
}
|
|
|
|
func CollaborativeRedeemWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
if len(args) != 3 {
|
|
return nil, errors.New("invalid number of args")
|
|
}
|
|
addr := args[0].String()
|
|
amount := uint64(args[1].Int())
|
|
withExpiryCoinselect := args[2].Bool()
|
|
|
|
txID, err := arkSdkClient.CollaborativeRedeem(
|
|
context.Background(), addr, amount, withExpiryCoinselect,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return js.ValueOf(txID), nil
|
|
})
|
|
}
|
|
|
|
func GetTransactionHistoryWrapper() js.Func {
|
|
return JSPromise(func(args []js.Value) (interface{}, error) {
|
|
history, err := arkSdkClient.GetTransactionHistory(context.Background())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
rawHistory := make([]map[string]interface{}, 0)
|
|
for _, record := range history {
|
|
rawHistory = append(rawHistory, map[string]interface{}{
|
|
"boardingTxid": record.BoardingTxid,
|
|
"roundTxid": record.RoundTxid,
|
|
"redeemTxid": record.RedeemTxid,
|
|
"amount": strconv.Itoa(int(record.Amount)),
|
|
"type": record.Type,
|
|
"isPending": record.IsPending,
|
|
"createdAt": record.CreatedAt.Format(time.RFC3339),
|
|
})
|
|
}
|
|
result, err := json.MarshalIndent(rawHistory, "", " ")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return js.ValueOf(string(result)), nil
|
|
})
|
|
}
|
|
|
|
func GetAspUrlWrapper() js.Func {
|
|
return js.FuncOf(func(this js.Value, p []js.Value) interface{} {
|
|
data, _ := arkSdkClient.GetConfigData(context.Background())
|
|
var url string
|
|
if data != nil {
|
|
url = data.AspUrl
|
|
}
|
|
return js.ValueOf(url)
|
|
})
|
|
}
|
|
|
|
func GetAspPubkeyWrapper() js.Func {
|
|
return js.FuncOf(func(this js.Value, p []js.Value) interface{} {
|
|
data, _ := arkSdkClient.GetConfigData(context.Background())
|
|
var aspPubkey string
|
|
if data != nil {
|
|
aspPubkey = hex.EncodeToString(data.AspPubkey.SerializeCompressed())
|
|
}
|
|
return js.ValueOf(aspPubkey)
|
|
})
|
|
}
|
|
|
|
func GetWalletTypeWrapper() js.Func {
|
|
return js.FuncOf(func(this js.Value, p []js.Value) interface{} {
|
|
data, _ := arkSdkClient.GetConfigData(context.Background())
|
|
var walletType string
|
|
if data != nil {
|
|
walletType = data.WalletType
|
|
}
|
|
return js.ValueOf(walletType)
|
|
})
|
|
}
|
|
|
|
func GetClientTypeWrapper() js.Func {
|
|
return js.FuncOf(func(this js.Value, p []js.Value) interface{} {
|
|
data, _ := arkSdkClient.GetConfigData(context.Background())
|
|
var clientType string
|
|
if data != nil {
|
|
clientType = data.ClientType
|
|
}
|
|
return js.ValueOf(clientType)
|
|
})
|
|
}
|
|
|
|
func GetNetworkWrapper() js.Func {
|
|
return js.FuncOf(func(this js.Value, p []js.Value) interface{} {
|
|
data, _ := arkSdkClient.GetConfigData(context.Background())
|
|
var network string
|
|
if data != nil {
|
|
network = data.Network.Name
|
|
}
|
|
return js.ValueOf(network)
|
|
})
|
|
}
|
|
|
|
func GetRoundLifetimeWrapper() js.Func {
|
|
return js.FuncOf(func(this js.Value, p []js.Value) interface{} {
|
|
data, _ := arkSdkClient.GetConfigData(context.Background())
|
|
var roundLifettime int64
|
|
if data != nil {
|
|
roundLifettime = data.RoundLifetime
|
|
}
|
|
return js.ValueOf(roundLifettime)
|
|
})
|
|
}
|
|
|
|
func GetUnilateralExitDelayWrapper() js.Func {
|
|
return js.FuncOf(func(this js.Value, p []js.Value) interface{} {
|
|
data, _ := arkSdkClient.GetConfigData(context.Background())
|
|
var unilateralExitDelay int64
|
|
if data != nil {
|
|
unilateralExitDelay = data.UnilateralExitDelay
|
|
}
|
|
return js.ValueOf(unilateralExitDelay)
|
|
})
|
|
}
|
|
|
|
func GetDustWrapper() js.Func {
|
|
return js.FuncOf(func(this js.Value, p []js.Value) interface{} {
|
|
data, _ := arkSdkClient.GetConfigData(context.Background())
|
|
var dust uint64
|
|
if data != nil {
|
|
dust = data.Dust
|
|
}
|
|
return js.ValueOf(dust)
|
|
})
|
|
}
|
|
|
|
type promise func(args []js.Value) (interface{}, error)
|
|
|
|
func JSPromise(fn promise) js.Func {
|
|
return js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
|
handlerArgs := args
|
|
handler := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
|
resolve := args[0]
|
|
reject := args[1]
|
|
|
|
go func() {
|
|
data, err := fn(handlerArgs)
|
|
if err != nil {
|
|
errorConstructor := js.Global().Get("Error")
|
|
errorObject := errorConstructor.New(err.Error())
|
|
reject.Invoke(errorObject)
|
|
} else {
|
|
resolve.Invoke(data)
|
|
}
|
|
}()
|
|
|
|
return nil
|
|
})
|
|
|
|
promiseConstructor := js.Global().Get("Promise")
|
|
return promiseConstructor.New(handler)
|
|
})
|
|
}
|