add native token + internal transfers

This commit is contained in:
2026-05-11 11:27:24 +08:00
parent 9fca18cf95
commit 0074d6fb4e
4 changed files with 267 additions and 70 deletions
+93 -34
View File
@@ -5,6 +5,7 @@ import {
Updater, Updater,
defineElectrobunRPC, defineElectrobunRPC,
type RPCSchema, type RPCSchema,
Utils,
} from 'electrobun/bun' } from 'electrobun/bun'
const DEV_SERVER_PORT = 5173 const DEV_SERVER_PORT = 5173
@@ -57,20 +58,17 @@ const url = await getMainViewUrl()
const ETHERSCAN_API = 'https://api.etherscan.io/v2/api' const ETHERSCAN_API = 'https://api.etherscan.io/v2/api'
type EtherscanTx = { type TxEntry = {
blockNumber: string
timeStamp: string
hash: string hash: string
timeStamp: string
from: string from: string
to: string to: string
value: string value: string
gas: string isError?: string
gasPrice: string tokenSymbol?: string
isError: string tokenName?: string
txreceipt_status: string tokenDecimal?: string
input: string contractAddress?: string
contractAddress: string
gasUsed: string
} }
type RPC = { type RPC = {
@@ -98,7 +96,13 @@ type RPC = {
page?: number page?: number
offset?: number offset?: number
} }
response: Promise<EtherscanTx[]> response: Promise<TxEntry[]>
}
openExternal: {
params: {
url: string
}
response: Promise<void>
} }
} }
messages: {} messages: {}
@@ -108,8 +112,34 @@ type RPC = {
messages: {} 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>({ const rpc = BrowserView.defineRPC<RPC>({
maxRequestTime: 10000, maxRequestTime: 20000,
handlers: { handlers: {
requests: { requests: {
getSecret: async ({ name, service }) => { getSecret: async ({ name, service }) => {
@@ -118,38 +148,67 @@ const rpc = BrowserView.defineRPC<RPC>({
setSecret: async ({ name, service, value }) => { setSecret: async ({ name, service, value }) => {
await Bun.secrets.set({ name, service, value }) await Bun.secrets.set({ name, service, value })
}, },
openExternal: async ({ url }) => {
Utils.openExternal(url)
},
fetchTxHistory: async ({ fetchTxHistory: async ({
address, address,
chainid, chainid,
page = 1, page = 1,
offset = 20, offset = 1000,
}) => { }) => {
const key = await Bun.secrets.get({ const key = await Bun.secrets.get({
service: 'koins', service: 'koins',
name: 'etherscan_key', name: 'etherscan_key',
}) })
if (!key) return [] if (!key) return []
const params = new URLSearchParams({
module: 'account', const [nativeTxs, tokenTxs] = await Promise.all([
action: 'txlist', fetchEtherscan(
address, key,
page: String(page), chainid,
offset: String(offset), 'txlist',
sort: 'desc', address,
apikey: key, page,
chainid, offset,
}) ),
try { fetchEtherscan(
const url = `${ETHERSCAN_API}?${params}` key,
const res = await fetch(url) chainid,
const data = await res.json() 'tokentx',
console.log(data) address,
if (data.status !== '1') return [] page,
return data.result as EtherscanTx[] offset,
} catch (error) { ),
console.log(error) ])
return []
} 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: {}, messages: {},
+14 -11
View File
@@ -1,19 +1,16 @@
import { Electroview } from 'electrobun/view' import { Electroview } from 'electrobun/view'
export type EtherscanTx = { export type TxEntry = {
blockNumber: string
timeStamp: string
hash: string hash: string
timeStamp: string
from: string from: string
to: string to: string
value: string value: string
isError: string isError?: string
txreceipt_status: string tokenSymbol?: string
gas: string tokenName?: string
gasPrice: string tokenDecimal?: string
input: string contractAddress?: string
contractAddress: string
gasUsed: string
} }
type RPC = { type RPC = {
@@ -41,7 +38,13 @@ type RPC = {
page?: number page?: number
offset?: number offset?: number
} }
response: Promise<EtherscanTx[]> response: Promise<TxEntry[]>
}
openExternal: {
params: {
url: string
}
response: Promise<void>
} }
} }
messages: {} messages: {}
+91 -3
View File
@@ -5,12 +5,20 @@ import {
formatUnits, formatUnits,
Contract, Contract,
} from 'ethers' } from 'ethers'
import { electrobun, type EtherscanTx } from '$lib/electrobun' import { electrobun, type TxEntry } from '$lib/electrobun'
const ERC20_ABI = [ const ERC20_ABI = [
'function balanceOf(address) view returns (uint256)', '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 = [ export const networks = [
{ {
id: 'bsc', id: 'bsc',
@@ -35,7 +43,7 @@ export const networks = [
{ {
id: 'polygon', id: 'polygon',
name: 'Polygon', name: 'Polygon',
rpc: 'https://polygon.drpc.org', rpc: 'https://polygon-bor.publicnode.com',
symbol: 'POL', symbol: 'POL',
chainid: '137', chainid: '137',
explorerUrl: 'https://polygonscan.com/tx/', explorerUrl: 'https://polygonscan.com/tx/',
@@ -94,7 +102,8 @@ export const Wallet = () => {
let vaultExists = $state(false) let vaultExists = $state(false)
let ready = $state(false) let ready = $state(false)
let etherscanKey = $state('') let etherscanKey = $state('')
let transactions = $state<EtherscanTx[]>([]) let transactions = $state<TxEntry[]>([])
let discoveredTokens = $state<DiscoveredToken[]>([])
const net = () => networks.find((n) => n.id === network)! const net = () => networks.find((n) => n.id === network)!
@@ -125,6 +134,7 @@ export const Wallet = () => {
const switchNetwork = async (id: NetworkId) => { const switchNetwork = async (id: NetworkId) => {
network = id network = id
discoveredTokens = []
if (seed) await refresh() if (seed) await refresh()
} }
@@ -155,6 +165,7 @@ export const Wallet = () => {
error = '' error = ''
tokenBalances = [] tokenBalances = []
transactions = [] transactions = []
discoveredTokens = []
} }
const refresh = async () => { const refresh = async () => {
@@ -180,6 +191,18 @@ export const Wallet = () => {
return { symbol: t.symbol, balance: '0' } 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) balance = formatEther(nativeBal)
tokenBalances = tokenBals tokenBalances = tokenBals
@@ -212,6 +235,68 @@ export const Wallet = () => {
chainid: net().chainid, chainid: net().chainid,
}) })
transactions = txs ?? [] 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 { return {
@@ -269,6 +354,9 @@ export const Wallet = () => {
get transactions() { get transactions() {
return transactions return transactions
}, },
get discoveredTokens() {
return discoveredTokens
},
refresh, refresh,
init, init,
lock, lock,
+69 -22
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { electrobun } from '$lib/electrobun.js'
import { Wallet } from '$lib/states/wallet.svelte.js' import { Wallet } from '$lib/states/wallet.svelte.js'
import { Button } from '$lib/components/ui/button/index.js' import { Button } from '$lib/components/ui/button/index.js'
import { Textarea } from '$lib/components/ui/textarea/index.js' import { Textarea } from '$lib/components/ui/textarea/index.js'
@@ -9,7 +10,7 @@
CardHeader, CardHeader,
CardTitle, CardTitle,
} from '$lib/components/ui/card/index.js' } from '$lib/components/ui/card/index.js'
import { formatEther } from 'ethers' import { formatEther, formatUnits } from 'ethers'
let w = Wallet() let w = Wallet()
let inputSeed = $state('') let inputSeed = $state('')
@@ -61,13 +62,20 @@
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
<div> <div>
<CardTitle>Wallet</CardTitle> <CardTitle>Wallet</CardTitle>
<CardDescription>Your wallet is unlocked</CardDescription> <CardDescription>
Your wallet is unlocked
</CardDescription>
</div> </div>
<div class="flex gap-1" role="group"> <div class="flex gap-1" role="group">
{#each w.networks as net} {#each w.networks as net}
<button <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'}" class="cursor-pointer rounded-md px-2.5 py-1 text-xs font-medium transition-colors {w.network ===
onclick={() => w.switchNetwork(net.id)}>{net.name}</button> 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} {/each}
</div> </div>
</div> </div>
@@ -77,14 +85,19 @@
<div class="mb-4 space-y-1"> <div class="mb-4 space-y-1">
<p class="font-medium text-xs">Address</p> <p class="font-medium text-xs">Address</p>
<p class="font-mono text-xs break-all">{w.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> <p class="font-mono text-lg">{w.balance} {w.symbol}</p>
</div> </div>
<div class="mb-4 space-y-1"> <div class="mb-4 space-y-1">
<p class="font-medium text-xs">Tokens</p> <p class="font-medium text-xs">Tokens</p>
{#each w.tokenBalances as t} {#each w.tokenBalances as t}
<p class="font-mono text-sm"> <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> </p>
{/each} {/each}
</div> </div>
@@ -119,27 +132,61 @@
<Button <Button
size="sm" size="sm"
onclick={() => w.saveEtherscanKey(apiKeyInput)} onclick={() => w.saveEtherscanKey(apiKeyInput)}
disabled={!apiKeyInput.trim()}>Save</Button> disabled={!apiKeyInput.trim()}>
Save
</Button>
</div> </div>
{:else if w.transactions.length === 0} {: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} {:else}
<div class="max-h-48 space-y-1 overflow-y-auto"> <div class="max-h-96 space-y-1 overflow-y-auto">
{#each w.transactions.slice(0, 10) as tx} {#each w.transactions as tx}
<div class="flex items-center justify-between rounded-md bg-muted px-2 py-1.5 font-mono text-xs"> <div
<div class="min-w-0 flex-1"> class="flex items-center justify-between rounded-md bg-muted px-3 py-2 text-xs">
<p class="truncate" title={tx.hash}> <div class="min-w-0 flex-1 space-y-0.5">
<a <p class="truncate font-mono" title={tx.hash}>
href="{w.explorerUrl}{tx.hash}" <button
target="_blank" onclick={() => electrobun.rpc?.request.openExternal({ url: w.explorerUrl + tx.hash })}
rel="noreferrer" class="hover:underline cursor-pointer">
class="hover:underline">{tx.hash.slice(0, 10)}...</a> {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>
<p class="text-muted-foreground">{Number(formatEther(tx.value)).toFixed(4)} {w.symbol}</p>
</div> </div>
<span class="shrink-0 {tx.isError === '0' ? 'text-green-500' : 'text-red-500'}"> {#if !tx.tokenSymbol}
{tx.isError === '0' ? '✓' : '✗'} <span
</span> class="ml-2 shrink-0 {tx.isError === '0'
? 'text-green-500'
: 'text-red-500'}">
{tx.isError === '0' ? '✓' : '✗'}
</span>
{/if}
</div> </div>
{/each} {/each}
</div> </div>