add native token + internal transfers
This commit is contained in:
@@ -5,6 +5,7 @@ import {
|
||||
Updater,
|
||||
defineElectrobunRPC,
|
||||
type RPCSchema,
|
||||
Utils,
|
||||
} from 'electrobun/bun'
|
||||
|
||||
const DEV_SERVER_PORT = 5173
|
||||
@@ -57,20 +58,17 @@ const url = await getMainViewUrl()
|
||||
|
||||
const ETHERSCAN_API = 'https://api.etherscan.io/v2/api'
|
||||
|
||||
type EtherscanTx = {
|
||||
blockNumber: string
|
||||
timeStamp: string
|
||||
type TxEntry = {
|
||||
hash: string
|
||||
timeStamp: string
|
||||
from: string
|
||||
to: string
|
||||
value: string
|
||||
gas: string
|
||||
gasPrice: string
|
||||
isError: string
|
||||
txreceipt_status: string
|
||||
input: string
|
||||
contractAddress: string
|
||||
gasUsed: string
|
||||
isError?: string
|
||||
tokenSymbol?: string
|
||||
tokenName?: string
|
||||
tokenDecimal?: string
|
||||
contractAddress?: string
|
||||
}
|
||||
|
||||
type RPC = {
|
||||
@@ -98,7 +96,13 @@ type RPC = {
|
||||
page?: number
|
||||
offset?: number
|
||||
}
|
||||
response: Promise<EtherscanTx[]>
|
||||
response: Promise<TxEntry[]>
|
||||
}
|
||||
openExternal: {
|
||||
params: {
|
||||
url: string
|
||||
}
|
||||
response: Promise<void>
|
||||
}
|
||||
}
|
||||
messages: {}
|
||||
@@ -108,8 +112,34 @@ type RPC = {
|
||||
messages: {}
|
||||
}>
|
||||
}
|
||||
|
||||
async function fetchEtherscan(
|
||||
key: string,
|
||||
chainid: string,
|
||||
action: string,
|
||||
address: string,
|
||||
page: number,
|
||||
offset: number,
|
||||
): Promise<any[]> {
|
||||
const params = new URLSearchParams({
|
||||
module: 'account',
|
||||
action,
|
||||
address,
|
||||
page: String(page),
|
||||
offset: String(offset),
|
||||
sort: 'desc',
|
||||
apikey: key,
|
||||
chainid,
|
||||
})
|
||||
const res = await fetch(`${ETHERSCAN_API}?${params}`)
|
||||
const data = await res.json()
|
||||
console.log(data)
|
||||
if (data.status !== '1') return []
|
||||
return data.result
|
||||
}
|
||||
|
||||
const rpc = BrowserView.defineRPC<RPC>({
|
||||
maxRequestTime: 10000,
|
||||
maxRequestTime: 20000,
|
||||
handlers: {
|
||||
requests: {
|
||||
getSecret: async ({ name, service }) => {
|
||||
@@ -118,38 +148,67 @@ const rpc = BrowserView.defineRPC<RPC>({
|
||||
setSecret: async ({ name, service, value }) => {
|
||||
await Bun.secrets.set({ name, service, value })
|
||||
},
|
||||
openExternal: async ({ url }) => {
|
||||
Utils.openExternal(url)
|
||||
},
|
||||
fetchTxHistory: async ({
|
||||
address,
|
||||
chainid,
|
||||
page = 1,
|
||||
offset = 20,
|
||||
offset = 1000,
|
||||
}) => {
|
||||
const key = await Bun.secrets.get({
|
||||
service: 'koins',
|
||||
name: 'etherscan_key',
|
||||
})
|
||||
if (!key) return []
|
||||
const params = new URLSearchParams({
|
||||
module: 'account',
|
||||
action: 'txlist',
|
||||
address,
|
||||
page: String(page),
|
||||
offset: String(offset),
|
||||
sort: 'desc',
|
||||
apikey: key,
|
||||
chainid,
|
||||
})
|
||||
try {
|
||||
const url = `${ETHERSCAN_API}?${params}`
|
||||
const res = await fetch(url)
|
||||
const data = await res.json()
|
||||
console.log(data)
|
||||
if (data.status !== '1') return []
|
||||
return data.result as EtherscanTx[]
|
||||
} catch (error) {
|
||||
console.log(error)
|
||||
return []
|
||||
}
|
||||
|
||||
const [nativeTxs, tokenTxs] = await Promise.all([
|
||||
fetchEtherscan(
|
||||
key,
|
||||
chainid,
|
||||
'txlist',
|
||||
address,
|
||||
page,
|
||||
offset,
|
||||
),
|
||||
fetchEtherscan(
|
||||
key,
|
||||
chainid,
|
||||
'tokentx',
|
||||
address,
|
||||
page,
|
||||
offset,
|
||||
),
|
||||
])
|
||||
|
||||
const combined: TxEntry[] = [
|
||||
...nativeTxs.map((t: any) => ({
|
||||
hash: t.hash,
|
||||
timeStamp: t.timeStamp,
|
||||
from: t.from,
|
||||
to: t.to,
|
||||
value: t.value,
|
||||
isError: t.isError,
|
||||
})),
|
||||
...tokenTxs.map((t: any) => ({
|
||||
hash: t.hash,
|
||||
timeStamp: t.timeStamp,
|
||||
from: t.from,
|
||||
to: t.to,
|
||||
value: t.value,
|
||||
tokenSymbol: t.tokenSymbol,
|
||||
tokenName: t.tokenName,
|
||||
tokenDecimal: t.tokenDecimal,
|
||||
contractAddress: t.contractAddress,
|
||||
})),
|
||||
]
|
||||
|
||||
combined.sort(
|
||||
(a, b) => Number(b.timeStamp) - Number(a.timeStamp),
|
||||
)
|
||||
|
||||
return combined
|
||||
},
|
||||
},
|
||||
messages: {},
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
import { Electroview } from 'electrobun/view'
|
||||
|
||||
export type EtherscanTx = {
|
||||
blockNumber: string
|
||||
timeStamp: string
|
||||
export type TxEntry = {
|
||||
hash: string
|
||||
timeStamp: string
|
||||
from: string
|
||||
to: string
|
||||
value: string
|
||||
isError: string
|
||||
txreceipt_status: string
|
||||
gas: string
|
||||
gasPrice: string
|
||||
input: string
|
||||
contractAddress: string
|
||||
gasUsed: string
|
||||
isError?: string
|
||||
tokenSymbol?: string
|
||||
tokenName?: string
|
||||
tokenDecimal?: string
|
||||
contractAddress?: string
|
||||
}
|
||||
|
||||
type RPC = {
|
||||
@@ -41,7 +38,13 @@ type RPC = {
|
||||
page?: number
|
||||
offset?: number
|
||||
}
|
||||
response: Promise<EtherscanTx[]>
|
||||
response: Promise<TxEntry[]>
|
||||
}
|
||||
openExternal: {
|
||||
params: {
|
||||
url: string
|
||||
}
|
||||
response: Promise<void>
|
||||
}
|
||||
}
|
||||
messages: {}
|
||||
|
||||
@@ -5,12 +5,20 @@ import {
|
||||
formatUnits,
|
||||
Contract,
|
||||
} from 'ethers'
|
||||
import { electrobun, type EtherscanTx } from '$lib/electrobun'
|
||||
import { electrobun, type TxEntry } from '$lib/electrobun'
|
||||
|
||||
const ERC20_ABI = [
|
||||
'function balanceOf(address) view returns (uint256)',
|
||||
'function symbol() view returns (string)',
|
||||
'function decimals() view returns (uint8)',
|
||||
]
|
||||
|
||||
type DiscoveredToken = {
|
||||
address: string
|
||||
symbol: string
|
||||
decimals: number
|
||||
}
|
||||
|
||||
export const networks = [
|
||||
{
|
||||
id: 'bsc',
|
||||
@@ -35,7 +43,7 @@ export const networks = [
|
||||
{
|
||||
id: 'polygon',
|
||||
name: 'Polygon',
|
||||
rpc: 'https://polygon.drpc.org',
|
||||
rpc: 'https://polygon-bor.publicnode.com',
|
||||
symbol: 'POL',
|
||||
chainid: '137',
|
||||
explorerUrl: 'https://polygonscan.com/tx/',
|
||||
@@ -94,7 +102,8 @@ export const Wallet = () => {
|
||||
let vaultExists = $state(false)
|
||||
let ready = $state(false)
|
||||
let etherscanKey = $state('')
|
||||
let transactions = $state<EtherscanTx[]>([])
|
||||
let transactions = $state<TxEntry[]>([])
|
||||
let discoveredTokens = $state<DiscoveredToken[]>([])
|
||||
|
||||
const net = () => networks.find((n) => n.id === network)!
|
||||
|
||||
@@ -125,6 +134,7 @@ export const Wallet = () => {
|
||||
|
||||
const switchNetwork = async (id: NetworkId) => {
|
||||
network = id
|
||||
discoveredTokens = []
|
||||
if (seed) await refresh()
|
||||
}
|
||||
|
||||
@@ -155,6 +165,7 @@ export const Wallet = () => {
|
||||
error = ''
|
||||
tokenBalances = []
|
||||
transactions = []
|
||||
discoveredTokens = []
|
||||
}
|
||||
|
||||
const refresh = async () => {
|
||||
@@ -180,6 +191,18 @@ export const Wallet = () => {
|
||||
return { symbol: t.symbol, balance: '0' }
|
||||
}
|
||||
}),
|
||||
...discoveredTokens.map(async (t) => {
|
||||
try {
|
||||
const c = new Contract(t.address, ERC20_ABI, provider)
|
||||
const bal = await c.balanceOf(wallet.address)
|
||||
return {
|
||||
symbol: t.symbol,
|
||||
balance: formatUnits(bal, t.decimals),
|
||||
}
|
||||
} catch {
|
||||
return { symbol: t.symbol, balance: '0' }
|
||||
}
|
||||
}),
|
||||
])
|
||||
balance = formatEther(nativeBal)
|
||||
tokenBalances = tokenBals
|
||||
@@ -212,6 +235,68 @@ export const Wallet = () => {
|
||||
chainid: net().chainid,
|
||||
})
|
||||
transactions = txs ?? []
|
||||
|
||||
const seen = new Set(
|
||||
net().tokens.map((t) => t.address.toLowerCase()),
|
||||
)
|
||||
discoveredTokens.forEach((d) => seen.add(d.address.toLowerCase()))
|
||||
|
||||
const newAddrs = [
|
||||
...new Set(
|
||||
(txs ?? [])
|
||||
.filter(
|
||||
(t) =>
|
||||
t.contractAddress &&
|
||||
!seen.has(t.contractAddress.toLowerCase()),
|
||||
)
|
||||
.map((t) => t.contractAddress!.toLowerCase()),
|
||||
),
|
||||
]
|
||||
if (newAddrs.length === 0) return
|
||||
|
||||
const provider = new JsonRpcProvider(net().rpc)
|
||||
const newTokens: DiscoveredToken[] = []
|
||||
|
||||
for (const addr of newAddrs) {
|
||||
try {
|
||||
const c = new Contract(addr, ERC20_ABI, provider)
|
||||
const [symbol, decimals] = await Promise.all([
|
||||
c.symbol(),
|
||||
c.decimals(),
|
||||
])
|
||||
if (
|
||||
typeof symbol !== 'string' ||
|
||||
symbol.length > 12 ||
|
||||
/[\s.:/]/.test(symbol)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
newTokens.push({ address: addr, symbol, decimals })
|
||||
} catch {
|
||||
// not ERC-20, skip
|
||||
}
|
||||
}
|
||||
|
||||
console.log(newTokens)
|
||||
|
||||
if (newTokens.length > 0) {
|
||||
discoveredTokens = [...discoveredTokens, ...newTokens]
|
||||
const newBals = await Promise.all(
|
||||
newTokens.map(async (t) => {
|
||||
try {
|
||||
const c = new Contract(t.address, ERC20_ABI, provider)
|
||||
const bal = await c.balanceOf(address)
|
||||
return {
|
||||
symbol: t.symbol,
|
||||
balance: formatUnits(bal, t.decimals),
|
||||
}
|
||||
} catch {
|
||||
return { symbol: t.symbol, balance: '0' }
|
||||
}
|
||||
}),
|
||||
)
|
||||
tokenBalances = [...tokenBalances, ...newBals]
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -269,6 +354,9 @@ export const Wallet = () => {
|
||||
get transactions() {
|
||||
return transactions
|
||||
},
|
||||
get discoveredTokens() {
|
||||
return discoveredTokens
|
||||
},
|
||||
refresh,
|
||||
init,
|
||||
lock,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { electrobun } from '$lib/electrobun.js'
|
||||
import { Wallet } from '$lib/states/wallet.svelte.js'
|
||||
import { Button } from '$lib/components/ui/button/index.js'
|
||||
import { Textarea } from '$lib/components/ui/textarea/index.js'
|
||||
@@ -9,7 +10,7 @@
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '$lib/components/ui/card/index.js'
|
||||
import { formatEther } from 'ethers'
|
||||
import { formatEther, formatUnits } from 'ethers'
|
||||
|
||||
let w = Wallet()
|
||||
let inputSeed = $state('')
|
||||
@@ -61,13 +62,20 @@
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Wallet</CardTitle>
|
||||
<CardDescription>Your wallet is unlocked</CardDescription>
|
||||
<CardDescription>
|
||||
Your wallet is unlocked
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div class="flex gap-1" role="group">
|
||||
{#each w.networks as net}
|
||||
<button
|
||||
class="cursor-pointer rounded-md px-2.5 py-1 text-xs font-medium transition-colors {w.network === net.id ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground hover:bg-muted/80'}"
|
||||
onclick={() => w.switchNetwork(net.id)}>{net.name}</button>
|
||||
class="cursor-pointer rounded-md px-2.5 py-1 text-xs font-medium transition-colors {w.network ===
|
||||
net.id
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-muted text-muted-foreground hover:bg-muted/80'}"
|
||||
onclick={() => w.switchNetwork(net.id)}>
|
||||
{net.name}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
@@ -77,14 +85,19 @@
|
||||
<div class="mb-4 space-y-1">
|
||||
<p class="font-medium text-xs">Address</p>
|
||||
<p class="font-mono text-xs break-all">{w.address}</p>
|
||||
<p class="mt-2 font-medium text-xs">{w.symbol} Balance</p>
|
||||
<p class="mt-2 font-medium text-xs">
|
||||
{w.symbol} Balance
|
||||
</p>
|
||||
<p class="font-mono text-lg">{w.balance} {w.symbol}</p>
|
||||
</div>
|
||||
<div class="mb-4 space-y-1">
|
||||
<p class="font-medium text-xs">Tokens</p>
|
||||
{#each w.tokenBalances as t}
|
||||
<p class="font-mono text-sm">
|
||||
{Number(t.balance) < 0.0001 && Number(t.balance) > 0 ? '<0.0001' : Number(t.balance).toFixed(4)} {t.symbol}
|
||||
{Number(t.balance) < 0.0001 && Number(t.balance) > 0
|
||||
? '<0.0001'
|
||||
: Number(t.balance).toFixed(4)}
|
||||
{t.symbol}
|
||||
</p>
|
||||
{/each}
|
||||
</div>
|
||||
@@ -119,27 +132,61 @@
|
||||
<Button
|
||||
size="sm"
|
||||
onclick={() => w.saveEtherscanKey(apiKeyInput)}
|
||||
disabled={!apiKeyInput.trim()}>Save</Button>
|
||||
disabled={!apiKeyInput.trim()}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
{:else if w.transactions.length === 0}
|
||||
<p class="text-muted-foreground text-xs">No transactions found</p>
|
||||
<p class="text-muted-foreground text-xs">
|
||||
No transactions found
|
||||
</p>
|
||||
{:else}
|
||||
<div class="max-h-48 space-y-1 overflow-y-auto">
|
||||
{#each w.transactions.slice(0, 10) as tx}
|
||||
<div class="flex items-center justify-between rounded-md bg-muted px-2 py-1.5 font-mono text-xs">
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="truncate" title={tx.hash}>
|
||||
<a
|
||||
href="{w.explorerUrl}{tx.hash}"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
class="hover:underline">{tx.hash.slice(0, 10)}...</a>
|
||||
<div class="max-h-96 space-y-1 overflow-y-auto">
|
||||
{#each w.transactions as tx}
|
||||
<div
|
||||
class="flex items-center justify-between rounded-md bg-muted px-3 py-2 text-xs">
|
||||
<div class="min-w-0 flex-1 space-y-0.5">
|
||||
<p class="truncate font-mono" title={tx.hash}>
|
||||
<button
|
||||
onclick={() => electrobun.rpc?.request.openExternal({ url: w.explorerUrl + tx.hash })}
|
||||
class="hover:underline cursor-pointer">
|
||||
{tx.hash.slice(0, 10)}...
|
||||
</button>
|
||||
</p>
|
||||
<p class="text-muted-foreground font-mono">
|
||||
{#if tx.tokenSymbol}
|
||||
{Number(
|
||||
formatUnits(
|
||||
tx.value,
|
||||
Number(tx.tokenDecimal ?? 18),
|
||||
),
|
||||
).toFixed(4)}
|
||||
{tx.tokenSymbol}
|
||||
{:else}
|
||||
{Number(formatEther(tx.value)).toFixed(4)}
|
||||
{w.symbol}
|
||||
{/if}
|
||||
</p>
|
||||
<p class="text-muted-foreground">
|
||||
{new Date(
|
||||
Number(tx.timeStamp) * 1000,
|
||||
).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})}
|
||||
</p>
|
||||
<p class="text-muted-foreground">{Number(formatEther(tx.value)).toFixed(4)} {w.symbol}</p>
|
||||
</div>
|
||||
<span class="shrink-0 {tx.isError === '0' ? 'text-green-500' : 'text-red-500'}">
|
||||
{tx.isError === '0' ? '✓' : '✗'}
|
||||
</span>
|
||||
{#if !tx.tokenSymbol}
|
||||
<span
|
||||
class="ml-2 shrink-0 {tx.isError === '0'
|
||||
? 'text-green-500'
|
||||
: 'text-red-500'}">
|
||||
{tx.isError === '0' ? '✓' : '✗'}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user