Skip to content

Commit

Permalink
core: reduce the number of wallet api calls (#522)
Browse files Browse the repository at this point in the history
## Context

In some cases, calls to the wallet API can take a long time (>100ms) so
the
library should make as few of them as possible to minimize the time it
takes to
connect to a wallet.

## Changes in this Pull Request

- Reduce the calls to `wallet_requestAccounts` used to check if the
wallet is locked.
- Update the `address` property in the `useAccount` hook without waiting
for the `account` object to be fully built.

## Test Plan

Use the `account` demo to test that less calls are made to the wallet.
You can
set a breakpoint in the `InjectedConnector.request` function.
  • Loading branch information
fracek authored Oct 29, 2024
2 parents 5c0029b + 381ee0b commit 6993533
Show file tree
Hide file tree
Showing 10 changed files with 86 additions and 42 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "core: reduce the number of wallet api calls",
"packageName": "@starknet-react/core",
"email": "[email protected]",
"dependentChangeType": "patch"
}
3 changes: 2 additions & 1 deletion docs/components/demo/account.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function Account() {
}

function AccountInner() {
const { address, connector } = useAccount();
const { address, connector, account } = useAccount();

return (
<div className="flex flex-col gap-4">
Expand All @@ -20,6 +20,7 @@ function AccountInner() {
{
address: address ?? "Connect wallet first",
connector: connector?.id ?? "Connect wallet first",
account: account ? typeof account : "Connect wallet first",
},
null,
2,
Expand Down
14 changes: 11 additions & 3 deletions packages/chains/package.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
{
"name": "@starknet-react/chains",
"version": "3.0.2",
"version": "3.0.3",
"license": "MIT",
"repository": "apibara/starknet-react",
"homepage": "https://www.starknet-react.com/",
"keywords": ["starknet", "ethereum", "l2"],
"keywords": [
"starknet",
"ethereum",
"l2"
],
"type": "module",
"main": "./src/index.ts",
"exports": "./src/index.ts",
Expand All @@ -18,7 +22,11 @@
"default": "./dist/index.js"
}
},
"files": ["dist", "src", "README.md"]
"files": [
"dist",
"src",
"README.md"
]
},
"scripts": {
"build": "tsup",
Expand Down
14 changes: 11 additions & 3 deletions packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
{
"name": "@starknet-react/core",
"version": "3.0.3",
"version": "3.1.0",
"license": "MIT",
"repository": "apibara/starknet-react",
"homepage": "https://www.starknet-react.com",
"keywords": ["starknet", "ethereum", "l2"],
"keywords": [
"starknet",
"ethereum",
"l2"
],
"type": "module",
"main": "./src/index.ts",
"exports": "./src/index.ts",
Expand All @@ -18,7 +22,11 @@
"default": "./dist/index.js"
}
},
"files": ["dist", "src", "README.md"]
"files": [
"dist",
"src",
"README.md"
]
},
"scripts": {
"build": "tsup",
Expand Down
14 changes: 9 additions & 5 deletions packages/core/src/connectors/injected.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,7 @@ export class InjectedConnector extends Connector {
}

try {
const chainIdHex = await this.request({ type: "wallet_requestChainId" });
const chainId = BigInt(chainIdHex);
return chainId;
return this.requestChainId();
} catch {
throw new ConnectorNotFoundError();
}
Expand All @@ -118,6 +116,7 @@ export class InjectedConnector extends Connector {
provider: ProviderOptions | ProviderInterface,
): Promise<AccountInterface> {
this.ensureWallet();

const locked = await this.isLocked();

if (locked || !this._wallet) {
Expand Down Expand Up @@ -159,7 +158,7 @@ export class InjectedConnector extends Connector {

const [account] = accounts;

const chainId = await this.chainId();
const chainId = await this.requestChainId();
this.emit("connect", { account, chainId });

return {
Expand Down Expand Up @@ -203,6 +202,11 @@ export class InjectedConnector extends Connector {
return accounts.length === 0;
}

private async requestChainId(): Promise<bigint> {
const chainIdHex = await this.request({ type: "wallet_requestChainId" });
return BigInt(chainIdHex);
}

private ensureWallet() {
// biome-ignore lint/suspicious/noExplicitAny: any
const global_object: Record<string, any> = globalThis;
Expand All @@ -222,7 +226,7 @@ export class InjectedConnector extends Connector {
const [account] = accounts;

if (account) {
const chainId = await this.chainId();
const chainId = await this.requestChainId();
this.emit("change", { account, chainId });
} else {
this.emit("disconnect");
Expand Down
17 changes: 4 additions & 13 deletions packages/core/src/context/starknet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ interface StarknetManagerState {
currentChain: Chain;
connectors: Connector[];
currentAddress?: Address;
currentAccount?: AccountInterface;
currentProvider: ProviderInterface;
error?: Error;
}
Expand Down Expand Up @@ -165,17 +164,13 @@ function useStarknetManager({
}

if (address && connectorRef.current) {
const account = await connectorRef.current.account(
state.currentProvider,
);
setState((state) => ({
...state,
currentAddress: address as Address,
currentAccount: account,
}));
}
},
[updateChainAndProvider, state.currentProvider],
[updateChainAndProvider],
);

useEffect(() => {
Expand Down Expand Up @@ -203,14 +198,13 @@ function useStarknetManager({
const { chainId, account: address } = await connector.connect({
chainIdHint: defaultChain.id,
});
const account = await connector.account(state.currentProvider);

if (address !== state.currentAccount?.address) {
if (address !== state.currentAddress) {
connectorRef.current = connector;

setState((state) => ({
...state,
currentAddress: address as Address,
currentAccount: account,
}));
}

Expand All @@ -233,8 +227,7 @@ function useStarknetManager({
},
[
autoConnect,
state.currentAccount,
state.currentProvider,
state.currentAddress,
defaultChain.id,
handleConnectorChange,
updateChainAndProvider,
Expand All @@ -245,7 +238,6 @@ function useStarknetManager({
setState((state) => ({
...state,
currentAddress: undefined,
currentAccount: undefined,
currentProvider: defaultProvider,
currentChain: defaultChain,
}));
Expand Down Expand Up @@ -299,7 +291,6 @@ function useStarknetManager({
}, []);

return {
account: state.currentAccount,
address: state.currentAddress,
provider: state.currentProvider,
chain: state.currentChain,
Expand Down
18 changes: 13 additions & 5 deletions packages/core/src/hooks/use-account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { useStarknetAccount } from "../context/account";
import { useStarknet } from "../context/starknet";
import { getAddress } from "../utils";
import { useConnect } from "./use-connect";
import { useProvider } from "./use-provider";

/** Account connection status. */
export type AccountStatus =
Expand Down Expand Up @@ -47,25 +48,32 @@ export type UseAccountResult = {
*/
export function useAccount(): UseAccountResult {
const { connector, chain } = useStarknet();
const { account: connectedAccount, address: connectedAddress } =
useStarknetAccount();
const { provider } = useProvider();
const { address: connectedAddress } = useStarknetAccount();
const [state, setState] = useState<UseAccountResult>({
status: "disconnected",
});

const refreshState = useCallback(async () => {
if (connector && connectedAccount && connectedAddress) {
if (connector && provider && connectedAddress) {
setState({
status: "connected" as const,
connector,
chainId: chain.id,
account: connectedAccount,
account: undefined,
address: getAddress(connectedAddress),
isConnected: true,
isConnecting: false,
isDisconnected: false,
isReconnecting: false,
});

// Lazily build the account since it makes a wallet call to check if the wallet is locked.
connector
.account(provider)
.then((connectedAccount) =>
setState((state) => ({ ...state, account: connectedAccount })),
);
} else {
return setState({
status: "disconnected" as const,
Expand All @@ -79,7 +87,7 @@ export function useAccount(): UseAccountResult {
isReconnecting: false,
});
}
}, [connectedAccount, connector, chain.id, connectedAddress]);
}, [provider, connector, chain.id, connectedAddress]);

useEffect(() => {
refreshState();
Expand Down
14 changes: 11 additions & 3 deletions packages/create-starknet/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "create-starknet",
"version": "3.0.0",
"version": "3.1.0",
"description": "Create starknet apps with one command",
"main": "./dist/index.js",
"type": "module",
Expand All @@ -16,7 +16,11 @@
"bin": {
"create-starknet": "dist/index.js"
},
"keywords": ["starknet", "ethereum", "l2"],
"keywords": [
"starknet",
"ethereum",
"l2"
],
"author": "Yohan Tancrez",
"license": "MIT",
"devDependencies": {
Expand All @@ -27,7 +31,11 @@
"tsup": "^8.0.2",
"typescript": "^5.5.4"
},
"files": ["dist", "src", "README.md"],
"files": [
"dist",
"src",
"README.md"
],
"dependencies": {
"@starknet-react/typescript-config": "workspace:*",
"@types/cross-spawn": "^6.0.2",
Expand Down
17 changes: 13 additions & 4 deletions packages/kakarot/package.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
{
"name": "@starknet-react/kakarot",
"version": "3.0.0",
"version": "3.0.1",
"license": "MIT",
"repository": "apibara/starknet-react",
"homepage": "https://www.starknet-react.com/",
"keywords": ["starknet", "ethereum", "l2", "kakarot"],
"keywords": [
"starknet",
"ethereum",
"l2",
"kakarot"
],
"type": "module",
"main": "./src/index.ts",
"exports": "./src/index.ts",
Expand All @@ -18,7 +23,11 @@
"default": "./dist/index.js"
}
},
"files": ["dist", "src", "README.md"]
"files": [
"dist",
"src",
"README.md"
]
},
"scripts": {
"build": "tsup",
Expand All @@ -35,7 +44,7 @@
},
"dependencies": {
"@starknet-io/types-js": "^0.7.7",
"@starknet-react/chains": "^3.0.2",
"@starknet-react/chains": "^3.0.3",
"@starknet-react/core": "workspace:^",
"mipd": "^0.0.7",
"starknet": "^6.11.0",
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 6993533

Please sign in to comment.