Skip to content

Commit

Permalink
style: linted
Browse files Browse the repository at this point in the history
  • Loading branch information
dafuga committed Sep 15, 2023
1 parent 8ada6ba commit 928e132
Show file tree
Hide file tree
Showing 15 changed files with 279 additions and 189 deletions.
2 changes: 1 addition & 1 deletion src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {storeAccount} from './stores/account-provider'
import {getClient} from './api-client'
import {appId, chains} from './config'
import {activeEvmSession, activeSession, availableSessions} from './store'
import { startEvmSession } from './lib/evm'
import {startEvmSession} from './lib/evm'

const transport = new Transport({
requestStatus: false,
Expand Down
2 changes: 0 additions & 2 deletions src/components/elements/form/transaction.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@
},
clear: () => {
error = false
console.log('clearing')
transaction_id.set(undefined)
},
retryTransaction: () => {
Expand All @@ -73,7 +72,6 @@
}
},
setTransaction: (id: string) => {
console.log('setting')
transaction_id.set(id)
},
setTransactionError: (err: any) => {
Expand Down
64 changes: 39 additions & 25 deletions src/lib/evm.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { wait } from "~/helpers"
import { get } from "svelte/store"
import { activeBlockchain, activeEvmSession, activeSession } from "~/store"
import {get} from 'svelte/store'
import BN from 'bn.js'
import {activeBlockchain, activeEvmSession, activeSession} from '~/store'
import {wait} from '~/helpers'

import { Asset, Int16, Int64, Name, NameType } from "anchor-link";
import { BigNumber, ethers } from "ethers";
import { getClient } from "~/api-client";
import {Asset, Name, NameType} from 'anchor-link'
import {BigNumber, ethers} from 'ethers'
import {getClient} from '~/api-client'

export type AvailableEvms = 'eos-mainnet' | 'telos'
export interface EvmChainConfig {
Expand All @@ -24,41 +25,45 @@ declare global {
}

export const evmChainConfigs: {[key: string]: EvmChainConfig} = {
'eos': {
eos: {
chainId: '0x4571',
chainName: 'EOS EVM Network',
nativeCurrency: {name: 'EOS', symbol: '4,EOS', decimals: 18},
rpcUrls: ['https://api.evm.eosnetwork.com/'],
blockExplorerUrls: ['https://explorer.evm.eosnetwork.com'],
},
'telos': {
telos: {
chainId: '0x4571',
chainName: 'EOS EVM Network',
nativeCurrency: {name: 'TLOS', symbol: '4,TLOS', decimals: 18},
rpcUrls: ['https://api.evm.eosnetwork.com/'],
blockExplorerUrls: ['https://explorer.evm.eosnetwork.com'],
}
},
}

export interface EvmSessionParams {
signer: ethers.providers.JsonRpcSigner
address: string
chainName: string
nativeAccountName?: NameType
}

export interface EvmSessionFromParams {
chainName: string
nativeAccountName?: NameType
}

export class EvmSession {
address: string
signer: ethers.providers.JsonRpcSigner
chainName: string
nativeAccountName?: NameType

constructor({address, signer, chainName}: EvmSessionParams) {
constructor({address, signer, chainName, nativeAccountName}: EvmSessionParams) {
this.address = address
this.signer = signer
this.chainName = chainName
this.nativeAccountName = nativeAccountName
}

get checksumAddress() {
Expand All @@ -69,24 +74,25 @@ export class EvmSession {
return evmChainConfigs[this.chainName]
}

static async from({ chainName }: EvmSessionFromParams) {
static async from({chainName, nativeAccountName}: EvmSessionFromParams) {
if (window.ethereum) {
const provider = getProvider()
let networkId = await provider.getNetwork()
if (networkId.chainId !== 17777) {
await switchNetwork(chainName)
networkId = await provider.getNetwork()
}

await window.ethereum.request({method: 'eth_requestAccounts'})
const signer = provider.getSigner()

await window.ethereum.get_currency_balance

return new EvmSession({
address: await signer.getAddress(),
signer,
chainName,
nativeAccountName,
})
} else {
throw new Error('You need to install Metamask in order to use this feature.')
Expand All @@ -110,15 +116,22 @@ export class EvmSession {
}

async getTelosEvmBalance() {
const account = await getTelosEvmAccount(this.address)
if (!this.nativeAccountName) {
throw new Error('Native account name is necessary to fetch Telos balance.')
}

const account = await getTelosEvmAccount(this.nativeAccountName)

if (!account) {
return Asset.from(0, this.chainConfig.nativeCurrency.symbol)
}

const bn = BigNumber.from(`0x${account.balance}`)

return Asset.from(Number(ethers.utils.formatEther(bn)), this.chainConfig.nativeCurrency.symbol)
return Asset.from(
Number(ethers.utils.formatEther(bn)),
this.chainConfig.nativeCurrency.symbol
)
}
}

Expand All @@ -130,13 +143,13 @@ export async function getTelosEvmAccount(nativeAccountName: NameType) {
throw new Error('API client could not be instantiated')
}

const { rows } = await client.v1.chain.get_table_rows({
const {rows} = await client.v1.chain.get_table_rows({
code: 'eosio.evm',
scope: 'eosio.evm',
table: 'account',
index_position: 'tertiary',
lower_bound: Name.from('gm3timrygqge'),
upper_bound: Name.from('gm3timrygqge'),
lower_bound: Name.from(nativeAccountName),
upper_bound: Name.from(nativeAccountName),
})

return rows[0]
Expand Down Expand Up @@ -179,9 +192,7 @@ export async function switchNetwork(chainName: string) {
if (e.code === 4902) {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [
evmNodeConfig
],
params: [evmNodeConfig],
})
}
})
Expand Down Expand Up @@ -239,7 +250,6 @@ function uint64ToAddr(str: string) {
return '0xbbbbbbbbbbbbbbbbbbbbbbbb' + str
}


let connectingToEvm = false

export async function startEvmSession(): Promise<EvmSession | undefined> {
Expand All @@ -249,13 +259,17 @@ export async function startEvmSession(): Promise<EvmSession | undefined> {
await wait(5000)
return startEvmSession()
}

connectingToEvm = true

const blockchain = get(activeBlockchain)
const nativeSession = get(activeSession)

try {
evmSession = await EvmSession.from({ chainName: blockchain.id })
evmSession = await EvmSession.from({
chainName: blockchain.id,
nativeAccountName: nativeSession?.auth.actor,
})
} catch (e) {
if (e.code === -32002) {
await wait(5000)
Expand Down
6 changes: 3 additions & 3 deletions src/pages/transfer/confirm.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@
{depositAmount}
</div>
<div class="fiat-value">
{depositAmountInUsd ? `~ ${depositAmountInUsd}`: ''}
{depositAmountInUsd ? `~ ${depositAmountInUsd}` : ''}
</div>
</td>
</tr>
Expand All @@ -167,7 +167,7 @@
{feeAmount || `0.0000 ${$systemTokenKey}`}
</div>
<div class="fiat-value">
{feeAmountInUsd ? `~ ${feeAmountInUsd}`: ''}
{feeAmountInUsd ? `~ ${feeAmountInUsd}` : ''}
</div>
</td>
</tr>
Expand All @@ -181,7 +181,7 @@
{receivedAmount}
</div>
<div class="fiat-value">
{receivedAmountInUsd ? `~ ${receivedAmountInUsd}`: ''}
{receivedAmountInUsd ? `~ ${receivedAmountInUsd}` : ''}
</div>
</td>
</tr>
Expand Down
74 changes: 42 additions & 32 deletions src/pages/transfer/form.svelte
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
<script lang="ts">
import {Asset as CoreAsset} from '@greymass/eosio'
import {activeEvmSession, activeSession, activeBlockchain} from '~/store'
import {activeEvmSession, activeSession, activeBlockchain, currentAccountBalance} from '~/store'
import {Token, systemToken} from '~/stores/tokens'
import Label from '~/components/elements/input/label.svelte'
import Form from '~/components/elements/form.svelte'
import Button from '~/components/elements/button.svelte'
import Asset from '~/components/elements/input/asset.svelte'
import Selector from '~/components/elements/input/token/selector.svelte'
import type { TransferManager } from './managers/transferManager'
import { transferManagers } from './managers'
import type { EvmSession } from '~/lib/evm'
import type {TransferManager} from './managers/transferManager'
import {transferManagers} from './managers'
import type {EvmSession} from '~/lib/evm'
export let handleContinue: () => void
export let amount: string = ''
Expand Down Expand Up @@ -69,30 +69,31 @@
fromOptions = []
await Promise.all(Object.values(transferManagers).map(async TransferManagerClass => {
if (!$systemToken) return
await Promise.all(
Object.values(transferManagers).map(async (TransferManagerClass) => {
if (!$systemToken) return
// Only displaying accounts that support the current chain
if (!TransferManagerClass.supportedChains.includes($activeBlockchain?.id)) return
// Only displaying accounts that support the current chain
if (!TransferManagerClass.supportedChains.includes($activeBlockchain?.id)) return
let accountBalance
let accountBalance
if (!TransferManagerClass.evmRequired || evmSession) {
const transferManager = new (TransferManagerClass as unknown as new (...args: any[]) => TransferManager)(
$activeSession!,
evmSession
)
await transferManager.updateMainBalance()
accountBalance = await transferManager.balance()
}
if (!TransferManagerClass.evmRequired || evmSession) {
const transferManager = new (TransferManagerClass as unknown as new (
...args: any[]
) => TransferManager)($activeSession!, evmSession)
await transferManager.updateMainBalance()
accountBalance = await transferManager.balance()
}
fromOptions.push({
...$systemToken,
key: TransferManagerClass.from,
name: TransferManagerClass.fromDisplayString,
balance: accountBalance || 'Connect',
fromOptions.push({
...$systemToken,
key: TransferManagerClass.from,
name: TransferManagerClass.fromDisplayString,
balance: accountBalance || 'Connect',
})
})
}))
)
toOptions = fromOptions
Expand All @@ -101,13 +102,23 @@
$: {
if (from) {
toOptions = fromOptions.filter(token => token.key !== from?.key)
toOptions = fromOptions.filter((token) => token.key !== from?.key)
} else {
toOptions = fromOptions
}
}
const initialBalanceValue = $currentAccountBalance?.value
$: {
// Regenerate options if the balance changes
if ($activeEvmSession && initialBalanceValue !== $currentAccountBalance?.value) {
generateOptions($activeEvmSession)
}
}
$: {
// Regenerate options if the user connects to evm wallet
if ($activeEvmSession) {
generateOptions($activeEvmSession)
} else {
Expand All @@ -116,8 +127,11 @@
}
$: {
transferManager?.balance().then(balance => {
availableToReceive = CoreAsset.from((balance?.value || 0) - (feeAmount?.value || 0), balance?.symbol || "4,EOS")
transferManager?.balance().then((balance) => {
availableToReceive = CoreAsset.from(
(balance?.value || 0) - (feeAmount?.value || 0),
balance?.symbol || '4,EOS'
)
})
}
Expand Down Expand Up @@ -160,7 +174,7 @@
padding: 20px;
min-height: 220px;
button {
button {
cursor: pointer;
color: var(--main-blue);
font-size: 0.7em;
Expand Down Expand Up @@ -232,11 +246,7 @@
bind:value={amount}
/>
{#if from && to}
<button
type="button"
on:click={useEntireBalance}
on:keyup={() => {}}
>
<button type="button" on:click={useEntireBalance} on:keyup={() => {}}>
Entire Balance
</button>
{/if}
Expand Down
Loading

0 comments on commit 928e132

Please sign in to comment.