Skip to content

Commit

Permalink
Fix display and ui optimize
Browse files Browse the repository at this point in the history
  • Loading branch information
schnetzlerjoe committed Sep 11, 2023
1 parent cd582a9 commit a2659c4
Show file tree
Hide file tree
Showing 14 changed files with 286 additions and 116 deletions.
11 changes: 11 additions & 0 deletions .gitpod.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# This configuration file was automatically generated by Gitpod.
# Please adjust to your needs (see https://www.gitpod.io/docs/introduction/learn-gitpod/gitpod-yaml)
# and commit this file to your remote git repository to share the goodness with others.

# Learn more from ready-to-use templates: https://www.gitpod.io/docs/introduction/getting-started/quickstart

tasks:
- init: yarn install && yarn run build
command: yarn run start


2 changes: 1 addition & 1 deletion packages/snap/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cosmsnap/snap",
"version": "0.1.12",
"version": "0.1.13",
"description": "The Cosmos extension for your Metamask wallet.",
"repository": {
"type": "git",
Expand Down
4 changes: 2 additions & 2 deletions packages/snap/snap.manifest.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
{
"version": "0.1.12",
"version": "0.1.13",
"description": "Cosmos Extension that adds Cosmos support to Metamask.",
"proposedName": "Cosmos Extension",
"repository": {
"type": "git",
"url": "https://github.com/cosmos/snap.git"
},
"source": {
"shasum": "mjWxRVx7VvVyf7FsGBLI0orobQyZhLK4x+vUbu/HqM0=",
"shasum": "Wb57UIJWIkWoPgwIfeb9OabgrNESQc9nufrAqJo+Mtk=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
2 changes: 1 addition & 1 deletion packages/snap/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,7 @@ export const onRpcRequest: OnRpcRequestHandler = async ({
heading("Confirm Chain Addition"),
divider(),
heading("Chain Info"),
text(`${new_chain}`),
text(`${JSON.stringify(new_chain, null, 4)}`),
]),
},
});
Expand Down
35 changes: 24 additions & 11 deletions packages/ui/src/components/AddChain.svelte
Original file line number Diff line number Diff line change
@@ -1,14 +1,27 @@
<script>
<script lang="ts">
import { JSONEditor, Mode } from 'svelte-jsoneditor';
import { state } from '../store/state';
import { ADD_CHAIN_EXAMPLE } from '../utils/constants';
import type { ChainInfo } from '@keplr-wallet/types';
import { validateChainInfo } from '../utils/general';
export let edit = false;
export let chainInfo = {};
let content = { json: {} };
$: {
content = {
json: chainInfo
export let chainInfo: ChainInfo = ADD_CHAIN_EXAMPLE;
let content = { text: undefined, json: chainInfo as any };
const addChain = async () => {
let good = validateChainInfo(chainInfo);
if (!good) {
$state.alertType = "danger";
$state.alertText = "Chain info is not supplied properly.";
$state.showAlert = true;
throw new Error("Chain info is not supplied properly.")
}
await window.cosmos.experimentalSuggestChain(chainInfo);
}
function handleChange(updatedContent: any, previousContent: any, { contentErrors, patchResult }: any) {
content = updatedContent;
chainInfo = updatedContent.json;
}
</script>

Expand All @@ -18,7 +31,7 @@
<div class="group-4446">
<div class="group-4444">
<div class="add-new-chain-1 inter-bold-white-20px">
{edit ? "Edit chain" : "Add new chain"}
Add new chain
</div>
<!-- svelte-ignore a11y-click-events-have-key-events -->
<img on:click={() => $state.openAddChainPopup = false} class="clear" src="https://anima-uploads.s3.amazonaws.com/projects/64863aebc1255e7dd4fb600b/releases/64ef9c2985c1bf1a9cb5beba/img/[email protected]" alt="clear">
Expand All @@ -28,11 +41,11 @@
<div class="group-4447">
<div class="group-4445">
<div class="overlap-group jse-theme-dark">
<JSONEditor content={content} mainMenuBar={false} navigationBar={false} statusBar={false} mode={Mode.text}/>
<JSONEditor onChange="{handleChange}" content={content} mainMenuBar={false} navigationBar={false} statusBar={false} mode={Mode.tree}/>
</div>
</div>
<button class="frame-1-2 create-new-chain inter-medium-white-12px">
{edit ? "Save chain edits" : "Create new chain"}
<button on:click={addChain} class="frame-1-2 create-new-chain inter-medium-white-12px">
Add Chain
</button>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/src/components/Balance.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
${_.round(dollarAmount, 2)}
</p>
<p class="percent inter-medium-white-14px w-[150px]">
{_.round(tokenAmount, 2) + " " + tokenDenom.substring(1).toUpperCase()}
{_.round(tokenAmount, 2) + " " + tokenDenom}
</p>
</div>
</div>
Expand Down
129 changes: 74 additions & 55 deletions packages/ui/src/components/Transfer.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,82 +4,101 @@
import { balances } from "../store/balances";
import { getSkipRecommendation, getMsgs, type CoinIBC } from '../utils/ibc';
import { state } from "../store/state";
import type { Coin } from "@cosmjs/stargate";
import type { Msg } from "@cosmsnap/snapper";
import _ from 'lodash';
import { makeCoinPresentable } from "../utils/general";
let source = "cosmoshub-4";
let destination = "cosmoshub-4";
let denom = "uatom";
let available: Coin = {amount: "0", denom};
let selected: CoinIBC = {amount: "0", denom: "uatom", ibc: false, display: "uatom".substring(1).toUpperCase()};
let amount = 0;
let noRoute = false;
let recipient = "";
let slippage = "1";
let sourceBalances: CoinIBC[] = [];
let defaultSourceAsset: string = "";
let setInitial = false;
$: {
if ($balances) {
let source_chain = $balances.filter(item => item.chain_id == source)[0];
if (source_chain) {
sourceBalances = source_chain.balances;
defaultSourceAsset = source_chain.balances[0].ibc ? source_chain.balances[0].ibc_denom! : source_chain.balances[0].denom;
if (!setInitial) {
selected = sourceBalances[0];
setInitial = true;
}
}
}
}
const computeIBCRoute = async () => {
noRoute = false;
if (source != destination) {
try {
let skipRec = await getSkipRecommendation(denom, source, destination);
if (skipRec.recommendations.length == 0) {
noRoute = true;
throw new Error("No recommended asset found.");
}
let msg = await getMsgs(source, denom, destination, skipRec.recommendations[0].asset.denom, (amount*1000000).toString(), slippage, $chains);
let fees = {
amount: [
{
amount: "100000",
denom: "uosmo"
}
],
gas: "300000",
}
let messages: Msg[] = msg.msgs.map(item => {
let msgCamel: any = _.mapKeys(JSON.parse(item.msg), (value: any, key: any) => _.camelCase(key));
return {
value: msgCamel,
typeUrl: item.msg_type_url
}
});
await window.cosmos.signAndBroadcast(source, messages, fees);
} catch (error: any) {
console.log(error);
noRoute = true;
$state.alertType = "danger";
$state.showAlert = true;
$state.alertText = `Error Occured Finding Route: ${error.message}`
const setSelected = async (e: Event) => {
const target = e.target as HTMLSelectElement;
if (sourceBalances) {
let find = sourceBalances.find(item => item.denom.toUpperCase() == target.value.toUpperCase());
if (find) {
selected = find
}
}
}
$: {
let filtBal = $balances.filter(item => item.chain_id == source);
if (filtBal.length > 0) {
let filtTokens = filtBal[0].balances.filter(item => item.denom == denom);
if (filtTokens.length > 0) {
available = makeCoinPresentable(filtTokens[0])
} else {
available = makeCoinPresentable({ amount: "0", denom, ibc: false });
}
} else {
available = makeCoinPresentable({ amount: "0", denom, ibc: false });
const computeIBCRoute = async () => {
noRoute = false;
if (source === destination) {
return;
}
}
try {
const skipRec = await getSkipRecommendation(selected.denom, source, destination);
if (!Array.isArray(skipRec.recommendations) || skipRec.recommendations.length === 0) {
throw new Error("No recommended asset found.");
}
const firstRec = skipRec.recommendations[0].asset;
if (!firstRec || !firstRec.denom) {
throw new Error("Invalid recommendation data.");
}
const adjustedAmount = (amount * 1000000).toString();
const msg = await getMsgs(source, selected.denom, destination, firstRec.denom, adjustedAmount, slippage, $chains);
if (!Array.isArray(msg.msgs)) {
throw new Error("Invalid message data.");
}
const fees = {
amount: [
{
amount: "100000",
denom: "uosmo"
}
],
gas: "300000",
};
const messages: Msg[] = msg.msgs.map(item => {
if (!item.msg || !item.msg_type_url) {
throw new Error("Invalid message format.");
}
const msgCamel = _.mapKeys(JSON.parse(item.msg), (value: any, key: any) => _.camelCase(key));
return {
value: msgCamel,
typeUrl: item.msg_type_url
};
});
await window.cosmos.signAndBroadcast(source, messages, fees);
} catch (error: any) {
console.error(error);
$state.alertType = "danger";
$state.showAlert = true;
$state.alertText = `Error Occurred Finding Route: ${error.message}`;
}
};
</script>

<div class="overlap-group1">
Expand All @@ -100,9 +119,9 @@
<div class="percent inter-medium-white-14px">
Asset
</div>
<select bind:value={defaultSourceAsset} id="denom" name="denom" class="group-32-1 source-chain-osmosis inter-medium-white-14px">
<select on:change={async e => { await setSelected(e) }} id="denom" name="denom" class="group-32-1 source-chain-osmosis inter-medium-white-14px">
{#each sourceBalances as balance}
<option class="source-chain-osmosis inter-medium-white-14px" value={balance.ibc ? balance.ibc_denom : balance.denom}>{makeCoinPresentable(balance).denom}</option>
<option class="source-chain-osmosis inter-medium-white-14px" value={balance.ibc ? balance.ibc_denom : balance.denom}>{balance.display}</option>
{/each}
</select>
</div>
Expand All @@ -125,8 +144,8 @@
</div>
<input bind:value={recipient} type="text" placeholder="Enter recipient address" class="enter-amount inter-medium-white-14px overlap-group-7"/>
<!-- svelte-ignore a11y-click-events-have-key-events -->
<div on:click={() => { amount = _.round((Number(available.amount) / 1000000)) }} class="available-balance-1454789 inter-medium-blueberry-14px cursor-pointer">
Available: {_.round((Number(available.amount) / 1000000))} {available.denom.substring(1).toUpperCase()}
<div on:click={() => { amount = _.round((Number(selected.amount) / 1000000)) }} class="available-balance-1454789 inter-medium-blueberry-14px cursor-pointer">
Available: {_.round((Number(selected.amount) / 1000000))} {selected.display}
</div>
<button on:click={computeIBCRoute} class="frame-1-2 frame-1-4 button-send">
<div class="send-amount-1 inter-medium-white-12px">
Expand Down
16 changes: 12 additions & 4 deletions packages/ui/src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,24 @@
import { state } from '../store/state';
import { goto } from '$app/navigation';
import { LOCAL_STORAGE_CHAINS } from '../utils/general';
import { chains } from '../store/chains';
let loading = true;
let isMetaMaskInstalledValue: boolean = false;
let isSnapInstalledValue: boolean = false;
let isSnapInitValue: boolean = false;
const runInstallSnap = async () => {
await installSnap();
isSnapInstalledValue = true;
await initializeSnap();
}
const initializeSnap = async () => {
let chains = await initSnap();
if (chains) {
localStorage.setItem(LOCAL_STORAGE_CHAINS, JSON.stringify(chains))
let chainsFromInit = await initSnap();
if (chainsFromInit) {
localStorage.setItem(LOCAL_STORAGE_CHAINS, JSON.stringify(chainsFromInit))
chains.set(chainsFromInit);
}
isSnapInitValue = true;
$state.connected = true;
Expand Down Expand Up @@ -75,7 +83,7 @@

<Step
disabled={!isMetaMaskInstalledValue || isSnapInstalledValue}
action={async () => { await installSnap(); isSnapInstalledValue = true; }}
action={runInstallSnap}
complete={isSnapInstalledValue}
stepNumber="2"
stepTitle="Install Cosmos Snap"
Expand Down
15 changes: 14 additions & 1 deletion packages/ui/src/routes/api/balances/+server.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import { json } from '@sveltejs/kit';
import { getDenomFromIBC } from '../../../utils/ibc.js';

const getDenomFromIBC = async (/** @type {string | import("@cosmjs/stargate").HttpEndpoint} */ url, /** @type {import("@cosmjs/stargate").Coin} */ ibc_coin) => {
let splits = ibc_coin.denom.toUpperCase().split("IBC/");
if (splits.length > 1) {
let hash = splits[1];
let res = await fetch(`${url}/ibc/apps/transfer/v1/denom_traces/${hash}`);
let data = await res.json();
return {
denom: data.denom_trace.base_denom,
amount: ibc_coin.amount
}
}
return ibc_coin
}

export async function POST({ request }) {

Expand Down
Loading

0 comments on commit a2659c4

Please sign in to comment.