Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OnboardingAPI: Implement faucet for remark signing evm on cent chain #1547

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 20 additions & 9 deletions centrifuge-app/src/pages/Onboarding/queries/useSignRemark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
useTransactions,
useWallet,
} from '@centrifuge/centrifuge-react'
import { useNativeBalance } from '@centrifuge/centrifuge-react/dist/components/WalletProvider/evm/utils'
import { Contract } from '@ethersproject/contracts'
import React, { useEffect } from 'react'
import { UseMutateFunction } from 'react-query'
Expand Down Expand Up @@ -39,10 +40,12 @@
connectedType,
isEvmOnSubstrate,
substrate: { selectedAddress, selectedAccount },
evm: { selectedAddress: evmSelectedAddress, chainId: evmChainId },
connectedNetwork,
} = useWallet()
const [expectedTxFee, setExpectedTxFee] = React.useState(Dec(0))
const balances = useBalances(selectedAddress || '')
const balances = useBalances(selectedAddress || undefined)
const { data: evmBalance } = useNativeBalance()
const { authToken } = useOnboardingAuth()
const [account] = useSuitableAccounts({ actingAddress: [selectedAddress || ''] })

Expand Down Expand Up @@ -79,7 +82,7 @@
const txIdSignRemark = Math.random().toString(36).substr(2)
addOrUpdateTransaction({
id: txIdSignRemark,
title: `Get ${balances?.native.currency.symbol}`,
title: `Get ${balances?.native.currency.symbol || 'CFG'}`,
status: 'pending',
args: [],
})
Expand All @@ -95,16 +98,16 @@
if (response.status !== 201) {
addOrUpdateTransaction({
id: txIdSignRemark,
title: `Get ${balances?.native.currency.symbol}`,
title: `Get ${balances?.native.currency.symbol || 'CFG'}`,
status: 'failed',
args: [],
})
setIsSubstrateTxLoading(false)
throw new Error('Insufficient funds')
throw new Error('Unable to get balance for signing')
} else {
addOrUpdateTransaction({
id: txIdSignRemark,
title: `Get ${balances?.native.currency.symbol}`,
title: `Get ${balances?.native.currency.symbol || 'CFG'}`,
status: 'succeeded',
args: [],
})
Expand All @@ -113,23 +116,31 @@

const signSubstrateRemark = async (args: [message: string]) => {
setIsSubstrateTxLoading(true)
if (!isEvmOnSubstrate && balances?.native.balance?.toDecimal().lt(expectedTxFee.mul(1.1))) {
if (balances?.native.balance?.toDecimal().lt(expectedTxFee.mul(1.1))) {
await getBalanceForSigning()
}
if (isEvmOnSubstrate && evmBalance?.toDecimal().lt(expectedTxFee.mul(1.1))) {
onnovisser marked this conversation as resolved.
Show resolved Hide resolved
await getBalanceForSigning()
}
substrateMutation.execute(args, { account })
}

useEffect(() => {
const executePaymentInfo = async () => {
if (selectedAccount && selectedAccount.signer) {
const api = await centrifuge.connect(selectedAccount.address, selectedAccount.signer as any)
if ((selectedAccount && selectedAccount.signer) || (isEvmOnSubstrate && evmSelectedAddress)) {
const address =
isEvmOnSubstrate && evmSelectedAddress
? centrifuge.utils.evmToSubstrateAddress(evmSelectedAddress, evmChainId!)
: selectedAccount?.address
const signer = selectedAccount?.signer || (await evmProvider?.getSigner())
const api = await centrifuge.connect(address!, signer as any)
const paymentInfo = await lastValueFrom(
api.remark.signRemark(
[
`I hereby sign the subscription agreement of pool [POOL_ID] and tranche [TRANCHE_ID]: [IPFS_HASH_OF_TEMPLATE]`,
],
{
paymentInfo: selectedAccount.address,
paymentInfo: address!,
}
)
)
Expand All @@ -138,7 +149,7 @@
}
}
executePaymentInfo()
}, [centrifuge, selectedAccount])

Check warning on line 152 in centrifuge-app/src/pages/Onboarding/queries/useSignRemark.ts

View workflow job for this annotation

GitHub Actions / build-app

React Hook useEffect has missing dependencies: 'evmChainId', 'evmProvider', 'evmSelectedAddress', and 'isEvmOnSubstrate'. Either include them or remove the dependency array

const signEvmRemark = async (args: [message: string]) => {
const txId = Math.random().toString(36).substr(2)
Expand Down
4 changes: 2 additions & 2 deletions onboarding-api/src/controllers/auth/authenticateWallet.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { isAddress } from '@polkadot/util-crypto'
import { Request, Response } from 'express'
import * as jwt from 'jsonwebtoken'
import { InferType, object, string, StringSchema } from 'yup'
import { InferType, number, object, string, StringSchema } from 'yup'
import { SupportedNetworks } from '../../database'
import { reportHttpError } from '../../utils/httpError'
import { NetworkSwitch } from '../../utils/networks/networkSwitch'
Expand Down Expand Up @@ -30,7 +30,7 @@ const verifyWalletInput = object({
}),
nonce: string().required(),
network: string().oneOf(['evm', 'substrate', 'evmOnSubstrate']) as StringSchema<SupportedNetworks>,
chainId: string().required(),
chainId: number().required(),
})

export const authenticateWalletController = async (
Expand Down
4 changes: 2 additions & 2 deletions onboarding-api/src/database/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Firestore } from '@google-cloud/firestore'
import { Storage } from '@google-cloud/storage'
import * as dotenv from 'dotenv'
import { Request } from 'express'
import { array, bool, date, InferType, lazy, mixed, object, string, StringSchema } from 'yup'
import { array, bool, date, InferType, lazy, mixed, number, object, string, StringSchema } from 'yup'
import { HttpError } from '../utils/httpError'
import { Subset } from '../utils/types'

Expand Down Expand Up @@ -34,7 +34,7 @@ export const transactionInfoSchema = object({
txHash: string().required(),
blockNumber: string().required(),
isEvmOnSubstrate: bool().optional(),
chainId: string().required(),
chainId: number().required(),
})
export type TransactionInfo = InferType<typeof transactionInfoSchema>

Expand Down
11 changes: 6 additions & 5 deletions onboarding-api/src/utils/networks/centrifuge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,13 @@ export const validateSubstrateRemark = async (
}

export const checkBalanceBeforeSigningRemark = async (wallet: Request['wallet']) => {
const address = await getValidSubstrateAddress(wallet)
const signer = await getSigner()
const $api = getCentrifuge().getApi()
const $paymentInfo = $api
.pipe(switchMap((api) => api.tx.system.remarkWithEvent('Signing for pool').paymentInfo(wallet.address)))
.pipe(switchMap((api) => api.tx.system.remarkWithEvent('Signing for pool').paymentInfo(address)))
.pipe(take(1))
const $nativeBalance = $api.pipe(switchMap((api) => api.query.system.account(wallet.address))).pipe(take(1))
const $nativeBalance = $api.pipe(switchMap((api) => api.query.system.account(address))).pipe(take(1))
const tx = await lastValueFrom(
combineLatest([$api, $paymentInfo, $nativeBalance]).pipe(
switchMap(([api, paymentInfo, nativeBalance]) => {
Expand All @@ -151,18 +152,18 @@ export const checkBalanceBeforeSigningRemark = async (wallet: Request['wallet'])
}

// add 10% buffer to the transaction fee
const submittable = api.tx.tokens.transfer({ Id: wallet.address }, 'Native', txFee.add(txFee.muln(1.1)))
const submittable = api.tx.tokens.transfer({ Id: address }, 'Native', txFee.add(txFee.muln(1.1)))
return submittable.signAndSend(signer)
}),
takeWhile(({ events, isFinalized }) => {
if (events.length > 0) {
events.forEach(({ event }) => {
const result = event.data[0]?.toHuman()
if (event.method === 'ProxyExecuted' && result === 'Ok') {
console.log(`Executed proxy for transfer`, { walletAddress: wallet.address, result })
console.log(`Executed proxy for transfer`, { walletAddress: address, result })
}
if (event.method === 'ExtrinsicFailed') {
console.log(`Extrinsic failed`, { walletAddress: wallet.address, result })
console.log(`Extrinsic failed`, { walletAddress: address, result })
throw new HttpError(400, 'Extrinsic failed')
}
})
Expand Down
12 changes: 6 additions & 6 deletions onboarding-api/src/utils/networks/evm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@ import { signAndSendDocumentsInput } from '../../controllers/emails/signAndSendD
import { HttpError } from '../httpError'
import RemarkerAbi from './abi/Remarker.abi.json'

const getEvmProvider = (chainId: number | string, isEvmOnCentChain?: boolean): Provider => {
const getEvmProvider = (chainId: number, isEvmOnCentChain?: boolean): Provider => {
if (isEvmOnCentChain) {
return new InfuraProvider(chainId, process.env.INFURA_KEY)
}
switch (chainId.toString()) {
case '1': // eth mainnet
case '5': // goerli
switch (chainId) {
case 1: // eth mainnet
case 5: // goerli
return new InfuraProvider(chainId, process.env.INFURA_KEY)
case '8453': // base mainnet
case 8453: // base mainnet
return new JsonRpcProvider('https://mainnet.base.org')
case '84531': // base goerli
case 84531: // base goerli
return new JsonRpcProvider('https://goerli.base.org')
default:
throw new HttpError(404, `Unsupported chainId ${chainId}`)
Expand Down
2 changes: 1 addition & 1 deletion onboarding-api/src/utils/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ declare global {
wallet: {
address: string
network: SupportedNetworks
chainId: string
chainId: number
}
}
}
Expand Down
Loading