github.com/0chain/gosdk@v1.17.11/wasmsdk/wallet.go (about)

     1  //go:build js && wasm
     2  // +build js,wasm
     3  
     4  package main
     5  
     6  import (
     7  	"errors"
     8  
     9  	"fmt"
    10  	"os"
    11  	"strconv"
    12  
    13  	"github.com/0chain/gosdk/core/zcncrypto"
    14  	"github.com/0chain/gosdk/wasmsdk/jsbridge"
    15  	"github.com/0chain/gosdk/zboxcore/client"
    16  	"github.com/0chain/gosdk/zcncore"
    17  )
    18  
    19  func setWallet(clientID, clientKey, peerPublicKey, publicKey, privateKey, mnemonic string, isSplit bool) error {
    20  	if mnemonic == "" && !isSplit {
    21  		return errors.New("mnemonic is required")
    22  	}
    23  	mode := os.Getenv("MODE")
    24  	fmt.Println("gosdk setWallet, mode:", mode, "is split:", isSplit)
    25  	keys := []zcncrypto.KeyPair{
    26  		{
    27  			PrivateKey: privateKey,
    28  			PublicKey:  publicKey,
    29  		},
    30  	}
    31  
    32  	c := client.GetClient()
    33  	c.Mnemonic = mnemonic
    34  	c.ClientID = clientID
    35  	c.ClientKey = clientKey
    36  	c.PeerPublicKey = peerPublicKey
    37  	c.Keys = keys
    38  	c.IsSplit = isSplit
    39  
    40  	w := &zcncrypto.Wallet{
    41  		ClientID:      clientID,
    42  		ClientKey:     clientKey,
    43  		PeerPublicKey: peerPublicKey,
    44  		Mnemonic:      mnemonic,
    45  		Keys:          keys,
    46  		IsSplit:       isSplit,
    47  	}
    48  	fmt.Println("set Wallet, is split:", isSplit)
    49  	err := zcncore.SetWallet(*w, isSplit)
    50  	if err != nil {
    51  		return err
    52  	}
    53  
    54  	zboxApiClient.SetWallet(clientID, privateKey, publicKey)
    55  	if mode == "" { // main thread, need to notify the web worker to update wallet
    56  		// notify the web worker to update wallet
    57  		if err := jsbridge.PostMessageToAllWorkers(jsbridge.MsgTypeUpdateWallet, map[string]string{
    58  			"client_id":       clientID,
    59  			"client_key":      clientKey,
    60  			"peer_public_key": peerPublicKey,
    61  			"public_key":      publicKey,
    62  			"private_key":     privateKey,
    63  			"mnemonic":        mnemonic,
    64  			"is_split":        strconv.FormatBool(isSplit),
    65  		}); err != nil {
    66  			return err
    67  		}
    68  	}
    69  
    70  	return nil
    71  }