Giter Site home page Giter Site logo

kaspa-wallet-deprecated's Introduction

Kaspa Wallet Framework

Kaspa Wallet implements Wallet functionality for the Kaspa Network

Kaspa Wallet is implemented in TypeScript and can be used server-side (NodeJs) and client-side (browser)

PLEASE NOTE: This project is under heavy development

Components

Kaspa Wallet uses the following modules:

Applications built on top of Kaspa Wallet Framework:

PLEASE NOTE: all Kaspa applications and libraries are under heavy development

Kaspa Wallet Framework

Before you can use Kaspa Wallet, you need to initialize the framework. Framework initialization loads various dependencies such as secp256k1-wasm and blake2b-wasm modules use in the underlying transaction cryptography.

const { Wallet, initKaspaFramework } = require('@kaspa/wallet');
const { RPC } = require('@kaspa/grpc-node');

(async () => { 
  await initKaspaFramework();
  ...
})();

Creating a wallet

Network types are identified by address prefixes:

  • kaspa (Mainnet)
  • kaspatest (Testnet)
  • kaspadev (Devnet)
  • kaspasim (Simnet)

Wallet class can be created using two static functions:

static fromMnemonic(
  seedPhrase: string, 
  networkOptions: NetworkOptions, 
  options: WalletOptions = {}): Wallet { }

static async import(
  password: string, 
  encryptedMnemonic: string, 
  networkOptions: NetworkOptions, 
  options: WalletOptions = {}): Promise <Wallet> { }

Wallet creation functions accept following configuration objects:

export interface WalletOptions{
  skipSyncBalance?:boolean;           // do not perform balance sync
  addressDiscoveryExtent?:number;     // address derivation scan (default 64)
  syncOnce?:boolean;                  // 'sync-and-exit' (true) or 'monitoring' mode
  logLevel?:string;                   // wallet log level
  disableAddressDerivation?:boolean;  // disable address derivation and discovery
}

export interface NetworkOptions{
  network:Network;                    // network: kaspa, kaspatest, kaspadev, kaspasim
  rpc?:IRPC;                          // gRPC interface (must be bound to transport before use)
}

Following options are important:

  • addressDiscoveryExtent - the number of HD address derivations to scan forward from the last known used address
  • syncOnce - allows wallet to be started temporarily, without starting monitoring services
  • disableAddressDerivation - starts wallet in a single-address mode, where receive address and change address will always be the first receive address generated from the private key.

Creating from Mnemonic:

const network = "kaspatest";
const { port } = Wallet.networkTypes[kaspatest].port; // default port for testnet
const rpc = new RPC({ clientConfig:{ host : '127.0.0.1:'+port } });

Wallet.fromMnemonic(
    "user mnemonic string",
    { network, rpc },
    {disableAddressDerivation:true}
);

Creating new wallet instance with dynamically generated mnemonic:

const wallet = new Wallet(null, null, {network, rpc});
const encryptedMnemonic = await wallet.export(cmd.password);
console.log('mnemonic:',wallet.mnemonic);
console.log('encrypted mnemonic:',encryptedMnemonic);

Restoring from encrypted mnemonic:

const password = "user password";
const encryptedMnemonic = "previously encrypted mnemonic";
let wallet = await Wallet.import(password, encryptedMnemonic, { network, rpc })

Logging and debugging

Wallet class contains an integrated logger that can be set to one of the following levels: error, warn, info, verbose, debug. The default log level is info. You can set the log level to verbose to see internal wallet data processing activity.

Wallet log level can be supplied as a part of WalletOptions (describe above) or set at runtime as follows:

wallet.setLogLevel('verbose');

Synchronizing a wallet

The function Wallet::sync(once?:boolean) can be used to perform wallet synchronization. Wallet synchronization will connect to kaspad and scan available UTXO entries for wallet addresses, update the wallet balance and if once is true, exit or if once is false, start wallet monitoring services.

When operating with monitoring enabled, wallet will retain connection to kaspad and dynamically update wallet UTXO entries as well as balances.

  • wallet.sync() - starts the wallet in monitoring mode
  • wallet.sync(true) - performs a single-time synchronization

Sending transactions

submitTransaction() function can be used to create transactions on the Kaspa network:

async submitTransaction(txParamsArg: TxSend): Promise < TxResp | null > {
  // ...
}

This function accepts TxSend object on input and returns a Promise<TxResp> object:

export interface TxSend {
  toAddr: string;
  amount: number;
  fee: number;
  changeAddrOverride? : string;
  networkFeeMax?:number;
}
  • toAddr - Destination address
  • amount - Amount of KAS in base units (sompis)
  • fee - Transaction priority fee
  • changeAddrOverride - (optional) Allows you to supply your own address for the change transaction
  • networkFeeMax - (optional) Allows you to set an upper bound for automatic network (data storage) fee calculation. Kaspa Wallet will automatically calculate appropriate fees and add them to the transaction based on the transaction size. This feature is disabled if the property is omitted or set to zero.
export interface TxResp {
  txid: string;
  rpctx?: string; // reserved
}
  • txid - Generated transaction id
try {
  let response = await this.wallet.submitTransaction({
      address, // destination address
      amount,  // amount in base units
      fee,     // user fees
  });
  if(!response)
    console.log('general error');  // if kaspad returns null (should never occur)
  else
    console.log('success:', txid);
} catch(ex) {
  console.log('error:',ex.toString());
}

On failure, submitTransaction() rejects with and error indicating the reason for failure.

Wallet balance

Wallet retains 2 types of balances:

  • available - balance contains KAS ready to be spent, comprised of UTXO records with block maturity blue score over 10.
  • pending - balance contains newly received transactions with UTXO block maturity less than 10. Upon each UTXO maturity balance is relocated from pending to available.

