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

Update to ethers 6 #1776

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
63 changes: 38 additions & 25 deletions main/wallet-backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@

const keytar = require('keytar')
const { strict: assert } = require('node:assert')
const { ethers } = require('ethers')
const {
JsonRpcProvider,
Wallet,
FetchRequest,
Contract,
parseEther,
formatUnits
} = require('ethers')
const {
delegatedFromEthAddress,
ethAddressFromDelegated,
Expand All @@ -27,6 +34,7 @@ const { format } = require('node:util')
/** @typedef {
import('./typings').FILTransactionProcessing
} FILTransactionProcessing */
/** @typedef {import('ethers').HDNodeWallet} HDNodeWallet */

const DISABLE_KEYTAR = process.env.DISABLE_KEYTAR === 'true'
// eslint-disable-next-line max-len
Expand All @@ -48,9 +56,9 @@ class WalletBackend {
disableKeytar = DISABLE_KEYTAR,
onTransactionUpdate = noop
} = {}) {
/** @type {ethers.providers.JsonRpcProvider | null} */
/** @type {JsonRpcProvider | null} */
this.provider = null
/** @type {ethers.Wallet | null} */
/** @type {HDNodeWallet | null} */
this.signer = null
/** @type {`0x${string}` | null} */
this.address = null
Expand All @@ -73,25 +81,27 @@ class WalletBackend {
} else {
({ seed, isNew } = await this.getSeedPhrase())
}
this.provider = new ethers.providers.JsonRpcProvider({
url: 'https://api.node.glif.io/rpc/v0',
headers: {
Authorization: 'Bearer VOeqfEFbUjr/vnvYSwbohKuilNkdmD/4tI3gXzV7f3g='
}
})
this.signer = ethers.Wallet.fromMnemonic(seed).connect(this.provider)
const fetchRequest = new FetchRequest(
'https://api.node.glif.io/rpc/v1'
)
fetchRequest.setHeader(
'Authorization',
'Bearer VOeqfEFbUjr/vnvYSwbohKuilNkdmD/4tI3gXzV7f3g='
)
this.provider = new JsonRpcProvider(fetchRequest)
this.signer = Wallet.fromPhrase(seed).connect(this.provider)
this.address = /** @type {any} */(this.signer.address)
assert(this.address !== null)
this.addressDelegated = delegatedFromEthAddress(this.address, CoinType.MAIN)
this.filForwarder = new ethers.Contract(
this.filForwarder = new Contract(
'0x2b3ef6906429b580b7b2080de5ca893bc282c225',
await fs.readFile(join(__dirname, 'filforwarder-abi.json'), 'utf8'),
this.provider
).connect(this.signer)
const SparkImpactEvaluator = await import(
'@filecoin-station/spark-impact-evaluator'
)
this.meridian = new ethers.Contract(
this.meridian = new Contract(
SparkImpactEvaluator.ADDRESS,
SparkImpactEvaluator.ABI,
this.provider
Expand Down Expand Up @@ -122,21 +132,24 @@ class WalletBackend {
}
}

seed = ethers.Wallet.createRandom().mnemonic.phrase
const mnemonic = Wallet.createRandom().mnemonic
assert(mnemonic)
seed = mnemonic.phrase
if (!this.disableKeytar) {
await keytar.setPassword(service, 'seed', seed)
}
return { seed, isNew: true }
}

async fetchBalance () {
assert(this.signer)
return await this.signer.getBalance()
assert(this.provider)
assert(this.address)
return await this.provider.getBalance(this.address)
}

/**
* @param {string} to
* @param {ethers.BigNumber} amount
* @param {bigint} amount
* @returns {Promise<string>}
*/
async transferFunds (to, amount) {
Expand All @@ -155,15 +168,15 @@ class WalletBackend {

/**
* @param {`f1${string}`} to
* @param {ethers.BigNumber} amount
* @param {bigint} amount
* @returns {Promise<string>}
*/
async transferFundsToF1Address (to, amount) {
return await this.runTransaction(to, amount, async () => {
assert(this.signer)
assert(this.filForwarder)

const amountMinusGas = amount.sub(ethers.utils.parseEther('0.01'))
const amountMinusGas = amount - parseEther('0.01')
log.info('filForwarder.forward()', {
to,
amountMinusGas: amountMinusGas.toString()
Expand All @@ -177,14 +190,14 @@ class WalletBackend {

/**
* @param {`0x${string}`} to
* @param {ethers.BigNumber} amount
* @param {bigint} amount
* @returns {Promise<string>}
*/
async transferFundsToEthAddress (to, amount) {
return await this.runTransaction(to, amount, async () => {
assert(this.signer)

const amountMinusGas = amount.sub(ethers.utils.parseEther('0.01'))
const amountMinusGas = amount - parseEther('0.01')
log.info('sendTransaction()', {
to,
amount: amount.toString(),
Expand All @@ -199,7 +212,7 @@ class WalletBackend {

/**
* @param {`f1${string}` | `0x${string}`} to
* @param {ethers.BigNumber} amount
* @param {bigint} amount
* @param {function} fn
* @returns {Promise<string>}
*/
Expand All @@ -211,7 +224,7 @@ class WalletBackend {
timestamp: new Date().getTime(),
status: 'processing',
outgoing: true,
amount: ethers.utils.formatUnits(amount, 18),
amount: formatUnits(amount, 18),
address: startsWithF1(to)
? to
: delegatedFromEthAddress(to, CoinType.MAIN)
Expand Down Expand Up @@ -306,7 +319,7 @@ class WalletBackend {
height: message.height,
hash: message.tx_cid,
outgoing: message.tx_from === this.addressDelegated,
amount: ethers.utils.formatUnits(BigInt(message.amount), 18),
amount: formatUnits(BigInt(message.amount), 18),
address: message.tx_from === this.addressDelegated
? message.tx_to
: message.tx_from,
Expand All @@ -333,7 +346,7 @@ class WalletBackend {
}

/**
* @returns {Promise<ethers.BigNumber>}
* @returns {Promise<bigint>}
*/
async fetchScheduledRewards () {
assert(this.address, 'address')
Expand All @@ -342,7 +355,7 @@ class WalletBackend {
return await this.meridian.rewardsScheduledFor(this.address)
} catch (/** @type {any} */ err) {
log.error('Cannot fetch scheduled rewards:', err)
return ethers.BigNumber.from(0)
return 0n
}
}
}
Expand Down
21 changes: 10 additions & 11 deletions main/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ const timers = require('node:timers/promises')
const { format } = require('node:util')
const Store = require('electron-store')
const { WalletBackend } = require('./wallet-backend')
const { ethers } = require('ethers')
const { formatEther } = require('ethers/lib/utils')
const { formatEther, formatUnits } = require('ethers')

/** @typedef {import('./typings').Context} Context */
/** @typedef {import('./typings').FILTransaction} FILTransaction */
Expand Down Expand Up @@ -83,7 +82,7 @@ async function refreshState () {
* @returns {string}
*/
function getBalance () {
return ethers.utils.formatUnits(balance, 18)
return formatUnits(balance, 18)
}

/**
Expand Down Expand Up @@ -116,8 +115,8 @@ async function updateBalance () {
async function _updateBalance () {
assert(ctx)
balance = await backend.fetchBalance()
walletStore.set('balance_0x', balance.toHexString())
ctx.balanceUpdate(ethers.utils.formatUnits(balance, 18))
walletStore.set('balance_0x', balance.toString(16))
ctx.balanceUpdate(formatUnits(balance, 18))
}

/** @type {Promise<void>|undefined} */
Expand All @@ -140,10 +139,10 @@ async function _updateScheduledRewards () {
}

/**
* @param {ethers.BigNumber} scheduledRewards
* @param {bigint} scheduledRewards
*/
async function setScheduledRewards (scheduledRewards) {
walletStore.set('scheduled_rewards', scheduledRewards.toHexString())
walletStore.set('scheduled_rewards', `0x${scheduledRewards.toString(16)}`)
}

function listTransactions () {
Expand Down Expand Up @@ -232,17 +231,17 @@ function loadStoredEntries () {
}

/**
* @returns {ethers.BigNumber}
* @returns {bigint}
*/
function loadBalance () {
return ethers.BigNumber.from(
return BigInt(
// A workaround to fix false TypeScript errors
/** @type {string} */ (walletStore.get('balance_0x', '0x0'))
)
}

function loadScheduledRewards () {
return ethers.BigNumber.from(
return BigInt(
// A workaround to fix false TypeScript errors
/** @type {string} */ (walletStore.get('scheduled_rewards', '0x0'))
)
Expand All @@ -257,7 +256,7 @@ async function getSeedPhrase () {
}

/**
* @param {string | ethers.utils.Bytes} message
* @param {string} message
* @returns {Promise<string>}
*/
async function signMessage (message) {
Expand Down
Loading
Loading