Skip to content

Commit

Permalink
feat: add account rpc tests
Browse files Browse the repository at this point in the history
  • Loading branch information
badurinantun committed Jul 13, 2022
1 parent 2fac438 commit fc3b484
Show file tree
Hide file tree
Showing 6 changed files with 100 additions and 16 deletions.
24 changes: 19 additions & 5 deletions __tests__/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,30 @@ export const getTestProvider = () => {
};

// test account with fee token balance
export const getTestAccount = () => {
const provider = getTestProvider();
export const getTestAccount = (provider = getTestProvider(), isDevnet = false) => {
if (!isDevnet) {
if (!process.env.TEST_ACCOUNT_PRIVATE_KEY) {
throw new Error('TEST_ACCOUNT_PRIVATE_KEY is not set');
}

const testAccountAddress = process.env.TEST_ACCOUNT_ADDRESS || DEFAULT_TEST_ACCOUNT_ADDRESS;
const testAccountPrivateKey =
process.env.TEST_ACCOUNT_PRIVATE_KEY || DEFAULT_TEST_ACCOUNT_PRIVATE_KEY;
if (!process.env.TEST_ACCOUNT_ADDRESS) {
throw new Error('TEST_ACCOUNT_ADDRESS is not set');
}
}

const testAccountAddress = isDevnet
? DEFAULT_TEST_ACCOUNT_ADDRESS
: (process.env.TEST_ACCOUNT_ADDRESS as string);
const testAccountPrivateKey = isDevnet
? DEFAULT_TEST_ACCOUNT_PRIVATE_KEY
: (process.env.TEST_ACCOUNT_PRIVATE_KEY as string);

return new Account(provider, testAccountAddress, ec.getKeyPair(testAccountPrivateKey));
};

export const testIf = (condition: boolean) => (condition ? test : test.skip);
export const describeIf = (condition: boolean) => (condition ? describe : describe.skip);
export const testIfDevnet = testIf(IS_DEVNET);
export const testIfNotDevnet = testIf(!IS_DEVNET);
export const describeIfDevnet = describeIf(IS_DEVNET);
export const describeIfNotDevnet = describeIf(!IS_DEVNET);
58 changes: 56 additions & 2 deletions __tests__/rpcProvider.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { DeployContractResponse, RPCProvider } from '../src';
import { isBN } from 'bn.js';

import { Account, Contract, DeployContractResponse, Provider, RPCProvider } from '../src';
import { toBN } from '../src/utils/number';
import { compileCalldata } from '../src/utils/stark';
import { compiledErc20 } from './fixtures';
import { compiledErc20, describeIfNotDevnet, getTestAccount } from './fixtures';

const { TEST_RPC_URL } = process.env;

Expand Down Expand Up @@ -191,4 +194,55 @@ describe('RPCProvider', () => {
expect(chainId).toBe('0x534e5f474f45524c49');
});
});

