Skip to content

Commit

Permalink
Merge pull request #88 from onflow/cf/get-balance
Browse files Browse the repository at this point in the history
Add balance for previewnet
  • Loading branch information
chasefleming committed Feb 27, 2024
2 parents 73c28a3 + 765af53 commit 8e91e99
Show file tree
Hide file tree
Showing 4 changed files with 124 additions and 18 deletions.
114 changes: 105 additions & 9 deletions components/FundAccountSubmitted.tsx
Expand Up @@ -4,6 +4,11 @@ import LoadingFeedback from "components/LoadingFeedback"
import {Box, Flex, Link, Themed, ThemeUICSSObject} from "theme-ui"
import {ClientFundAccountResult} from "./FundAccountPanel"
import publicConfig from "lib/publicConfig"
import {useEffect, useState} from "react"
import {sendScript} from "../lib/flow/send"
import * as fcl from "@onflow/fcl"
import * as t from "@onflow/types"
import {getAddressType} from "../lib/common"

const styles: Record<string, ThemeUICSSObject> = {
resultsContainer: {
Expand All @@ -29,10 +34,84 @@ export default function FundAccountSubmitted({
}: {
result?: ClientFundAccountResult
}) {
const [isFetchingBalance, setIsFetchingBalance] = useState(false)
const [balance, setBalance] = useState("")
const [balanceError, setBalanceError] = useState("")

useEffect(() => {
if (typeof result === "undefined") return

const fetchBalance = async (addr: string) => {
try {
setIsFetchingBalance(true)

const addressType = getAddressType(result.address)
let addressArg

const addressArgType =
publicConfig.network === "testnet" || addressType === "FLOW"
? t.Address
: t.String

if (addressType === "FLOWEVM") {
const withoutPrefix = fcl.sansPrefix(result.address)
if (!withoutPrefix) {
throw new Error("Invalid address")
}

addressArg = withoutPrefix
} else {
addressArg = addr
}

const balanceScript =
publicConfig.network === "previewnet" && addressType === "FLOWEVM"
? `import EVM from ${publicConfig.contractEVM}
/// Returns the Flow balance of a given EVM address in FlowEVM
///
access(all) fun main(address: String): UFix64 {
let bytes = address.decodeHex()
let addressBytes: [UInt8; 20] = [
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4],
bytes[5], bytes[6], bytes[7], bytes[8], bytes[9],
bytes[10], bytes[11], bytes[12], bytes[13], bytes[14],
bytes[15], bytes[16], bytes[17], bytes[18], bytes[19]
]
return EVM.EVMAddress(bytes: addressBytes).balance().inFLOW()
}`
: `import FungibleToken from ${publicConfig.contractFungibleToken}
import FlowToken from ${publicConfig.contractFlowToken}
access(all) fun main(account: Address): UFix64 {
let vaultRef = getAccount(account)
.capabilities.borrow<&{FungibleToken.Balance}>(/public/flowTokenBalance)
?? panic("Could not borrow Balance reference to the Vault")
return vaultRef.balance
}`

const res = await sendScript({
script: balanceScript,
args: [fcl.arg(addressArg, addressArgType)],
})
setBalance(res)
} catch (error) {
setBalance("--")
setBalanceError("An error occurred")
} finally {
setIsFetchingBalance(false)
}
}

fetchBalance(result.address)
}, [result])

return (
<>
<Box mb={4} mt={4}>
<Themed.h3 sx={{mb: 0}}>Funding account</Themed.h3>
<Themed.h3 sx={{mb: 0}}>Funding Account</Themed.h3>
<Themed.p>Great! Your request has been submitted.</Themed.p>
</Box>
<Box mb={6} sx={styles.resultsContainer}>
Expand Down Expand Up @@ -60,15 +139,32 @@ export default function FundAccountSubmitted({
result.token
} tokens`}
</div>
<Link
href={`https://${publicConfig.network}.flowdiver.io/account/${result.address}`}
target="_blank"
variant="secondary"
sx={{fontSize: 1}}
>
View Account
</Link>
{publicConfig.network === "testnet" && (
<Link
href={`https://${publicConfig.network}.flowdiver.io/account/${result.address}`}
target="_blank"
variant="secondary"
sx={{fontSize: 1}}
>
View Account
</Link>
)}
</Flex>
{publicConfig.network === "previewnet" && (
<>
<Label>Balance</Label>
{isFetchingBalance ? (
<div>Fetching...</div>
) : (
<>
<div>{balance}</div>
{balanceError && balanceError.length > 0 && (
<div>{balanceError}</div>
)}
</>
)}
</>
)}
</Box>
</>
)}
Expand Down
8 changes: 8 additions & 0 deletions lib/common.ts
Expand Up @@ -16,3 +16,11 @@ export function verifyAPIKey(req: string, keys: string[]): boolean {
}
return false
}

export const getAddressType = function (address: string): "FLOW" | "FLOWEVM" {
if (address.length <= 18) {
return "FLOW"
} else {
return "FLOWEVM"
}
}
10 changes: 1 addition & 9 deletions lib/flow/fund.ts
Expand Up @@ -3,6 +3,7 @@ import * as t from "@onflow/types"
import {FLOW_TYPE} from "../constants"
import publicConfig, {TOKEN_FUNDING_AMOUNTS} from "../publicConfig"
import {sendTransaction} from "./send"
import {getAddressType} from "../common"

const txFundAccountFLOW = `
import FlowToken from ${publicConfig.contractFlowToken}
Expand Down Expand Up @@ -86,15 +87,6 @@ export const tokens: Tokens = {
FLOW: {tx: txFundAccountFLOW, amount: TOKEN_FUNDING_AMOUNTS[FLOW_TYPE]},
FLOWEVM: {tx: txFundAccountFlowEVM, amount: TOKEN_FUNDING_AMOUNTS[FLOW_TYPE]},
}

function getAddressType(address: string): "FLOW" | "FLOWEVM" {
if (address.length <= 18) {
return "FLOW"
} else {
return "FLOWEVM"
}
}

export async function fundAccount(
address: string,
token: TokenType,
Expand Down
10 changes: 10 additions & 0 deletions lib/flow/send.ts
Expand Up @@ -24,3 +24,13 @@ export async function sendTransaction({

return fcl.tx(response).onceSealed()
}

export async function sendScript({
script,
args,
}: {
script: string
args: fcl.TransactionArg[]
}) {
return fcl.send([fcl.script(script), fcl.args(args)]).then(fcl.decode)
}

0 comments on commit 8e91e99

Please sign in to comment.