Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: error handling #479

Merged
merged 4 commits into from
Oct 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 20 additions & 15 deletions src/lib/adapters/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import type { Schema } from 'zod'
type JSONdecoded = string | number | boolean | object | Array<JSONdecoded>

export async function saveToLocalStorage<T extends JSONdecoded>(key: string, data: T) {
if (!browser || !localStorage) {
console.error('Error saving to local storage: not in browser', data)
return
// Run in browser context only
if (!browser) return

if (!localStorage) {
throw new Error('Error saving to local storage: no local storage')
}

localStorage.setItem(key, JSON.stringify(data))
Expand All @@ -16,40 +18,43 @@ export function getFromLocalStorage<T extends JSONdecoded>(
key: string,
schema: Schema<T>,
): T | undefined {
if (!browser || !localStorage) {
console.error('Error getting from local storage: not in browser')
return
// Run in browser context only
if (!browser) return

if (!localStorage) {
throw new Error('Error getting from local storage: no local storage')
}

const data = localStorage.getItem(key)
if (!data) {
console.error('Error getting from local storage: no data', data)
return
throw new Error('Error getting from local storage: no data')
}

let parsed: unknown

try {
parsed = JSON.parse(data)
} catch (error) {
console.error(`Error getting from local storage: JSON parse error`, error)
return
throw new Error(
`Error getting from local storage: JSON parse error ${(error as Error).message}`,
)
}

const parseData = schema.safeParse(parsed)

if (!parseData.success) {
console.error(`Error getting from local storage: invalid data. ${parseData.error.issues}`, data)
return
throw new Error(`Error getting from local storage: invalid data. ${parseData.error.issues}`)
}

return parseData.data
}

export function removeFromLocalStorage(key: string) {
if (!browser || !localStorage) {
console.error('Error removing from local storage: not in browser')
return
// Run in browser context only
if (!browser) return

if (!localStorage) {
throw new Error('Error removing from local storage: no local storage')
}

localStorage.removeItem(key)
Expand Down
2 changes: 2 additions & 0 deletions src/lib/adapters/waku/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import { DEFAULT_FIAT_SYMBOL, exchangeStore } from '$lib/stores/exchangeRates'
import { balanceStore } from '$lib/stores/balances'
import type { ContentTopic } from './waku'
import { installedObjectStore } from '$lib/stores/installed-objects'
import { errorStore } from '$lib/stores/error'

const MAX_MESSAGES = 100

Expand Down Expand Up @@ -143,6 +144,7 @@ async function executeOnDataMessage(
...blockchainAdapter,
viewParams: [],
store,
addError: errorStore.addEnd,
updateStore,
send,
onViewChange: () => {
Expand Down
43 changes: 43 additions & 0 deletions src/lib/components/error-modal.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<script lang="ts">
export let title: string
export let message: string
</script>

<div class="root">
<div class="wrapper">
<h1>{title}</h1>
<p class="text-lg">{message}</p>
<div class="actions">
<slot />
</div>
</div>
</div>

<style>
.root {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: grid;
place-items: center;
background-color: rgba(var(--color-base-rgb, var(--color-dark-accent-rgb)), 0.5);
z-index: 1000;
padding: var(--spacing-24);
}
.wrapper {
background-color: var(--color-base, var(--color-dark-accent));
border-radius: var(--spacing-12);
padding: var(--spacing-24);
display: grid;
gap: var(--spacing-12);
place-items: center;
text-align: center;
box-shadow: 0px 1px 5px rgba(var(--color-accent-rgb, var(--color-dark-base-rgb)), 0.25);
}
.actions {
padding-top: var(--spacing-12);
gap: var(--spacing-12);
}
</style>
3 changes: 2 additions & 1 deletion src/lib/objects/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function makeWakuObjectAdapter(adapter: Adapter, wallet: BaseWallet): Wak
async function getTransaction(txHash: string): Promise<Transaction | undefined> {
const tx = await getTransactionResponse(txHash)
if (!tx) {
return undefined
throw new Error(`Transaction not found. ${txHash}}`)
}
const from = tx.from
const nonNativeToken = defaultBlockchainNetwork.tokens?.find((t) => t.address === tx.to)
Expand Down Expand Up @@ -70,6 +70,7 @@ export function makeWakuObjectAdapter(adapter: Adapter, wallet: BaseWallet): Wak
try {
timestamp = await getTransactionTimestamp(tx.blockNumber)
} catch (error) {
// TODO: review if this can silently fail or if we should throw
console.error(error)
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/lib/objects/chat.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import { chats } from '$lib/stores/chat'
import { DEFAULT_FIAT_SYMBOL, exchangeStore } from '$lib/stores/exchangeRates'
import { defaultBlockchainNetwork } from '$lib/adapters/transaction'
import { errorStore } from '$lib/stores/error'

export let message: DataMessage
export let users: User[]
Expand Down Expand Up @@ -65,6 +66,7 @@
store,
viewParams: [],
chatName,
addError: errorStore.addEnd,
send: (data: JSONSerializable) =>
adapter.sendData(wallet, chatId, message.objectId, message.instanceId, data),
updateStore,
Expand Down
6 changes: 5 additions & 1 deletion src/lib/objects/external/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,11 @@ export function makeIframeDispatcher(
}
postResponse(request.id, result, window)
} catch (e) {
console.error({ e })
args.addError({
title: 'External object error',
message: `Error dispatching. ${(e as Error)?.message}`,
ok: true,
})
const result: AdapterResponseError = {
type: 'error',
value: e,
Expand Down
1 change: 1 addition & 0 deletions src/lib/objects/external/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export const getNPMObject = async (
className,
}
} catch (err) {
// TODO: shouldn't this throw?
console.error(err)
return null
}
Expand Down
3 changes: 3 additions & 0 deletions src/lib/objects/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { ComponentType } from 'svelte'
import type { Transaction, User, TransactionState } from './schemas'
import type { Contract, Interface } from 'ethers'
import type { ExchangeRateRecord } from '$lib/stores/exchangeRates'
import type { ErrorDescriptor } from '$lib/stores/error'

export interface WakuObjectAdapter {
getTransaction(txHash: string): Promise<Transaction | undefined>
Expand Down Expand Up @@ -59,6 +60,8 @@ export interface WakuObjectContext<
send: (data: DataMessageType) => Promise<void>

onViewChange: (view: ViewType, ...rest: string[]) => void

addError: (error: ErrorDescriptor) => void
}

export interface WakuObjectArgs<
Expand Down
6 changes: 5 additions & 1 deletion src/lib/objects/payggy/chat.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@
if (res.success) {
data = res.data
} else {
console.error(res.error)
args.addError({
title: 'Payggy error',
message: `Received wrong payggy object. ${res.error.message}`,
ok: true,
})
}
}
}
Expand Down
57 changes: 36 additions & 21 deletions src/lib/objects/payggy/index.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,29 @@
import type { WakuObjectSvelteDescriptor } from '..'
import type { WakuObjectArgs, WakuObjectSvelteDescriptor } from '..'
import ChatComponent from './chat.svelte'
import { SendTransactionDataMessageSchema } from './schemas'
import StandaloneComponent from './standalone.svelte'
import logo from './logo.svg'
import { errorStore } from '$lib/stores/error'
import type { DataMessage } from '$lib/stores/chat'

export const PAYGGY_OBJECT_ID = 'payggy'

export const payggyDescriptor: WakuObjectSvelteDescriptor = {
objectId: PAYGGY_OBJECT_ID,
name: 'Payggy',
description: 'Send payments to chat members',
logo,

wakuObject: ChatComponent,
const onMessage = async (message: DataMessage, args: WakuObjectArgs) => {
if (!message?.data) {
console.error('Invalid message, no data', message)
return
}

standalone: StandaloneComponent,

onMessage: async (message, args) => {
if (!message?.data) {
return
}

const res = SendTransactionDataMessageSchema.safeParse(message.data)
if (!res.success) {
return
}
const res = SendTransactionDataMessageSchema.safeParse(message.data)
if (!res.success) {
console.error('Invalid message', res.error.message)
return
}

try {
const tx = await args.getTransaction(res.data.hash)
if (!tx) {
return
throw new Error(`Transaction not found. ${res.data.hash}}`)
}

const state = await args.getTransactionState(res.data.hash)
Expand Down Expand Up @@ -79,5 +74,25 @@ export const payggyDescriptor: WakuObjectSvelteDescriptor = {
args.checkBalance(token)
})
}
},
} catch (error) {
errorStore.addEnd({
title: 'Payggy message error',
message: `Failed to process paygy message transaction details. ${(error as Error).message}`,
retry: () => onMessage(message, args),
reload: true,
})
}
}

export const payggyDescriptor: WakuObjectSvelteDescriptor = {
objectId: PAYGGY_OBJECT_ID,
name: 'Payggy',
description: 'Send payments to chat members',
logo,

wakuObject: ChatComponent,

standalone: StandaloneComponent,

onMessage,
}
8 changes: 7 additions & 1 deletion src/lib/objects/payggy/standalone.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,18 @@
export let args: WakuObjectArgs

let store: SendTransactionStore | undefined

$: {
if (args.store) {
const res = SendTransactionStoreSchema.safeParse(args.store)
if (res.success) {
store = res.data
} else {
console.error(res.error)
args.addError({
title: 'Payggy error',
message: `Received wrong payggy object. ${res.error.message}`,
ok: true,
})
}
}
}
Expand Down Expand Up @@ -50,6 +55,7 @@
exitObject={exitObject(3)}
fiatRates={args.exchangeRates}
fiatSymbol={args.fiatSymbol}
addError={args.addError}
/>
{:else if args.view === 'details' && store}
<Details
Expand Down
50 changes: 38 additions & 12 deletions src/lib/objects/payggy/views/confirm-send.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -18,41 +18,67 @@
import { payggyDescriptor } from '..'
import type { ExchangeRateRecord } from '$lib/stores/exchangeRates'
import { getFiatAmountText } from '$lib/utils/fiat'
import type { ErrorDescriptor } from '$lib/stores/error'

export let toUser: User
export let estimateTransaction: (to: string, token: TokenAmount) => Promise<TokenAmount>
export let sendTransaction: (to: string, token: TokenAmount, fee: TokenAmount) => Promise<string>
export let send: (message: SendTransactionDataMessage) => Promise<void>
export let profile: User
export let amount: string
export let token: TokenAmount
export let fiatRates: Map<string, ExchangeRateRecord>
export let fiatSymbol: string | undefined

export let estimateTransaction: (to: string, token: TokenAmount) => Promise<TokenAmount>
export let sendTransaction: (to: string, token: TokenAmount, fee: TokenAmount) => Promise<string>
export let send: (message: SendTransactionDataMessage) => Promise<void>
export let exitObject: () => void
export let addError: (error: ErrorDescriptor) => void

let transactionSent = false
let fee: TokenAmount | undefined = undefined

$: if (toUser && amount && token) {
async function tryEstimateTransaction() {
try {
const tokenToTransfer = { ...token, amount: toBigInt(amount, token.decimals) }
estimateTransaction(toUser.address, tokenToTransfer).then((f) => (fee = f))
fee = await estimateTransaction(toUser.address, tokenToTransfer)
} catch (e) {
console.log({ e })
addError({
title: 'Payggy error',
message: `Failed to estimate transaction fee. ${(e as Error).message}`,
retry: tryEstimateTransaction,
ok: true,
})
}
}

$: if (toUser && amount && token) tryEstimateTransaction()

async function sendTransactionInternal() {
if (fee) {
transactionSent = true
if (!fee) {
addError({
title: 'Payggy error',
message: 'No estimated transaction fee.',
ok: true,
})
return
}

// FIXME error handling
const tokenToTransfer = { ...token, amount: toBigInt(amount, token.decimals) }
const transactionHash = await sendTransaction(toUser.address, tokenToTransfer, fee)
transactionSent = true
const tokenToTransfer = { ...token, amount: toBigInt(amount, token.decimals) }

await send({ hash: transactionHash })
let transactionHash: string
try {
transactionHash = await sendTransaction(toUser.address, tokenToTransfer, fee)

await send({ hash: transactionHash })
exitObject()
} catch (error) {
addError({
title: 'Payggy Error',
message: `Failed to send transaction. ${(error as Error).message}`,
retry: sendTransactionInternal,
ok: true,
})
return
}
}
</script>
Expand Down
Loading