describeIfNotDevnet('Account', () => {
let account: Account;
let erc20Address!: string;
let erc20: Contract;

beforeAll(async () => {
const rpcProvider = new Provider({ rpc: { nodeUrl: TEST_RPC_URL } });
account = getTestAccount(rpcProvider, false);
expect(account).toBeInstanceOf(Account);

// Using predeployed contract as RPC node has issues with using recent deployed contracts
erc20Address = '0x649c8b8dbb19009551120c364208bad865f06d4b12ecd3e7109421d8b22968e';
erc20 = new Contract(compiledErc20.abi, erc20Address, provider);

const mintResponse = await account.execute({
contractAddress: erc20Address,
entrypoint: 'mint',
calldata: [account.address, '1000'],
});

await provider.waitForTransaction(mintResponse.transaction_hash);
});

test('estimate fee', async () => {
const { overall_fee } = await account.estimateFee({
contractAddress: erc20Address,
entrypoint: 'transfer',
calldata: [erc20.address, '10'],
});

console.log({ overall_fee });
expect(isBN(overall_fee)).toBe(true);
});

test('execute by wallet owner', async () => {
const { res: before } = await erc20.balance_of(account.address);

const { transaction_hash } = await account.execute({
contractAddress: erc20Address,
entrypoint: 'transfer',
calldata: [erc20.address, '10'],
});

await account.waitForTransaction(transaction_hash);

const { res: after } = await erc20.balance_of(account.address);

expect(toBN(before).sub(toBN(after)).toString(10)).toBe('10');
});
});
});
2 changes: 1 addition & 1 deletion src/account/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export class Account extends Provider implements AccountInterface {

public async estimateFee(
calls: Call | Call[],
{ nonce: providedNonce, blockIdentifier = 'pending' }: EstimateFeeDetails = {}
{ nonce: providedNonce, blockIdentifier }: EstimateFeeDetails = {}
): Promise<EstimateFee> {
const transactions = Array.isArray(calls) ? calls : [calls];
const nonce = providedNonce ?? (await this.getNonce());
Expand Down
4 changes: 2 additions & 2 deletions src/provider/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ export class Provider implements ProviderInterface {

public async getEstimateFee(
invocation: Invocation,
blockIdentifier: BlockIdentifier,
invocationDetails?: InvocationsDetails
blockIdentifier: BlockIdentifier = 'latest', // 'pending' is not working on the RPC node
invocationDetails: InvocationsDetails = {}
): Promise<EstimateFeeResponse> {
return this.provider.getEstimateFee(invocation, blockIdentifier, invocationDetails);
}
Expand Down
25 changes: 20 additions & 5 deletions src/provider/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,14 +130,16 @@ export class RPCProvider implements ProviderInterface {

public async getEstimateFee(
invocation: Invocation,
blockIdentifier: BlockIdentifier = 'pending',
_invocationDetails: InvocationsDetails = {}
blockIdentifier: BlockIdentifier = 'latest',
invocationDetails: InvocationsDetails = {}
): Promise<EstimateFeeResponse> {
return this.fetchEndpoint('starknet_estimateFee', [
{
contract_address: invocation.contractAddress,
entry_point_selector: getSelectorFromName(invocation.entrypoint),
calldata: parseCalldata(invocation.calldata),
signature: bigNumberishArrayToDecimalStringArray(invocation.signature || []),
version: toHex(toBN(invocationDetails?.version || 0)),
},
blockIdentifier,
]).then(this.responseParser.parseFeeEstimateResponse);
Expand Down Expand Up @@ -179,15 +181,26 @@ export class RPCProvider implements ProviderInterface {
functionInvocation: Invocation,
details: InvocationsDetails
): Promise<InvokeFunctionResponse> {
console.log([
{
contract_address: functionInvocation.contractAddress,
entry_point_selector: getSelectorFromName(functionInvocation.entrypoint),
calldata: parseCalldata(functionInvocation.calldata),
},
bigNumberishArrayToDecimalStringArray(functionInvocation.signature || []),
toHex(toBN(details.maxFee || 0)),
toHex(toBN(details.version || 0)),
]);

return this.fetchEndpoint('starknet_addInvokeTransaction', [
{
contract_address: functionInvocation.contractAddress,
entry_point_selector: getSelectorFromName(functionInvocation.entrypoint),
calldata: parseCalldata(functionInvocation.calldata),
},
functionInvocation.signature,
details.maxFee,
details.version,
bigNumberishArrayToDecimalStringArray(functionInvocation.signature || []),
toHex(toBN(details.maxFee || 0)),
toHex(toBN(details.version || 0)),
]).then(this.responseParser.parseInvokeFunctionResponse);
}

Expand Down Expand Up @@ -221,6 +234,7 @@ export class RPCProvider implements ProviderInterface {
try {
// eslint-disable-next-line no-await-in-loop
const res = await this.getTransactionReceipt(txHash);
console.log({ res });

if (successStates.includes(res.status)) {
onchain = true;
Expand All @@ -231,6 +245,7 @@ export class RPCProvider implements ProviderInterface {
throw error;
}
} catch (error: unknown) {
console.log(error);
if (error instanceof Error && errorStates.includes(error.message)) {
throw error;
}
Expand Down
3 changes: 2 additions & 1 deletion src/utils/responseParser/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
InvokeFunctionResponse,
RPC,
} from '../../types';
import { toBN } from '../number';
import { ResponseParser } from '.';

export class RPCResponseParser extends ResponseParser {
Expand Down Expand Up @@ -68,7 +69,7 @@ export class RPCResponseParser extends ResponseParser {

public parseFeeEstimateResponse(res: RPC.EstimateFeeResponse): EstimateFeeResponse {
return {
overall_fee: res.overall_fee,
overall_fee: toBN(res.overall_fee),
};
}

Expand Down

0 comments on commit fc3b484

Please sign in to comment.