withdraw fix; wrap still broken

This commit is contained in:
tim
2025-05-07 21:02:05 -04:00
parent a42f228984
commit 72b061749d
9 changed files with 81 additions and 26 deletions

View File

@@ -22,6 +22,7 @@ export class Transaction {
} }
submit() { submit() {
console.log('submitting transaction', this.type)
const ws = useWalletStore(); const ws = useWalletStore();
if ( ws.transaction !== null ) { if ( ws.transaction !== null ) {
console.error('Transaction already in progress', ws.transaction) console.error('Transaction already in progress', ws.transaction)
@@ -32,6 +33,7 @@ export class Transaction {
// "propose" means attach the transaction to a specific vault // "propose" means attach the transaction to a specific vault
propose(owner, vault) { propose(owner, vault) {
console.log('transaction bind', owner, vault)
if (this.vault !== null && this.vault !== vault) { if (this.vault !== null && this.vault !== vault) {
this.failed('proposed vault did not match withdrawl vault', vault, this.vault) this.failed('proposed vault did not match withdrawl vault', vault, this.vault)
return return

View File

@@ -33,12 +33,14 @@ export const useWalletStore = defineStore('wallet', ()=>{
set(v) { set(v) {
_tx.value = v; _tx.value = v;
if (v===null) { if (v===null) {
console.log('clear transaction')
if (progressionInvoker!==null) { if (progressionInvoker!==null) {
clearTimeout(progressionInvoker) clearTimeout(progressionInvoker)
progressionInvoker = null progressionInvoker = null
} }
} }
else { else {
console.log('set transaction', v)
transactionProgressor.invoke(); transactionProgressor.invoke();
if (progressionInvoker===null) if (progressionInvoker===null)
progressionInvoker = setInterval(()=>transactionProgressor.invoke(), 1000) progressionInvoker = setInterval(()=>transactionProgressor.invoke(), 1000)
@@ -242,7 +244,7 @@ async function _discoverVaults(owner) {
if( useWalletStore().transaction ) { if( useWalletStore().transaction ) {
const num = 0 // todo multiple vaults const num = 0 // todo multiple vaults
if (result.length) if (result.length)
flushOrders(s.chainId, owner, num, result[0]) flushWalletTransactions(s.chainId, owner, num, result[0])
else else
ensureVault2(s.chainId, owner, num) ensureVault2(s.chainId, owner, num)
} }
@@ -284,7 +286,7 @@ async function doEnsureVault(chainId, owner, num) {
if (s.vaults.length <= num) if (s.vaults.length <= num)
await _discoverVaults(owner) await _discoverVaults(owner)
if( s.vaults[num] ) if( s.vaults[num] )
flushOrders(chainId, owner, num, s.vaults[num]) flushWalletTransactions(chainId, owner, num, s.vaults[num])
else { else {
console.log(`requesting vault ${owner} ${num}`) console.log(`requesting vault ${owner} ${num}`)
socket.emit('ensureVault', chainId, owner, num) socket.emit('ensureVault', chainId, owner, num)
@@ -309,11 +311,13 @@ export async function cancelOrder(vault, orderIndex) {
async function progressTransactions() { async function progressTransactions() {
const s = useStore() const s = useStore()
const ws = useWalletStore(); const ws = useWalletStore();
console.log('progressTransactions', ws.transaction)
if( ws.transaction===null ) if( ws.transaction===null )
return return
if( s.account === null ) { if( s.account === null ) {
let signer = null let signer = null
try { try {
console.log('account is null. requesting sign-in.')
signer = await provider.getSigner() signer = await provider.getSigner()
} }
catch (e) { catch (e) {
@@ -333,11 +337,27 @@ async function progressTransactions() {
} }
} }
if( s.vault === null ) { if( s.vault === null ) {
console.log('vault is null. requesting vault creation.')
ensureVault() ensureVault()
return return
} }
if( ws.transaction.state < TransactionState.Proposed )
ws.transaction.propose(s.account, s.vault)
if( ws.transaction.type === TransactionType.PlaceOrder ) { if( ws.transaction.type === TransactionType.PlaceOrder ) {
flushOrders(s.chainId, s.account, 0, s.vault) flushWalletTransactions(s.chainId, s.account, 0, s.vault)
}
else {
console.log('flushing transaction', ws.transaction.type)
if (ws.transaction.state < TransactionState.Proposed) {
pendTransaction(async (signer) => {
if (signer.address !== ws.transaction.owner) {
console.error('signer address does not match transaction owner', signer.address, ws.transaction.owner)
return
}
const contract = await vaultContract(ws.transaction.vault, signer)
return await ws.transaction.createTx(contract)
})
}
} }
} }
@@ -346,12 +366,10 @@ const transactionProgressor = new SingletonCoroutine(progressTransactions, 10)
let progressionInvoker = null let progressionInvoker = null
export function flushOrders(chainId, owner, num, vault) { export function flushWalletTransactions(chainId, owner, num, vault) {
const ws = useWalletStore(); const ws = useWalletStore();
console.log('flushOrders', chainId, owner, num, vault) console.log('flushWalletTransactions', chainId, owner, num, vault)
if (ws.transaction!==null && ws.transaction.type === TransactionType.PlaceOrder && ws.transaction.state < TransactionState.Proposed) let needsFlush = ws.transaction !== null && ws.transaction.type !== TransactionType.PlaceOrder
ws.transaction.propose(owner, vault)
let needsFlush = false
for( const pend of ws.pendingOrders ) { for( const pend of ws.pendingOrders ) {
if (pend.vault === null) if (pend.vault === null)
pend.vault = vault pend.vault = vault
@@ -420,6 +438,7 @@ function pendOrderAsTransaction(pend) {
export function pendTransaction(sender, errHandler) { export function pendTransaction(sender, errHandler) {
console.log('pendTransaction')
const s = useStore() const s = useStore()
s.transactionSenders.push([sender,errHandler]) s.transactionSenders.push([sender,errHandler])
flushTransactions() flushTransactions()
@@ -438,6 +457,7 @@ async function asyncFlushTransactions() {
console.log('flushTransactions', ws.transaction, s.vault) console.log('flushTransactions', ws.transaction, s.vault)
if (ws.transaction !== null) { if (ws.transaction !== null) {
if (s.vault === null) { if (s.vault === null) {
console.log('transaction doesn\'t have a vault. creating one.')
await ensureVault() await ensureVault()
if (s.vault === null) { if (s.vault === null) {
console.error('vault could not be created') console.error('vault could not be created')
@@ -455,8 +475,10 @@ async function asyncFlushTransactions() {
return return
} }
const senders = s.transactionSenders const senders = s.transactionSenders
if (!senders.length) if (!senders.length) {
console.log('no transactionSenders!')
return return
}
console.log(`flushing ${senders.length} transactions`) console.log(`flushing ${senders.length} transactions`)
let signer let signer
try { try {

View File

@@ -158,6 +158,7 @@ export function initTVButtons() {
} }
export function initWidget(el) { export function initWidget(el) {
getAllSymbols()
const symbol = prefs.selectedTicker === null ? 'default' : prefs.selectedTicker const symbol = prefs.selectedTicker === null ? 'default' : prefs.selectedTicker
const interval = prefs.selectedTimeframe === null ? '15' : prefs.selectedTimeframe const interval = prefs.selectedTimeframe === null ? '15' : prefs.selectedTimeframe
widget = window.tvWidget = new TradingView.widget({ widget = window.tvWidget = new TradingView.widget({

View File

@@ -6,7 +6,7 @@ import {useChartOrderStore} from "@/orderbuild.js";
import {useStore} from "@/store/store.js"; import {useStore} from "@/store/store.js";
import {subOHLC, unsubOHLC} from "@/blockchain/ohlcs.js"; import {subOHLC, unsubOHLC} from "@/blockchain/ohlcs.js";
import {ohlcStart} from "@/charts/chart-misc.js"; import {ohlcStart} from "@/charts/chart-misc.js";
import {timestamp} from "@/common.js"; import {timestamp, withTimeout} from "@/common.js";
import {erc20Contract} from "@/blockchain/contract.js"; import {erc20Contract} from "@/blockchain/contract.js";
import {track} from "@/track.js"; import {track} from "@/track.js";
@@ -140,7 +140,7 @@ function addSymbol(chainId, p, base, quote, inverted) {
// console.log(`invertedDefault(${symbolInfo.base.s}, ${symbolInfo.quote.s})`,invertedDefault(symbolInfo.base.a, symbolInfo.quote.a)) // console.log(`invertedDefault(${symbolInfo.base.s}, ${symbolInfo.quote.s})`,invertedDefault(symbolInfo.base.a, symbolInfo.quote.a))
// } // }
if (defaultSymbol===null && !invertedDefault(symbolInfo.base.a, symbolInfo.quote.a)) { if (defaultSymbol===null && !invertedDefault(symbolInfo.base.a, symbolInfo.quote.a)) {
// console.log('setting default symbol', symbolInfo.base.s, symbolInfo.quote.s, symbolInfo.base.a, symbolInfo.quote.a) console.log('setting default symbol', symbolInfo.base.s, symbolInfo.quote.s, symbolInfo.base.a, symbolInfo.quote.a)
defaultSymbol = _symbols[ticker] defaultSymbol = _symbols[ticker]
} }
log('new symbol', ticker, _symbols[ticker]) log('new symbol', ticker, _symbols[ticker])
@@ -335,6 +335,14 @@ class RealtimeSubscription {
} }
async function getLiquidities(markToken, symbolItem) {
const token = await erc20Contract(markToken.a, provider)
const liquidities = await Promise.all(symbolItem.feeGroup.map(
async ([addr, fee]) => await token.balanceOf(addr)
))
return liquidities;
}
export const DataFeed = { export const DataFeed = {
onReady(callback) { onReady(callback) {
log('[onReady]: Method call'); log('[onReady]: Method call');
@@ -381,9 +389,12 @@ export const DataFeed = {
onResolveErrorCallback, onResolveErrorCallback,
extension extension
) { ) {
// console.log('[resolveSymbol]: Method call', symbolName); console.log('resolveSymbol', symbolName);
const symbols = getAllSymbols(); const symbols = getAllSymbols();
const symbolItem = symbolName === 'default' ? defaultSymbol : symbols[symbolName] const symbolItem = symbolName === 'default' ? defaultSymbol : symbols[symbolName]
if (symbolName==='default') {
console.log('using default symbol', defaultSymbol)
}
if (!symbolItem) { if (!symbolItem) {
console.log('[resolveSymbol]: Cannot resolve symbol', symbolName); console.log('[resolveSymbol]: Cannot resolve symbol', symbolName);
onResolveErrorCallback('cannot resolve symbol'); onResolveErrorCallback('cannot resolve symbol');
@@ -399,10 +410,11 @@ export const DataFeed = {
const inv = invertedDefault(symbolItem.base.a, symbolItem.quote.a) const inv = invertedDefault(symbolItem.base.a, symbolItem.quote.a)
const markToken = inv ? symbolItem.base : symbolItem.quote const markToken = inv ? symbolItem.base : symbolItem.quote
const mark = useStore().markPrice(markToken.a) const mark = useStore().markPrice(markToken.a)
const token = await erc20Contract(markToken.a, provider) const liquidities = await withTimeout(
const liquidities = await Promise.all(symbolItem.feeGroup.map( getLiquidities(markToken, symbolItem),
async ([addr, fee]) => await token.balanceOf(addr) 3000,
)) 'liquidity fetch timeout'
)
symbolItem.liquidities = liquidities.map(l => Number(l / 10n ** BigInt(markToken.d))) symbolItem.liquidities = liquidities.map(l => Number(l / 10n ** BigInt(markToken.d)))
if (mark) { if (mark) {
symbolItem.liquidities = symbolItem.liquidities.map(l => l * mark) symbolItem.liquidities = symbolItem.liquidities.map(l => l * mark)

View File

@@ -178,3 +178,13 @@ export function decodeBase62(str) {
return str.split('').reverse().reduce((acc, char, i) => return str.split('').reverse().reduce((acc, char, i) =>
acc + base62charset.indexOf(char) * Math.pow(62, i), 0); acc + base62charset.indexOf(char) * Math.pow(62, i), 0);
} }
export function withTimeout(promise, timeoutDuration, fallbackErrorMessage) {
return Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error(fallbackErrorMessage)), timeoutDuration)
),
]);
}

View File

@@ -34,10 +34,10 @@
<v-card-item v-if="!empty"> <v-card-item v-if="!empty">
<v-table> <v-table>
<tbody> <tbody>
<native-row v-if="nativeBalance" :chain-id="s.chainId" :addr="s.vault" :amount="nativeBalance" <native-row v-if="nativeBalance && BigInt(nativeBalance)>0n" :chain-id="s.chainId" :addr="s.vault" :amount="nativeBalance"
:on-withdraw="onWithdrawNative" :on-wrap="()=>wrapShow=true"/> :on-withdraw="onWithdrawNative" :on-wrap="()=>wrapShow=true"/>
<suspense v-for="(amount,addr) of balances"> <suspense v-for="(amount,addr) of balances">
<token-row v-if="BigInt(amount)>0n" :chain-id="s.chainId" :addr="addr" :amount="amount" :onWithdraw="onWithdraw"/> <token-row v-if="amount && BigInt(amount)>0n" :chain-id="s.chainId" :addr="addr" :amount="amount" :onWithdraw="onWithdraw"/>
</suspense> </suspense>
</tbody> </tbody>
</v-table> </v-table>
@@ -90,7 +90,7 @@ const hasVault = computed(()=>s.vault!==null)
const withdrawToken = ref(null) const withdrawToken = ref(null)
const withdrawShow = ref(false) const withdrawShow = ref(false)
async function onWithdraw(token) { async function onWithdraw(token) {
console.log('withdraw', addr, token) console.log('withdraw', addr.value, token)
withdrawToken.value = token withdrawToken.value = token
withdrawShow.value = true withdrawShow.value = true
} }

View File

@@ -11,7 +11,7 @@
<v-btn variant="text" text="max" @click="floatAmount=balanceFloat"/> <v-btn variant="text" text="max" @click="floatAmount=balanceFloat"/>
</template> </template>
<template v-slot:append-inner> <template v-slot:append-inner>
<span>{{ token.s }}</span> <span style="max-width: 6em">{{ token.s }}</span>
</template> </template>
</v-text-field> </v-text-field>
<v-card-actions> <v-card-actions>
@@ -36,11 +36,17 @@ const s = useStore()
const props = defineProps(['modelValue', 'vault', 'token']) const props = defineProps(['modelValue', 'vault', 'token'])
const emit = defineEmits(['update:modelValue']) const emit = defineEmits(['update:modelValue'])
const balance = computed(() => { const balance = computed(() => {
console.log('balance', props.vault, props.token, s.vaultBalances) const b = s.getBalance(props.token?.a)
const b = s.vaultBalances[props.vault][props.token.address]; console.log('balance', b)
// const b = s.vaultBalances[props.vault][props.token.address];
return b === undefined ? 0n : BigInt(b) return b === undefined ? 0n : BigInt(b)
}) })
const balanceFloat = computed(() => tokenFloat(props.token, balance.value)) const balanceFloat = computed(() => {
let balance = tokenFloat(props.token, s.getBalance(props.token?.a))
balance /= 10**props.token.d
console.log('balanceFloat', balance, s.getBalance(props.token?.a), props.token)
return balance
})
const floatAmount = ref(0) const floatAmount = ref(0)
function withdraw() { function withdraw() {

View File

@@ -66,7 +66,9 @@ export const uint32max = 4294967295
export const uint64max = 18446744073709551615n export const uint64max = 18446744073709551615n
export function tokenNumber(token, balance) { export function tokenNumber(token, balance) {
return FixedNumber.fromValue(balance, token.decimals, {decimals: token.decimals, width: 256}) const dec = token ? token.decimals : 0
console.log('token dec', dec, balance)
return FixedNumber.fromValue(balance, dec, {decimals: dec, width: 256})
} }
export function tokenFloat(token, balance) { export function tokenFloat(token, balance) {

View File

@@ -1,6 +1,6 @@
import {socket} from "@/socket.js"; import {socket} from "@/socket.js";
import {useStore} from "@/store/store.js"; import {useStore} from "@/store/store.js";
import {flushOrders} from "@/blockchain/wallet.js"; import {flushWalletTransactions} from "@/blockchain/wallet.js";
import {parseElaboratedOrderStatus} from "@/blockchain/orderlib.js"; import {parseElaboratedOrderStatus} from "@/blockchain/orderlib.js";
import {DataFeed} from "./charts/datafeed"; import {DataFeed} from "./charts/datafeed";
import {notifyFillEvent} from "@/notify.js"; import {notifyFillEvent} from "@/notify.js";
@@ -76,7 +76,7 @@ socket.on('vaults', (chainId, owner, vaults)=>{
s.vaults = vaults s.vaults = vaults
if( vaults.length ) { if( vaults.length ) {
const vault = vaults[0] const vault = vaults[0]
flushOrders(chainId, owner, 0, vault) flushWalletTransactions(chainId, owner, 0, vault)
} }
} }
}) })