1
1
import * as v from "valibot"
2
- import { raise } from "$lib/utilities "
2
+ import { err , ok , ResultAsync } from "neverthrow "
3
3
4
4
const cosmosBalancesResponseSchema = v . object ( {
5
5
balances : v . array (
@@ -10,32 +10,33 @@ const cosmosBalancesResponseSchema = v.object({
10
10
)
11
11
} )
12
12
13
- export async function getCosmosChainBalances ( {
13
+ const fetchJson = ( url : string ) => {
14
+ return ResultAsync . fromPromise (
15
+ fetch ( url ) . then ( response => {
16
+ if ( ! response . ok ) {
17
+ throw new Error ( `HTTP error for url ${ url } status: ${ response . status } ` )
18
+ }
19
+ return response . json ( )
20
+ } ) ,
21
+ e =>
22
+ new Error ( `Failed to fetch data from url ${ url } with error: ${ ( e as Error ) . message } ` , {
23
+ cause : e
24
+ } )
25
+ )
26
+ }
27
+
28
+ export function getCosmosChainBalances ( {
14
29
url,
15
30
walletAddress
16
- } : { url : string ; walletAddress : string } ) {
17
- let json : undefined | unknown
18
-
19
- try {
20
- url = url . startsWith ( "https" ) ? url : `https://${ url } `
21
- const response = await fetch ( `${ url } /cosmos/bank/v1beta1/balances/${ walletAddress } ` )
22
- if ( ! response . ok ) raise ( "invalid response" )
23
-
24
- json = await response . json ( )
25
- } catch ( error ) {
26
- if ( error instanceof Error ) {
27
- raise ( `error fetching balances from /cosmos/bank: ${ error . message } ` )
28
- }
29
- raise ( `unknown error while fetching from /cosmos/bank: ${ JSON . stringify ( error ) } ` )
30
- }
31
-
32
- const result = v . safeParse ( cosmosBalancesResponseSchema , json )
33
-
34
- if ( ! result . success ) raise ( `error parsing result ${ JSON . stringify ( result . issues ) } ` )
35
- return result . output . balances . map ( x => ( {
36
- address : x . denom ,
37
- symbol : x . denom ,
38
- balance : BigInt ( x . amount ) ,
39
- decimals : 0
40
- } ) )
31
+ } : { url : string ; walletAddress : string } ) : ResultAsync <
32
+ v . InferOutput < typeof cosmosBalancesResponseSchema > ,
33
+ Error
34
+ > {
35
+ url = url . startsWith ( "https" ) ? url : `https://${ url } `
36
+ return fetchJson ( `${ url } /cosmos/bank/v1beta1/balances/${ walletAddress } ` ) . andThen ( json => {
37
+ const result = v . safeParse ( cosmosBalancesResponseSchema , json )
38
+ return result . success
39
+ ? ok ( result . output )
40
+ : err ( new Error ( "Validation failed:" , { cause : result . issues } ) )
41
+ } )
41
42
}
0 commit comments