Wallet::balance is an object containing the following properties that are updated during wallet operation:

wallet.balance = {
  available: 5150000000000,
  pending: 247500000000,
  total: 5397500000000
}

Wallet events

Wallet::on(subject, (data) => { ... }) allows for event handler registration. Similarly to NodeJs EventEmitter you can unregister events by supplying original callback to Wallet::removeEventListener(subject, handler) as follows:

const balanceHandler = (balance)=>{ console.log(balance); }
wallet.on('balance-update', balanceHandler);
wallet.removeEventListener('balance-update', balanceHandler);

Following events are emitted by the Wallet class:

  • api-online - gPRC API is online
  • api-offline - gRPC API is offline
  • sync-start - wallet sync started (occurs each time gRPC API connects or re-connects)
  • sync-finish - wallet sync finished
  • ready - wallet is ready for use (sent after sync-finish, event data contains the balance object)
  • blue-score-changed - indicates Kaspa blue score change (new block generation)
  • utxo-change - signaled when UTXO is added or removed from the wallet UTXO set
  • balance-update - indicates wallet balance change (event data contains the balance object)

kaspa-wallet-deprecated's People

Contributors

surinder83singh avatar aspect avatar n15a avatar someone235 avatar

Stargazers

snake avatar Bill avatar  avatar duoduo avatar Eric avatar kib0rg avatar Allen avatar Mercury Lee avatar  avatar

Watchers

James Cloos avatar  avatar  avatar tbear avatar  avatar  avatar Tiram avatar  avatar

kaspa-wallet-deprecated's Issues

installing kaspa-wallet with npm dependency issues

followed your instructions, I did run npm install on my machine where nodejs never seen in past and got following error (dependencys?)

$ kaspa-wallet help
/usr/lib/node_modules/@kaspa/wallet-cli/kaspa-wallet.js:48
errorCB?.(count)
^

SyntaxError: Unexpected token .
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.runMain (module.js:611:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:160:9)

Subscribing to derived address

Hello, I would like to know - is there a way to subscribe to the events of the derived addresses?
When I was using main receive address, i was getting the events, but when i tried to send KAS to derived address, no events emitted.
Here i derive address with index

deriveAddress(index: number) {
        // const dType = deriveType === 'receive' ? 0 : 1;
        const dType = '0'
        const seedWallet = Wallet.fromMnemonic(KEYCHAIN_SEED, { network: 'kaspa', rpc: this.rpc })
        const privateKey = seedWallet.HDWallet.deriveChild(`m/44'/972/0'/${dType}'/${index}'`)
        const addressManager = new AddressManager(privateKey, 'kaspa')
        const newAddr = addressManager.getAddresses(1, 'receive')

        return {
            publicKey: newAddr[0].address,
            privateKey: addressManager.receiveAddress.keypairs[newAddr[0].address].toString(),
        }
    }

Here, I'm subscribing to the events.

 const wallet = Wallet.fromMnemonic(
            KEYCHAIN_SEED,
            { network: 'kaspa', rpc: this.rpc },
            {
                addressDiscoveryExtent: 1000,
            }
        )
        
  wallet.on('balance-update', balance => {
            this.logger.warn('BALANCE UPDATED')
            this.logger.debug(JSON.stringify(balance))
        }) 

Accessing fund I'm a wallett

Accessing & Moving Kaspa out of this wallet. kaspa:qz93p25pjzr676vtl7n4kvf669pth7ssdmx7kqv8n50f8q7a7j0vjxjgun6hs
Or at least wanna get init I can't remember what platform it came from and I lost secret phrase and password.
KAS-Miner-Mining-Protocol-EN.pdf

Uploading e02894cc2fc119b6e136de13cff0481b.mp4…

Uploading Screenshot_20240707-090226.png…

Compound address derivation advance issue

I have this wallet from december. had slowly accumulated 700k for 2 month, compounding every 40k 3 miners, everyone have different address so spends will not grow too much, about 40 blocks@day
Using always latest KDX/kaspad, for compounding and monitoring from web-wallet

I did a compound today as usual, for every 40k and after that i found that new blocks from miners not showing up in transaction list

image

I went to kaspa-wallet-cli on my second node
this address, from compounding operation, was not in wallet-cli list kaspa:qph8y9z5497va9fcgu0dfg2qgxhkp4fwvl6mkctuzu9uu995al42yr6595n4g
i went to katnip freshly running on fresh node and saw no issue with that address
http://demisrael.synology.me:3040/addr/kaspa:qph8y9z5497va9fcgu0dfg2qgxhkp4fwvl6mkctuzu9uu995al42yr6595n4g
I checked address list now cli-wallet shows me 150 change addresses and 300 addresses..
Next, i requested 5kas from faucet and didn't saw incoming transaction. Then i clicked "scan more addresses" and it found another 13,500 KAS i was not familiar with.

Then found that wallet-cli shows me following balance:
balance available: 13,500 KAS pending: 0 KAS total: 13,500 KAS
The KDX was showing balance of 704,810.22200414 instead of 691,310.22200414 and i sent 704,810 KAS to known address from that same wallet. now it was look legit and i will try to do another compounding to see if issue persist.
kaspa-wallet-cli-addresses.txt - list of addresses - you can see that kaspa:qph8y9z5497va9fcgu0dfg2qgxhkp4fwvl6mkctuzu9uu995al42yr6595n4g not in list
kaspa-wallet-cli-addresses.txt
kaspa-compound-txs.txt -
kaspa-compound-txs.txt

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.