feat: add network for wallet accounts

This commit is contained in:
Vlad Stan 2022-08-01 11:51:10 +03:00
parent 4671954896
commit 6150b767e4
9 changed files with 57 additions and 23 deletions

View file

@ -22,9 +22,10 @@ async def create_watch_wallet(w: WalletAccount) -> WalletAccount:
title, title,
type, type,
address_no, address_no,
balance balance,
network
) )
VALUES (?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""", """,
( (
wallet_id, wallet_id,
@ -35,6 +36,7 @@ async def create_watch_wallet(w: WalletAccount) -> WalletAccount:
w.type, w.type,
w.address_no, w.address_no,
w.balance, w.balance,
w.network,
), ),
) )
@ -48,9 +50,10 @@ async def get_watch_wallet(wallet_id: str) -> Optional[WalletAccount]:
return WalletAccount.from_row(row) if row else None return WalletAccount.from_row(row) if row else None
async def get_watch_wallets(user: str) -> List[WalletAccount]: async def get_watch_wallets(user: str, network: str) -> List[WalletAccount]:
rows = await db.fetchall( rows = await db.fetchall(
"""SELECT * FROM watchonly.wallets WHERE "user" = ?""", (user,) """SELECT * FROM watchonly.wallets WHERE "user" = ? AND network = ?""",
(user, network),
) )
return [WalletAccount(**row) for row in rows] return [WalletAccount(**row) for row in rows]

View file

@ -77,6 +77,16 @@ async def m004_create_config_table(db):
);""" );"""
) )
async def m005_add_network_column_to_wallets(db):
"""
Add network' column to the 'wallets' table
"""
await db.execute(
"ALTER TABLE watchonly.wallets ADD COLUMN network TEXT DEFAULT 'Mainnet';"
)
### TODO: fix statspay dependcy first ### TODO: fix statspay dependcy first
# await db.execute( # await db.execute(
# "DROP TABLE watchonly.wallets;" # "DROP TABLE watchonly.wallets;"

View file

@ -7,6 +7,7 @@ from pydantic import BaseModel
class CreateWallet(BaseModel): class CreateWallet(BaseModel):
masterpub: str = Query("") masterpub: str = Query("")
title: str = Query("") title: str = Query("")
network: str = "Mainnet"
class WalletAccount(BaseModel): class WalletAccount(BaseModel):

View file

@ -65,7 +65,7 @@
<div> <div>
<a <a
style="color: unset" style="color: unset"
:href="mempoolEndpoint + '/address/' + props.row.address" :href="'https://'+ mempoolEndpoint + '/address/' + props.row.address"
target="_blank" target="_blank"
> >
{{props.row.address}}</a {{props.row.address}}</a

View file

