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

Feature: Add send advanced tab, private key export and provider caching #33

Merged
merged 3 commits into from
Sep 5, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 2 additions & 1 deletion background/lib/erc20.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
import logger from "./logger"
import SerialFallbackProvider from "../services/chain/serial-fallback-provider"
import { ShardToMulticall, getShardFromAddress } from "../constants"
import { get } from "lodash"

export const ERC20_FUNCTIONS = {
allowance: FunctionFragment.from(
Expand Down Expand Up @@ -202,7 +203,7 @@ export const getTokenBalances = async (
CHAIN_SPECIFIC_MULTICALL_CONTRACT_ADDRESSES[network.chainID] ||
MULTICALL_CONTRACT_ADDRESS
if (network.isQuai) {
multicallAddress = ShardToMulticall(globalThis.main.SelectedShard, network)
multicallAddress = ShardToMulticall(getShardFromAddress(address), network)
}

const contract = new quais.Contract(
Expand Down
4 changes: 2 additions & 2 deletions background/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -965,9 +965,9 @@ export default class Main extends BaseService<never> {
const signedTransactionResult =
await this.signingService.signTransaction(request, accountSigner)
await this.store.dispatch(transactionSigned(signedTransactionResult))
transactionConstructionSliceEmitter.emit("signedTransactionResult",
setTimeout(() => transactionConstructionSliceEmitter.emit("signedTransactionResult",
signedTransactionResult
)
), 1000) // could check broadcastOnSign here and broadcast if false but this is a hacky solution (could result in tx broadcasted twice)
Denis2626 marked this conversation as resolved.
Show resolved Hide resolved
this.analyticsService.sendAnalyticsEvent(
AnalyticsEvent.TRANSACTION_SIGNED,
{
Expand Down
15 changes: 12 additions & 3 deletions background/redux-slices/utils/contract-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import TallyWindowProvider from "@tallyho/window-provider"
import { Contract, ethers, ContractInterface } from "ethers"
import Emittery from "emittery"
import TallyWeb3Provider from "../../tally-provider"
import { SECOND } from "../../constants"

type InternalProviderPortEvents = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down Expand Up @@ -53,8 +54,16 @@ export const getSignerAddress = async (): Promise<string> => {
return signerAddress
}

var latestBlockNumber = 0
var latestAsk = 0
export const getCurrentTimestamp = async (): Promise<number> => {
const provider = getProvider()
const { timestamp } = await provider.getBlock(provider.getBlockNumber())
return timestamp
if(latestAsk + 10 * SECOND < Date.now()) {
const provider = getProvider()
const { timestamp } = await provider.getBlock(provider.getBlockNumber())
latestBlockNumber = timestamp
latestAsk = Date.now()
return timestamp
} else {
return latestBlockNumber
}
}
3 changes: 3 additions & 0 deletions background/services/chain/asset-data-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,12 @@ export default class AssetDataHelper {
addressOnNetwork: AddressOnNetwork,
smartContractAddresses?: HexString[]
): Promise<SmartContractAmount[]> {
let prevShard = globalThis.main.GetShard()
globalThis.main.SetShard(getShardFromAddress(addressOnNetwork.address))
const provider = this.providerTracker.providerForNetwork(
addressOnNetwork.network
)
globalThis.main.SetShard(prevShard)
if (typeof provider === "undefined") {
return []
}
Expand Down
16 changes: 8 additions & 8 deletions background/services/chain/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {
TransactionReceipt,
TransactionResponse,
} from "@ethersproject/providers"
import { BigNumber, ethers, utils } from "ethers"
import { Logger, UnsignedTransaction } from "ethers/lib/utils"
} from "@quais/providers"
import { BigNumber, quais, utils } from "quais"
import { Logger, UnsignedTransaction } from "quais/lib/utils"
import logger from "../../lib/logger"
import getBlockPrices from "../../lib/gas"
import { HexString, NormalizedEVMAddress, UNIXTime } from "../../types"
Expand Down Expand Up @@ -97,9 +97,9 @@ const NETWORK_POLLING_TIMEOUT = MINUTE * 2.05
// mempool) reasons.
const TRANSACTION_CHECK_LIFETIME_MS = 10 * HOUR

const GAS_POLLS_PER_PERIOD = 4 // 4 times per minute
const GAS_POLLS_PER_PERIOD = 1 // 1 time per 5 minutes

const GAS_POLLING_PERIOD = 1 // 1 minute
const GAS_POLLING_PERIOD = 5 // 5 minutes

// Maximum number of transactions with priority.
// Transactions that will be retrieved before others for one account.
Expand Down Expand Up @@ -254,7 +254,7 @@ export default class ChainService extends BaseService<Events> {
super({
queuedTransactions: {
schedule: {
delayInMinutes: 0.5,
delayInMinutes: 1,
periodInMinutes: 1,
},
handler: () => {
Expand Down Expand Up @@ -633,7 +633,7 @@ export default class ChainService extends BaseService<Events> {
maxFeePerGas: maxFeePerGas ?? 0n,
maxPriorityFeePerGas: maxPriorityFeePerGas ?? 0n,
input: input ?? null,
type: 2 as const,
type: network.isQuai ? 0 as const : 2 as const,
network,
chainID: network.chainID,
nonce,
Expand Down Expand Up @@ -1174,7 +1174,7 @@ export default class ChainService extends BaseService<Events> {

const provider = await this.providerForNetworkOrThrow(network)

const GasOracle = new ethers.Contract(
const GasOracle = new quais.Contract(
OPTIMISM_GAS_ORACLE_ADDRESS,
OPTIMISM_GAS_ORACLE_ABI,
provider
Expand Down
1 change: 1 addition & 0 deletions background/services/chain/serial-fallback-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,7 @@ export default class SerialFallbackProvider extends QuaisJsonRpcProvider {
)
) {
if (this.shouldSendMessageOnNextProvider(messageId)) {
console.trace()
// If there is another provider to try - try to send the message on that provider
if (this.currentProviderIndex + 1 < this.providerCreators.length) {
return await this.attemptToSendMessageOnNewProvider(messageId)
Expand Down
2 changes: 1 addition & 1 deletion background/services/chain/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
import {
Transaction as EthersTransaction,
UnsignedTransaction,
} from "@ethersproject/transactions"
} from "@quais/transactions"

import {
AnyEVMTransaction,
Expand Down
16 changes: 15 additions & 1 deletion background/services/enrichment/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import {
getERC20LogsForAddresses,
} from "./utils"
import { enrichAddressOnNetwork } from "./addresses"
import { OPTIMISM } from "../../constants"
import { OPTIMISM, SECOND } from "../../constants"
import { parseLogsForWrappedDepositsAndWithdrawals } from "../../lib/wrappedAsset"
import {
ERC20TransferLog,
Expand Down Expand Up @@ -183,6 +183,8 @@ export async function annotationsFromLogs(
* Resolve an annotation for a partial transaction request, or a pending
* or mined transaction.
*/
var latestWorkedAsk = 0
var numAsks = 0
export default async function resolveTransactionAnnotation(
chainService: ChainService,
indexingService: IndexingService,
Expand All @@ -198,6 +200,7 @@ export default async function resolveTransactionAnnotation(
}),
desiredDecimals: number
): Promise<TransactionAnnotation> {

const assets = await indexingService.getCachedAssets(network)

// By default, annotate all requests as contract interactions, unless they
Expand All @@ -216,6 +219,17 @@ export default async function resolveTransactionAnnotation(
)?.metadata?.logoURL,
}

if(numAsks > 10 && latestWorkedAsk + 5 * SECOND > Date.now()) {
// Requesting too often
console.log("Requesting tx annotations too often, skipping")
return txAnnotation
} else if (numAsks > 10 && latestWorkedAsk + 5 * SECOND < Date.now()) {
// Reset
numAsks = 0
}
numAsks++
latestWorkedAsk = Date.now()

let block: AnyEVMBlock | undefined

const {
Expand Down
4 changes: 2 additions & 2 deletions background/services/indexing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ import {
const FAST_TOKEN_REFRESH_BLOCK_RANGE = 10
// The number of ms to coalesce tokens whose balances are known to have changed
// before balance-checking them.
const ACCELERATED_TOKEN_REFRESH_TIMEOUT = 300
const ACCELERATED_TOKEN_REFRESH_TIMEOUT = 3000

interface Events extends ServiceLifecycleEvents {
accountsWithBalances: {
Expand Down Expand Up @@ -517,7 +517,7 @@ export default class IndexingService extends BaseService<Events> {

const balances = await this.chainService.assetData.getTokenBalances(
addressNetwork,
smartContractAssets?.map(({ contractAddress }) => contractAddress)
smartContractAssets?.map(({ contractAddress }) => getShardFromAddress(contractAddress) == getShardFromAddress(addressNetwork.address) ? contractAddress : "")
)

const listedAssetByAddress = (smartContractAssets ?? []).reduce<{
Expand Down
16 changes: 9 additions & 7 deletions background/services/internal-ethereum-provider/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { TransactionRequest as EthersTransactionRequest } from "@ethersproject/abstract-provider"
import { serialize as serializeEthersTransaction } from "@ethersproject/transactions"
import { TransactionRequest as EthersTransactionRequest } from "@quais/abstract-provider"
import { serialize as serializeEthersTransaction } from "@quais/transactions"

import {
EIP1193Error,
Expand Down Expand Up @@ -384,15 +384,15 @@ export default class InternalEthereumProviderService extends BaseService<Events>
async getCurrentOrDefaultNetworkForOrigin(
origin: string
): Promise<EVMNetwork> {
/*const currentNetwork = await this.db.getCurrentNetworkForOrigin(origin)
const currentNetwork = await this.db.getCurrentNetworkForOrigin(origin)
if (!currentNetwork) {
// If this is a new dapp or the dapp has not implemented wallet_switchEthereumChain
// use the default network.
const defaultNetwork = await this.getCurrentInternalNetwork()
return defaultNetwork
}
return currentNetwork*/
return QUAI_NETWORK
return currentNetwork
//return QUAI_NETWORK
}

async removePrefererencesForChain(chainId: string): Promise<void> {
Expand All @@ -415,9 +415,11 @@ export default class InternalEthereumProviderService extends BaseService<Events>
throw new Error("Transactions must have a from address for signing.")
}

const currentNetwork = await this.getCurrentOrDefaultNetworkForOrigin(
/*let currentNetwork = await this.getCurrentOrDefaultNetworkForOrigin(
origin
)
)*/
const currentNetwork = globalThis.main.store.getState().ui.selectedAccount.network


const isRootstock = currentNetwork.chainID === ROOTSTOCK.chainID

Expand Down
5 changes: 3 additions & 2 deletions background/services/name/resolvers/ens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export default function ensResolverFor(
address,
network,
}: AddressOnNetwork): Promise<NameOnNetwork | undefined> {
return undefined
const name = await chainService
// Hard-coded to ETHEREUM to support ENS names on ETH L2's.
.providerForNetwork(QUAI_NETWORK)
Expand All @@ -109,10 +110,10 @@ export default function ensResolverFor(
return undefined
}

return {
/*return {
name,
network,
}
}*/
},
}
}
1 change: 1 addition & 0 deletions background/services/name/resolvers/rns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export default function rnsResolver(): NameResolver<"RNS"> {
address,
network,
}: AddressOnNetwork): Promise<NameOnNetwork | undefined> {
return undefined
const reverseRecordHash = utils.namehash(
`${stripHexPrefix(address)}.addr.reverse`
)
Expand Down
1 change: 1 addition & 0 deletions background/services/name/resolvers/uns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ export default function unsResolver(): NameResolver<"UNS"> {
address,
network,
}: AddressOnNetwork): Promise<NameOnNetwork | undefined> {
return undefined
// Get all the records associated with the particular ETH address
const data = (await reverseLookupAddress(address))?.data
// Since for a given address you can have multiple UNS records, we just pick the first one
Expand Down
Loading