Skip to content
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { Box, Button } from '@chakra-ui/react';
import { createCoinbaseWalletSDK } from '@coinbase/wallet-sdk';
import { useCallback, useState } from 'react';

type GetSubAccountsProps = {
sdk: ReturnType<typeof createCoinbaseWalletSDK>;
};

export function GetSubAccounts({ sdk }: GetSubAccountsProps) {
const [subAccounts, setSubAccounts] = useState<{
subAccounts: {
address: string;
factory: string;
factoryCalldata: string;
}[];
}>();
const [error, setError] = useState<string>();
const [isLoading, setIsLoading] = useState(false);

const handleGetSubAccounts = useCallback(async () => {
if (!sdk) {
return;
}

setIsLoading(true);
try {
const provider = sdk.getProvider();
const accounts = await provider.request({
method: 'eth_requestAccounts',
}) as string[];
if (accounts.length < 2) {
throw new Error('Create a sub account first by clicking the Add Address button');
}
const response = await provider.request({
method: 'wallet_getSubAccounts',
params: [{
account: accounts[1],
domain: window.location.origin,
}],
});

console.info('getSubAccounts response', response);
setSubAccounts(response as { subAccounts: { address: string; factory: string; factoryCalldata: string; }[] });
} catch (error) {
console.error('Error getting sub accounts:', error);
setError(error instanceof Error ? error.message : 'Unknown error');
} finally {
setIsLoading(false);
}
}, [sdk]);

return (
<>
<Button w="full" onClick={handleGetSubAccounts} isLoading={isLoading} loadingText="Getting Sub Accounts...">
Get Sub Accounts
</Button>
{subAccounts && (
<Box
as="pre"
w="full"
p={2}
bg="gray.900"
borderRadius="md"
border="1px solid"
borderColor="gray.700"
overflow="auto"
whiteSpace="pre-wrap"
>
{JSON.stringify(subAccounts, null, 2)}
</Box>
)}
{error && (
<Box
as="pre"
w="full"
p={2}
bg="red.900"
borderRadius="md"
border="1px solid"
borderColor="red.700"
overflow="auto"
whiteSpace="pre-wrap"
>
{error}
</Box>
)}
</>
);
}
2 changes: 2 additions & 0 deletions examples/testapp/src/pages/add-sub-account/index.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { AddSubAccount } from './components/AddSubAccount';
import { AddSubAccountWithoutKeys } from './components/AddSubAccountWithoutKeys';
import { Connect } from './components/Connect';
import { GenerateNewSigner } from './components/GenerateNewSigner';
import { GetSubAccounts } from './components/GetSubAccounts';
import { GrantSpendPermission } from './components/GrantSpendPermission';
import { PersonalSign } from './components/PersonalSign';
import { SendCalls } from './components/SendCalls';
Expand Down Expand Up @@ -81,6 +82,7 @@ export default function SubAccounts() {
onAddSubAccount={setSubAccountAddress}
signerFn={getSubAccountSigner}
/>
<GetSubAccounts sdk={sdk} />
<AddSubAccountWithoutKeys
sdk={sdk}
onAddSubAccount={setSubAccountAddress}
Expand Down
70 changes: 70 additions & 0 deletions packages/wallet-sdk/src/core/rpc/wallet_getSubAccount.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest';

import {
GetSubAccountsRequest,
GetSubAccountsResponse,
GetSubAccountsResponseItem,
} from './wallet_getSubAccount.js';

describe('wallet_getSubAccounts schema', () => {
it('should have correct request type structure', () => {
const request: GetSubAccountsRequest = {
account: '0x742C4d6c2B4ABE65a3A3B0A4B2Ed8B6a67c2E3f1',
domain: 'example.com',
};

expect(request.account).toBeDefined();
expect(request.domain).toBeDefined();
expect(typeof request.account).toBe('string');
expect(typeof request.domain).toBe('string');
});

it('should have correct response item type structure', () => {
const responseItem: GetSubAccountsResponseItem = {
address: '0x742C4d6c2B4ABE65a3A3B0A4B2Ed8B6a67c2E3f1',
factory: '0x4e59b44847b379578588920cA78FbF26c0B4956C',
factoryData: '0x1234567890abcdef',
};

expect(responseItem.address).toBeDefined();
expect(responseItem.factory).toBeDefined();
expect(responseItem.factoryData).toBeDefined();
expect(typeof responseItem.address).toBe('string');
expect(typeof responseItem.factory).toBe('string');
expect(typeof responseItem.factoryData).toBe('string');
});

it('should have correct response type structure', () => {
const response: GetSubAccountsResponse = {
subAccounts: [
{
address: '0x742C4d6c2B4ABE65a3A3B0A4B2Ed8B6a67c2E3f1',
factory: '0x4e59b44847b379578588920cA78FbF26c0B4956C',
factoryData: '0x1234567890abcdef',
},
{
address: '0x8ba1f109551bD432803012645Hac136c5e84F31D',
factory: '0x5FbDB2315678afecb367f032d93F642f64180aa3',
factoryData: '0xabcdef1234567890',
},
],
};

expect(response.subAccounts).toBeDefined();
expect(Array.isArray(response.subAccounts)).toBe(true);
expect(response.subAccounts.length).toBe(2);
expect(response.subAccounts[0]).toHaveProperty('address');
expect(response.subAccounts[0]).toHaveProperty('factory');
expect(response.subAccounts[0]).toHaveProperty('factoryData');
});

it('should allow empty subAccounts array', () => {
const response: GetSubAccountsResponse = {
subAccounts: [],
};

expect(response.subAccounts).toBeDefined();
expect(Array.isArray(response.subAccounts)).toBe(true);
expect(response.subAccounts.length).toBe(0);
});
});
16 changes: 16 additions & 0 deletions packages/wallet-sdk/src/core/rpc/wallet_getSubAccount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Address, Hex } from 'viem';

