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] Account hoisting #88

Merged
merged 16 commits into from
Jan 11, 2024
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
1 change: 1 addition & 0 deletions packages/sdk/src/common/decorators/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export const ConsoleCss: Record<HeadMessage, string> = {
'Views:': 'color: aquamarine',
'Call:': 'color: orange',
'Error:': 'color: red',
'Deprecation:': 'color: red',
'LOG:': 'color: lightblue',
'Cache:': 'color: mediumvioletred',
'Permit:': 'color: lime',
Expand Down
7 changes: 7 additions & 0 deletions packages/sdk/src/common/decorators/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ export const Logger = function (headMessage: HeadMessage = 'LOG:') {
const methodName = String(context.name);

const replacementMethod = function (this: This, ...args: Args): Return {
if (headMessage === 'Deprecation:')
callConsoleMessage.call(
this,
headMessage,
`Method '${methodName}' is being deprecated in the next major version`,
);

callConsoleMessage.call(
this,
headMessage,
Expand Down
3 changes: 2 additions & 1 deletion packages/sdk/src/common/decorators/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ export type HeadMessage =
| 'Permit:'
| 'Events:'
| 'Statistic:'
| 'Rewards:';
| 'Rewards:'
| 'Deprecation:';
5 changes: 4 additions & 1 deletion packages/sdk/src/common/utils/sdk-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ export class SDKError extends Error {

constructor({ code, error = {}, message }: SDKErrorProps) {
super(message);
Object.assign(this, error);
if (error instanceof Error) {
this.cause = error.cause;
this.stack = error.stack;
}
this.code = code ?? ERROR_CODE.UNKNOWN_ERROR;
this.errorMessage = message;
}
Expand Down
238 changes: 233 additions & 5 deletions packages/sdk/src/core/__tests__/core-wallet.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,41 @@
import { test, expect, describe } from '@jest/globals';
import { test, expect, describe, jest } from '@jest/globals';

import { useWeb3Core } from '../../../tests/utils/fixtures/use-core.js';
import { getContract, maxUint256, parseEther } from 'viem';
import {
useRpcCore,
useWeb3Core,
} from '../../../tests/utils/fixtures/use-core.js';
import {
WalletClient,
createWalletClient,
getContract,
http,
maxUint256,
parseEther,
zeroAddress,
} from 'viem';
import { expectAddress } from '../../../tests/utils/expect/expect-address.js';
import { useTestsEnvs } from '../../../tests/utils/fixtures/use-test-envs.js';
import { expectNonNegativeBn } from '../../../tests/utils/expect/expect-bn.js';
import { LIDO_CONTRACT_NAMES } from '../../index.js';
import {
CHAINS,
LIDO_CONTRACT_NAMES,
LidoSDKCore,
LidoSDKStake,
PerformTransactionGasLimit,
PerformTransactionSendTransaction,
VIEM_CHAINS,
} from '../../index.js';
import {
useAccount,
useAltAccount,
} from '../../../tests/utils/fixtures/use-wallet-client.js';
import {
MockTransportCallback,
useMockTransport,
} from '../../../tests/utils/fixtures/use-mock-transport.js';
import { testSpending } from '../../../tests/utils/test-spending.js';
import { expectTxCallback } from '../../../tests/utils/expect/expect-tx-callback.js';
import { usePublicRpcProvider } from '../../../tests/utils/fixtures/use-test-rpc-provider.js';

const permitAbi = [
{
Expand All @@ -25,6 +55,17 @@ const permitAbi = [
},
] as const;

const createCore = (walletClient?: WalletClient) => {
const { chainId } = useTestsEnvs();
const rpcProvider = usePublicRpcProvider();
return new LidoSDKCore({
chainId,
logMode: 'none',
rpcProvider,
web3Provider: walletClient,
});
};

describe('Core Wallet Tests', () => {
const { chainId } = useTestsEnvs();
const web3Core = useWeb3Core();
Expand Down Expand Up @@ -87,7 +128,7 @@ describe('Core Wallet Tests', () => {
expect(provider).toBeDefined();
});

test('account is available', async () => {
test('getWeb3Address works', async () => {
const address = await web3Core.getWeb3Address();
expect(address).toBeDefined();
expectAddress(address);
Expand All @@ -107,3 +148,190 @@ describe('Core Wallet Tests', () => {
await expect(testPermit(false)).resolves.not.toThrow();
});
});

describe('Account hoisting', () => {
const altAccount = useAltAccount();
const { rpcUrl } = useTestsEnvs();

test('useAccount returns from prop address', async () => {
const core = createCore();
const account = await core.useAccount(altAccount.address);
expectAddress(account.address, altAccount.address);
expect(account.type).toBe('json-rpc');
});

test('useAccount returns from prop account', async () => {
const core = createCore();
const account = await core.useAccount(altAccount);
expect(account).toBe(altAccount);
});

test('useAccount returns hoisted account', async () => {
const walletClient = createWalletClient({
account: altAccount,
transport: http(rpcUrl),
});
const core = createCore(walletClient);
const account = await core.useAccount();
expect(account).toBe(altAccount);
});

test('useAccount requests account from web3Provider', async () => {
const mockFn = jest.fn();
const mockTransport = useMockTransport(async (args, originalRequest) => {
mockFn(args.method);
if (args.method === 'eth_requestAccounts') {
return [altAccount.address];
}
return originalRequest();
});

// setup, no account
const walletClient = createWalletClient({
transport: mockTransport,
});
const core = createCore(walletClient);
expect(core.useWeb3Provider().account).toBeUndefined();

// first call, account hoisted
const account = await core.useAccount();
expect(account.address).toBe(altAccount.address);
expect(account.type).toBe('json-rpc');
expect(core.web3Provider?.account).toBe(account);
expect(mockFn).toHaveBeenCalledTimes(1);
expect(mockFn.mock.calls[0]?.[0]).toBe('eth_requestAccounts');

// second call, account reused
const accountReused = await core.useAccount();
expect(accountReused).toBe(account);
expect(mockFn).toHaveBeenCalledTimes(1);
});
});

describe('Perform Transaction', () => {
const { chainId } = useTestsEnvs();
const mockMultisigAddress = useRpcCore().getContractLidoLocator().address;
const account = useAccount();
const value = 100n;
const testHash = '0xaaaaaabbbbbbb';

testSpending('perform transaction works with EOA', async () => {
const mockTransportCallback = jest.fn<MockTransportCallback>((_, next) =>
next(),
);
const core = createCore(
createWalletClient({
account,
chain: VIEM_CHAINS[chainId as CHAINS],
transport: useMockTransport(mockTransportCallback),
}),
);
const stake = new LidoSDKStake({ core });
const rawContract = await stake.getContractStETH();

const mockGetGasLimit = jest.fn<PerformTransactionGasLimit>((options) =>
rawContract.estimateGas.submit([zeroAddress], {
...options,
value,
}),
);
const mockSendTransaction = jest.fn<PerformTransactionSendTransaction>(
(options) =>
rawContract.write.submit([zeroAddress], { ...options, value }),
);
const mockTxCallback = jest.fn();

const txResult = await core.performTransaction({
getGasLimit: mockGetGasLimit,
sendTransaction: mockSendTransaction,
callback: mockTxCallback,
});
const gasLimit = await mockGetGasLimit.mock.results[0]?.value;
expectTxCallback(mockTxCallback, txResult);
expect(mockGetGasLimit).toHaveBeenCalledWith({
account,
chain: core.chain,
gas: undefined,
maxFeePerGas: expect.any(BigInt),
maxPriorityFeePerGas: expect.any(BigInt),
});
expect(mockSendTransaction).toHaveBeenCalledWith({
account,
chain: core.chain,
gas: gasLimit,
maxFeePerGas: mockGetGasLimit.mock.calls[0]?.[0]?.maxFeePerGas,
maxPriorityFeePerGas:
mockGetGasLimit.mock.calls[0]?.[0].maxPriorityFeePerGas,
});

expect(mockTransportCallback).toHaveBeenLastCalledWith(
{
method: 'eth_sendRawTransaction',
params: expect.any(Array),
},
expect.anything(),
);
});

testSpending('perform transaction works with Multisig', async () => {
const mockTransportCallback = jest.fn<MockTransportCallback>(
async (args, next) => {
if (args.method === 'eth_sendTransaction') {
return testHash;
}
return next();
},
);
const core = createCore(
createWalletClient({
account: mockMultisigAddress,
chain: VIEM_CHAINS[chainId as CHAINS],
transport: useMockTransport(mockTransportCallback),
}),
);

const stake = new LidoSDKStake({ core });
const rawContract = await stake.getContractStETH();

const mockGetGasLimit = jest.fn<PerformTransactionGasLimit>((options) =>
rawContract.estimateGas.submit([zeroAddress], {
...options,
value,
}),
);
const mockSendTransaction = jest.fn<PerformTransactionSendTransaction>(
(options) =>
rawContract.write.submit([zeroAddress], { ...options, value }),
);
const mockTxCallback = jest.fn();

const txResult = await core.performTransaction({
getGasLimit: mockGetGasLimit,
sendTransaction: mockSendTransaction,
callback: mockTxCallback,
});

expect(txResult.hash).toBe(testHash);

expectTxCallback(mockTxCallback, { ...txResult, isMultisig: true });
expect(mockGetGasLimit).not.toHaveBeenCalled();
expect(mockSendTransaction).toHaveBeenCalledWith({
chain: core.chain,
account: { address: mockMultisigAddress, type: 'json-rpc' },
gas: 21000n,
maxFeePerGas: 1n,
maxPriorityFeePerGas: 1n,
nonce: 1,
});

// first call is chainId cross-check
expect(mockTransportCallback).toHaveBeenCalledTimes(2);
expect(mockTransportCallback).toHaveBeenLastCalledWith(
{
method: 'eth_sendTransaction',
params: expect.any(Array),
},
expect.anything(),
);
});
});
6 changes: 3 additions & 3 deletions packages/sdk/src/core/__tests__/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ describe('Core Tests', () => {
expect(core.web3Provider).toBeUndefined();
});

test('Core accepts only valid arguments', () => {
void expectSDKError(
test('Core accepts only valid arguments', async () => {
await expectSDKError(
() =>
new LidoSDKCore({
chainId: chainId,
Expand All @@ -38,7 +38,7 @@ describe('Core Tests', () => {
ERROR_CODE.INVALID_ARGUMENT,
);

void expectSDKError(
await expectSDKError(
() =>
new LidoSDKCore({
chainId: 100 as any,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ describe('getLatestBlockToTimestamp', () => {

// eslint-disable-next-line jest/no-disabled-tests
test.skip('throws error at invalid timestamp', async () => {
// TODO: research for some reason expectSDKError does not work here
// TODO: research for some reason jest prints this error and abruptly exits
await expect(core.getLatestBlockToTimestamp(0n)).rejects.toThrow(
'No blocks at this timestamp',
);
Expand Down
Loading
Loading