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

Improved CW20 prediction in app #3674

Draft
wants to merge 11 commits into
base: main
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion app/app.nix
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ _: {
{
packages = {
app = jsPkgs.buildNpmPackage {
npmDepsHash = "sha256-ZXPdOFx9IyZNGVbKXSBm1rDA3rkwgQYQROrAX35E09c=";
npmDepsHash = lib.fakeHash;
src = ./.;
sourceRoot = "app";
npmFlags = [
Expand Down
9 changes: 5 additions & 4 deletions app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@
"postinstall": "patch-package"
},
"dependencies": {
"temporal-polyfill": "^0.2.5",
"mode-watcher": "0.5.0",
"svelte-sonner": "^0.3.27",
"@cosmjs/amino": "^0.32.4",
"@cosmjs/cosmwasm-stargate": "0.32.4",
"@cosmjs/encoding": "^0.32.4",
Expand All @@ -28,15 +25,19 @@
"@tanstack/svelte-query": "5.61.5",
"@tanstack/svelte-table": "^8.20.5",
"@tanstack/svelte-virtual": "3.10.9",
"@unionlabs/client": "0.0.53",
"@unionlabs/client": "0.0.55",
"@wagmi/connectors": "5.7.5",
"@wagmi/core": "2.16.3",
"bits-ui": "^0.21.13",
"cmdk-sv": "^0.0.18",
"gql.tada": "1.8.10",
"graphql-request": "7.1.2",
"mode-watcher": "0.5.0",
"neverthrow": "^8.1.1",
"svelte-persisted-store": "^0.11.0",
"svelte-radix": "^1.1.1",
"svelte-sonner": "^0.3.27",
"temporal-polyfill": "^0.2.5",
"three": "0.170.0",
"valibot": "0.42.1",
"vaul-svelte": "^0.3.2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,15 @@ export let rotateTo: Props["rotateTo"]
let { rawIntents, intents, context } = stores

let sortedTokens = derived([context], ([$context]) =>
$context.baseTokens.toSorted((a, b) => Number(BigInt(b.balance) - BigInt(a.balance)))
$context.baseTokens.toSorted((a, b) => {
if (a.balance.isErr()) {
return 1
}
if (b.balance.isErr()) {
return -1
}
return Number(BigInt(b.balance.value) - BigInt(a.balance.value))
})
)

function setAsset(denom: string) {
Expand Down Expand Up @@ -55,7 +63,14 @@ function setAsset(denom: string) {
class="px-2 py-1 hover:bg-neutral-400 dark:hover:bg-neutral-800 text-md flex justify-start items-center"
on:click={() => setAsset(token.denom)}
>
<Token chainId={$rawIntents.source} denom={token.denom} amount={token.balance} {chains}/>
{#if token.balance.isOk() }
<Token chainId={$rawIntents.source} denom={token.denom} amount={token.balance.value} {chains}/>
{:else}
<div class="text-left">
<Token chainId={$rawIntents.source} denom={token.denom} {chains}/>
<div class="text-xs">{token.balance.error.message}</div>
</div>
{/if}
</button>
{/each}
</div>
Expand Down
2 changes: 1 addition & 1 deletion app/src/lib/components/TransferFrom/index.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,4 @@ validation.subscribe(async data => {
{#if TRANSFER_DEBUG}
<DebugBox {stores}/>
{/if}
</div>
</div>
11 changes: 9 additions & 2 deletions app/src/lib/components/TransferFrom/transfer/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { derived, type Readable } from "svelte/store"
import type { Chain, Ucs03Channel, UserAddresses } from "$lib/types"
import type { userBalancesQuery } from "$lib/queries/balance"
import type { RawIntentsStore } from "$lib/components/TransferFrom/transfer/raw-intents"
import { err, ok, type Result } from "neverthrow"

export interface TokenBalance {
denom: string
balance: string
balance: Result<string, Error>
}

export interface BalanceQueryResult {
Expand Down Expand Up @@ -34,7 +35,13 @@ export function createContextStore(
const chainBalances = $balances.find(b => b.data?.chain_id === $rawIntents.source)?.data
return sourceChain.tokens.map(token => ({
denom: token.denom,
balance: chainBalances?.balances[token.denom] ?? "0"
balance:
chainBalances?.balances?.andThen(bal => {
if (bal[token.denom]) {
return ok(bal[token.denom])
}
return err(new Error("no balance for this asset"))
}) ?? err(new Error("chainbalances undefined"))
}))
})

Expand Down
2 changes: 1 addition & 1 deletion app/src/lib/components/address.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const explorer = chain?.explorers?.at(0)?.address_url ?? null

<!-- svelte-ignore a11y-interactive-supports-focus -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div class={cn("flex flex-col text-xs transition-colors", $highlightItem?.kind === "address" && $highlightItem.address === address ? "bg-union-accent-300 dark:bg-union-accent-950" : "")}
<div class={cn("flex flex-col text-xs", $highlightItem?.kind === "address" && $highlightItem.address === address ? "bg-union-accent-300 dark:bg-union-accent-950" : "")}
on:mouseleave={() => highlightItem.set(null)}
on:mouseenter={() => {
highlightItem.set(address ? { kind: "address", address} : null)
Expand Down
75 changes: 34 additions & 41 deletions app/src/lib/components/chains-gate.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -25,50 +25,43 @@ let checkedChains: Readable<Array<Chain>> = derived([chains, page], ([$chains, $
return EMPTY_CHAINS
}

return $chains.data
.map(chain => {
let display_name = ""
return $chains.data.map(chain => {
let display_name = ""

if (chain.display_name === null) {
console.error("no display_name for chain", chain)
} else {
display_name = chain.display_name
}
if (chain.display_name === null) {
console.error("no display_name for chain", chain)
} else {
display_name = chain.display_name
}

let rpcType = chain.rpc_type
if (!rpcType) console.error("no rpc type found")
let rpcType = chain.rpc_type
if (!rpcType) console.error("no rpc type found")

let addr_prefix = ""
if (chain.addr_prefix === null) {
console.error("no addr_prefix for chain", chain)
} else {
addr_prefix = chain.addr_prefix
}
let addr_prefix = ""
if (chain.addr_prefix === null) {
console.error("no addr_prefix for chain", chain)
} else {
addr_prefix = chain.addr_prefix
}

return {
chain_id: chain.chain_id,
enabled: chain.enabled,
enabled_staging: chain.enabled_staging,
display_name,
rpc_type: rpcType,
rpcs: chain.rpcs,
addr_prefix,
testnet: !!chain.testnet,
explorers: chain.explorers,
// this as statement should no longer be required in the next typescript release
tokens: chain.tokens,
// @deprecated
assets: chain.assets.filter(
asset => asset.display_symbol !== null && asset.decimals !== null && asset.denom !== null
) as Chain["assets"]
} as Chain
})
.filter(chain => {
const chainFeature = $page.data.features.find(
(feature: ChainFeature) => feature.chain_id === chain.chain_id
)
return chainFeature?.features[0]?.transfer_submission
})
return {
chain_id: chain.chain_id,
enabled: chain.enabled,
enabled_staging: chain.enabled_staging,
display_name,
rpc_type: rpcType,
rpcs: chain.rpcs,
addr_prefix,
testnet: !!chain.testnet,
explorers: chain.explorers,
// this as statement should no longer be required in the next typescript release
tokens: chain.tokens,
// @deprecated
assets: chain.assets.filter(
asset => asset.display_symbol !== null && asset.decimals !== null && asset.denom !== null
) as Chain["assets"]
} as Chain
})
})

let checkedUcs03Channels: Readable<Array<Ucs03Channel>> = derived(ucs03channels, $ucs03channels => {
Expand Down Expand Up @@ -101,4 +94,4 @@ let checkedUcs03Channels: Readable<Array<Ucs03Channel>> = derived(ucs03channels,
<LoadingLogo class="size-16" />
{:else if $chains.isError}
Error loading chains.
{/if}
{/if}
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,6 @@ const render = (mode: string | undefined) => {

renderer.render(scene, camera)
requestAnimationFrame(animate)
// console.log(clock.elapsedTime);
}
requestAnimationFrame(animate)
}
Expand Down
4 changes: 1 addition & 3 deletions app/src/lib/components/token.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ export let userAmount: string | null = null
export let expanded = false

$: chain = chains.find(c => c.chain_id === chainId) ?? null
$: graphqlToken =
chain?.tokens.find(t => t.denom?.toLowerCase() === (denom ?? "").toLowerCase()) ?? null
$: tokenInfo = tokenInfoQuery(chainId, (denom ?? "").toLowerCase(), chains)
</script>

Expand All @@ -41,7 +39,7 @@ $: tokenInfo = tokenInfoQuery(chainId, (denom ?? "").toLowerCase(), chains)
{#if userAmount !== null}
{userAmount}
{/if}
<span class={cn("inline-flex gap-1 transition-colors", $highlightItem?.kind === "token" && $highlightItem.denom === denom ? "bg-union-accent-300 dark:bg-union-accent-950" : "")}><b><Truncate
<span class={cn("inline-flex gap-1", $highlightItem?.kind === "token" && $highlightItem.denom === denom ? "bg-union-accent-300 dark:bg-union-accent-950" : "")}><b><Truncate
value={token.combined.symbol} type="symbol"/></b>
<div class="text-muted-foreground text-xs flex gap-1 items-center">
{toDisplayName(chainId, chains)}
Expand Down
1 change: 0 additions & 1 deletion app/src/lib/components/transfer-details.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ let transfers = createQuery({
refetchInterval: query => (query.state.data?.length === 0 ? 1_000 : false), // fetch every second until we have the transaction
placeholderData: (previousData, _) => previousData,
queryFn: async () => {
console.log("querying")
const response = await request(URLS().GRAPHQL, transfersBySourceHashBaseQueryDocument, {
source_transaction_hash: source
})
Expand Down
64 changes: 37 additions & 27 deletions app/src/lib/queries/balance/cosmos.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import * as v from "valibot"
import { raise } from "$lib/utilities"
import { err, errAsync, ok, ResultAsync } from "neverthrow"
import type { RawBalances } from "."
import { toHex } from "viem"
import { isValidBech32Address } from "@unionlabs/client"

const cosmosBalancesResponseSchema = v.object({
balances: v.array(
Expand All @@ -10,32 +13,39 @@ const cosmosBalancesResponseSchema = v.object({
)
})

export async function getCosmosChainBalances({
const fetchJson = (url: string) => {
return ResultAsync.fromPromise(
fetch(url).then(response => {
if (!response.ok) {
throw new Error(`HTTP error for url ${url} status: ${response.status}`)
}
return response.json()
}),
e =>
new Error(`Failed to fetch data from url ${url} with error: ${(e as Error).message}`, {
cause: e
})
)
}

export function getCosmosChainBalances({
url,
walletAddress
}: { url: string; walletAddress: string }) {
let json: undefined | unknown

try {
url = url.startsWith("https") ? url : `https://${url}`
const response = await fetch(`${url}/cosmos/bank/v1beta1/balances/${walletAddress}`)
if (!response.ok) raise("invalid response")

json = await response.json()
} catch (error) {
if (error instanceof Error) {
raise(`error fetching balances from /cosmos/bank: ${error.message}`)
}
raise(`unknown error while fetching from /cosmos/bank: ${JSON.stringify(error)}`)
}

const result = v.safeParse(cosmosBalancesResponseSchema, json)

if (!result.success) raise(`error parsing result ${JSON.stringify(result.issues)}`)
return result.output.balances.map(x => ({
address: x.denom,
symbol: x.denom,
balance: BigInt(x.amount),
decimals: 0
}))
}: { url: string; walletAddress: string }): ResultAsync<RawBalances, Error> {
url = url.startsWith("https") ? url : `https://${url}`
if (!isValidBech32Address(walletAddress))
return errAsync(new Error(`invalid cosmos wallet address provided: ${walletAddress}`))
return fetchJson(`${url}/cosmos/bank/v1beta1/balances/${walletAddress}`)
.andThen(json => {
const result = v.safeParse(cosmosBalancesResponseSchema, json)
return result.success
? ok(result.output)
: err(new Error("Validation failed:", { cause: result.issues }))
})
.map(balances =>
balances.balances.reduce((acc, cur) => {
acc[toHex(cur.denom)] = cur.amount
return acc
}, {})
)
}
5 changes: 4 additions & 1 deletion app/src/lib/queries/balance/evm/multicall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { raise } from "$lib/utilities/index.ts"
import { config } from "$lib/wallet/evm/config.ts"
import { erc20Abi, getAddress, type Address } from "viem"
import type { NoRepetition } from "$lib/utilities/types.ts"
import { ResultAsync } from "neverthrow"

/**
* @example
Expand Down Expand Up @@ -54,7 +55,9 @@ export async function erc20ReadMulticall({
const currentResult = accumulator.at(-1)
const fn = functionNames[index % functionNames.length]
if (!currentResult) return accumulator
currentResult[fn === "balanceOf" ? "balance" : fn] = result ?? (fn === "decimals" ? 0 : "")
if (result !== undefined) {
currentResult[fn === "balanceOf" ? "balance" : fn] = result ?? (fn === "decimals" ? 0 : "")
}
return accumulator
},
[] as Array<Record<string, any>>
Expand Down
Loading
Loading