export type GetSubAccountsRequest = {
account: Address;
domain: string;
};

export type GetSubAccountsResponseItem = {
address: Address;
factory: Address;
factoryData: Hex;
};

export type GetSubAccountsResponse = {
subAccounts: GetSubAccountsResponseItem[];
};
28 changes: 27 additions & 1 deletion packages/wallet-sdk/src/sign/scw/SCWSigner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { RPCResponse } from ':core/message/RPCResponse.js';
import { AppMetadata, ProviderEventCallback, RequestArguments } from ':core/provider/interface.js';
import { FetchPermissionsResponse } from ':core/rpc/coinbase_fetchSpendPermissions.js';
import { WalletConnectRequest, WalletConnectResponse } from ':core/rpc/wallet_connect.js';
import { GetSubAccountsResponse } from ':core/rpc/wallet_getSubAccount.js';
import {
logHandshakeCompleted,
logHandshakeError,
Expand Down Expand Up @@ -179,7 +180,7 @@ export class SCWSigner implements Signer {
this.callback?.('connect', { chainId: numberToHex(this.chain.id) });
return this.accounts;
}
case 'wallet_switchEthereumChain': {
case 'wallet_switchEthereumChain': {
assertParamsChainId(request.params);
this.chain.id = Number(request.params[0].chainId);
return;
Expand Down Expand Up @@ -280,6 +281,31 @@ export class SCWSigner implements Signer {
return this.sendRequestToPopup(modifiedRequest);
}
// Sub Account Support
case 'wallet_getSubAccounts': {
const subAccount = store.subAccounts.get();
if (subAccount?.address) {
return {
subAccounts: [subAccount],
};
}

if (!this.chain.rpcUrl) {
throw standardErrors.rpc.internal('No RPC URL set for chain');
}
Comment on lines +292 to +294
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I probably missed the design reviews for getSubAccounts but should the RPC take a chainID?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

current BE implementation dedupes them on network so only one sub account is returned per address so chain ID is not required. The current approach is that sub accounts will feel cross-chain as the SDK/keys will perform JIT sub account deployments for crosschain transactions, and also perform JIT signer updates if the local signer is not on a given chain. We can revisit if we need to provide explicit chain id querying here in the future as well

const response = await fetchRPCRequest(request, this.chain.rpcUrl) as GetSubAccountsResponse;
assertArrayPresence(response.subAccounts, 'subAccounts');
if (response.subAccounts.length > 0) {
// cache the sub account
assertSubAccount(response.subAccounts[0]);
const subAccount = response.subAccounts[0];
store.subAccounts.set({
address: subAccount.address,
factory: subAccount.factory,
factoryData: subAccount.factoryData,
});
}
return response;
}
case 'wallet_addSubAccount':
return this.addSubAccount(request);
case 'coinbase_fetchPermissions': {
Expand Down