@ -8,11 +8,7 @@ async function walletConfig(path) {
data: function () { data: function () {
return { return {
networOptions: ['Mainnet', 'Testnet'], networOptions: ['Mainnet', 'Testnet'],
internalConfig: { internalConfig: {},
mempool_endpoint: 'https://mempool.space',
receive_gap_limit: 20,
change_gap_limit: 5
},
show: false show: false
} }
}, },

View file

@ -4,7 +4,7 @@ async function walletList(path) {
name: 'wallet-list', name: 'wallet-list',
template, template,
props: ['adminkey', 'inkey', 'sats-denominated', 'addresses'], props: ['adminkey', 'inkey', 'sats-denominated', 'addresses', 'network'],
data: function () { data: function () {
return { return {
walletAccounts: [], walletAccounts: [],
@ -47,6 +47,15 @@ async function walletList(path) {
} }
} }
}, },
watch: {
immediate: true,
async network(newNet, oldNet) {
console.log('### newNet, oldNet', newNet, oldNet)
if (newNet !== oldNet) {
await this.refreshWalletAccounts()
}
}
},
methods: { methods: {
satBtc(val, showUnit = true) { satBtc(val, showUnit = true) {
@ -55,6 +64,7 @@ async function walletList(path) {
addWalletAccount: async function () { addWalletAccount: async function () {
const data = _.omit(this.formDialog.data, 'wallet') const data = _.omit(this.formDialog.data, 'wallet')
data.network = this.network
await this.createWalletAccount(data) await this.createWalletAccount(data)
}, },
createWalletAccount: async function (data) { createWalletAccount: async function (data) {
@ -106,7 +116,7 @@ async function walletList(path) {
try { try {
const {data} = await LNbits.api.request( const {data} = await LNbits.api.request(
'GET', 'GET',
'/watchonly/api/v1/wallet', `/watchonly/api/v1/wallet/?network=${this.network}`,
this.inkey this.inkey
) )
return data return data

View file

@ -47,14 +47,15 @@ const watchOnly = async () => {
showAddress: false, showAddress: false,
addressNote: '', addressNote: '',
showPayment: false, showPayment: false,
fetchedUtxos: false fetchedUtxos: false,
network: null
} }
}, },
computed: { computed: {
mempoolHostname() { mempoolHostname: function () {
if (!this.config.isLoaded) return if (!this.config.isLoaded) return
const hostname = new URL(this.config.mempool_endpoint).hostname let hostname = new URL(this.config.mempool_endpoint).hostname
if (this.config.network === 'testnet') { if (this.config.network === 'Testnet') {
hostname += '/testnet' hostname += '/testnet'
} }
return hostname return hostname

View file

@ -17,9 +17,11 @@
</wallet-config> </wallet-config>
<wallet-list <wallet-list
v-if="config.isLoaded"
:adminkey="g.user.wallets[0].adminkey" :adminkey="g.user.wallets[0].adminkey"
:inkey="g.user.wallets[0].inkey" :inkey="g.user.wallets[0].inkey"
:sats-denominated="config.sats_denominated" :sats-denominated="config.sats_denominated"
:network="config.network"
:addresses="addresses" :addresses="addresses"
@accounts-update="updateAccounts" @accounts-update="updateAccounts"
@new-receive-address="showAddressDetails" @new-receive-address="showAddressDetails"

View file

@ -49,12 +49,17 @@ from .helpers import parse_key
@watchonly_ext.get("/api/v1/wallet") @watchonly_ext.get("/api/v1/wallet")
async def api_wallets_retrieve(wallet: WalletTypeInfo = Depends(get_key_type)): async def api_wallets_retrieve(
network: str = Query("Mainnet"), wallet: WalletTypeInfo = Depends(get_key_type)
):
try: try:
return [wallet.dict() for wallet in await get_watch_wallets(wallet.wallet.user)] return [
wallet.dict()
for wallet in await get_watch_wallets(wallet.wallet.user, network)
]
except: except:
return "" return []
@watchonly_ext.get("/api/v1/wallet/{wallet_id}") @watchonly_ext.get("/api/v1/wallet/{wallet_id}")
@ -76,7 +81,13 @@ async def api_wallet_create_or_update(
data: CreateWallet, w: WalletTypeInfo = Depends(require_admin_key) data: CreateWallet, w: WalletTypeInfo = Depends(require_admin_key)
): ):
try: try:
(descriptor, _) = parse_key(data.masterpub) (descriptor, network) = parse_key(data.masterpub)
if data.network != network["name"]:
raise ValueError(
"Account network error. This account is for '{}'".format(
network["name"]
)
)
new_wallet = WalletAccount( new_wallet = WalletAccount(
id="none", id="none",
@ -87,9 +98,10 @@ async def api_wallet_create_or_update(
title=data.title, title=data.title,
address_no=-1, # so fresh address on empty wallet can get address with index 0 address_no=-1, # so fresh address on empty wallet can get address with index 0
balance=0, balance=0,
network=network["name"],
) )
wallets = await get_watch_wallets(w.wallet.user) wallets = await get_watch_wallets(w.wallet.user, network["name"])
existing_wallet = next( existing_wallet = next(
(ew for ew in wallets if ew.fingerprint == new_wallet.fingerprint), None (ew for ew in wallets if ew.fingerprint == new_wallet.fingerprint), None
) )
@ -233,7 +245,7 @@ async def api_psbt_create(
descriptors[masterpub.fingerprint] = parse_key(masterpub.public_key) descriptors[masterpub.fingerprint] = parse_key(masterpub.public_key)
inputs_extra = [] inputs_extra = []
for i, inp in enumerate(data.inputs): for i, inp in enumerate(data.inputs):
bip32_derivations = {} bip32_derivations = {}
descriptor = descriptors[inp.masterpub_fingerprint][0] descriptor = descriptors[inp.masterpub_fingerprint][0]
@ -292,7 +304,6 @@ async def api_psbt_extract_tx(
if not final_psbt: if not final_psbt:
raise ValueError("PSBT cannot be finalized!") raise ValueError("PSBT cannot be finalized!")
res.tx_hex = final_psbt.to_string() res.tx_hex = final_psbt.to_string()
print('### hex', res.tx_hex)
transaction = Transaction.from_string(res.tx_hex) transaction = Transaction.from_string(res.tx_hex)
tx = { tx = {