Skip to content

Commit

Permalink
feat: remove deprecated compileCalldata
Browse files Browse the repository at this point in the history
  • Loading branch information
tabaktoni committed Apr 25, 2023
1 parent e4fcf24 commit e5adca4
Show file tree
Hide file tree
Showing 16 changed files with 71 additions and 96 deletions.
6 changes: 3 additions & 3 deletions __tests__/cairo1.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,19 @@ describeIfDevnetSequencer('Cairo 1', () => {
describe('Sequencer API', () => {
const provider = getTestProvider() as SequencerProvider;
const account = getTestAccount(provider);
const classHash: any = '0x3e2e625998f89befe4d429d5d958275f86421310bfb00440c2431140e8c90ba';
let classHash: any; // = '0x3e2e625998f89befe4d429d5d958275f86421310bfb00440c2431140e8c90ba';
let contractAddress: any;
let declareV2Tx: any;
let cairo1Contract: Contract;
initializeMatcher(expect);

beforeAll(async () => {
/* declareV2Tx = await account.declare({
declareV2Tx = await account.declare({
contract: compiledHelloSierra,
casm: compiledHelloSierraCasm,
});
classHash = declareV2Tx.class_hash;
await provider.waitForTransaction(declareV2Tx.transaction_hash); */
await provider.waitForTransaction(declareV2Tx.transaction_hash);
const { transaction_hash, contract_address } = await account.deploy({ classHash });
[contractAddress] = contract_address;
await provider.waitForTransaction(transaction_hash);
Expand Down
13 changes: 6 additions & 7 deletions __tests__/contract.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { Contract, ContractFactory, json, stark } from '../src';
import { Contract, ContractFactory, RawArgs, json, stark } from '../src';
import { CallData } from '../src/utils/calldata';
import { felt, tuple, uint256 } from '../src/utils/calldata/cairo';
import { getSelectorFromName } from '../src/utils/hash';
import { BigNumberish, hexToDecimalString, toBigInt } from '../src/utils/num';
import { encodeShortString } from '../src/utils/shortString';
import { compileCalldata } from '../src/utils/stark';
import { uint256ToBN } from '../src/utils/uint256';
import {
compiledErc20,
Expand Down Expand Up @@ -76,12 +75,12 @@ describe('contract module', () => {
erc20Contract.address,
getSelectorFromName('balanceOf'),
Object.keys(args1).length,
...compileCalldata(args1),
...CallData.compile(args1),

erc20Contract.address,
getSelectorFromName('decimals'),
Object.keys(args2).length,
...compileCalldata(args2),
...CallData.compile(args2),
];
const { block_number, result } = await multicallContract.aggregate(calls);
expect(BigInt(block_number));
Expand Down Expand Up @@ -210,7 +209,7 @@ describe('contract module', () => {
test('deployment of new contract', async () => {
const factory = new ContractFactory(compiledErc20, classHash, account);
const erc20 = await factory.deploy(
compileCalldata({
CallData.compile({
name: encodeShortString('Token'),
symbol: encodeShortString('ERC20'),
recipient: wallet,
Expand All @@ -221,7 +220,7 @@ describe('contract module', () => {
test('wait for deployment transaction', async () => {
const factory = new ContractFactory(compiledErc20, classHash, account);
const contract = await factory.deploy(
compileCalldata({
CallData.compile({
name: encodeShortString('Token'),
symbol: encodeShortString('ERC20'),
recipient: wallet,
Expand Down Expand Up @@ -326,7 +325,7 @@ describe('Complex interaction', () => {
});

test('callData compile', async () => {
const newCalldata = {
const newCalldata: RawArgs = {
name: 'TokenMTK',
symbol: 'MTK',
decimals: 18,
Expand Down
10 changes: 4 additions & 6 deletions __tests__/defaultProvider.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BlockNumber, GetBlockResponse, LibraryError, Provider, stark } from '../src';
import { BlockNumber, CallData, GetBlockResponse, LibraryError, Provider, stark } from '../src';
import { toBigInt } from '../src/utils/num';
import { encodeShortString } from '../src/utils/shortString';
import {
Expand All @@ -10,8 +10,6 @@ import {
} from './fixtures';
import { initializeMatcher } from './schema';

const { compileCalldata } = stark;

const testProvider = new Provider(getTestProvider());

describe('defaultProvider', () => {
Expand Down Expand Up @@ -133,7 +131,7 @@ describe('defaultProvider', () => {
testProvider.callContract({
contractAddress: erc20ContractAddress,
entrypoint: 'balanceOf',
calldata: compileCalldata({
calldata: CallData.compile({
user: '0x9ff64f4ab0e1fe88df4465ade98d1ea99d5732761c39279b8e1374fa943e9b',
}),
})
Expand All @@ -146,7 +144,7 @@ describe('defaultProvider', () => {
.callContract({
contractAddress: erc20ContractAddress,
entrypoint: 'balanceOf',
calldata: compileCalldata({
calldata: CallData.compile({
user: wallet,
}),
})
Expand All @@ -161,7 +159,7 @@ describe('defaultProvider', () => {
testProvider.callContract({
contractAddress: erc20ContractAddress,
entrypoint: 'non_existent_entrypoint',
calldata: compileCalldata({
calldata: CallData.compile({
user: '0xdeadbeef',
}),
})
Expand Down
16 changes: 7 additions & 9 deletions __tests__/utils/stark.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import fs from 'fs';

import { RawArgs, json, stark } from '../../src';
import { CallData, RawArgs, json, stark } from '../../src';
import { toBigInt, toHex } from '../../src/utils/num';
import { compiledOpenZeppelinAccount } from '../fixtures';

const compiledAccount = json.parse(fs.readFileSync('./__mocks__/Account.json').toString('ascii'));
const compiledAccount = compiledOpenZeppelinAccount;

describe('stark', () => {
describe('compressProgram()', () => {
Expand All @@ -23,11 +22,11 @@ describe('stark', () => {
});
});

describe('compileCalldata() ', () => {
describe('CallData.compile() ', () => {
test('compiles BigNumberish[] calldata', () => {
const callData = ['0x000', 2n, 10000];

const compiled = stark.compileCalldata(callData);
const compiled = CallData.compile(callData);

expect(compiled).toEqual(['0', '2', '10000']);
});
Expand All @@ -40,15 +39,14 @@ describe('stark', () => {
d: [1n, 2n, '0x3'],
};

const compiled = stark.compileCalldata(callData);
const compiled = CallData.compile(callData);

expect(compiled).toEqual(['0', '2', '10000', '3', '1', '2', '3']);
});

test('compiles Struct type calldata', () => {
const calldata: RawArgs = {
a: {
type: 'struct',
x: 1n,
y: 2n,
z: 3n,
Expand All @@ -57,7 +55,7 @@ describe('stark', () => {
c: ['1', '2', toBigInt(3), toHex(4)],
};

const compiled = stark.compileCalldata(calldata);
const compiled = CallData.compile(calldata);

expect(compiled).toEqual(['1', '2', '3', '10000000000', '4', '1', '2', '3', '4']);
});
Expand Down
14 changes: 5 additions & 9 deletions src/account/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
UniversalDeployerContractPayload,
} from '../types';
import { EstimateFeeBulk, TransactionSimulation } from '../types/account';
import { CallData } from '../utils/calldata';
import { extractContractHashes, isSierra } from '../utils/contract';
import { starkCurve } from '../utils/ec';
import { parseUDCEvent } from '../utils/events';
Expand All @@ -44,12 +45,7 @@ import {
} from '../utils/hash';
import { BigNumberish, toBigInt, toCairoBool } from '../utils/num';
import { parseContract } from '../utils/provider';
import {
compileCalldata,
estimatedFeeToMaxFee,
formatSignature,
randomAddress,
} from '../utils/stark';
import { estimatedFeeToMaxFee, formatSignature, randomAddress } from '../utils/stark';
import { getExecuteCalldata } from '../utils/transaction';
import { TypedData, getMessageHash } from '../utils/typedData';
import { AccountInterface } from './interface';
Expand Down Expand Up @@ -372,7 +368,7 @@ export class Account extends Provider implements AccountInterface {
constructorCalldata = [],
} = it as UniversalDeployerContractPayload;

const compiledConstructorCallData = compileCalldata(constructorCalldata);
const compiledConstructorCallData = CallData.compile(constructorCalldata);
const deploySalt = salt ?? randomAddress();

return {
Expand Down Expand Up @@ -497,7 +493,7 @@ export class Account extends Provider implements AccountInterface {
await this.callContract({
contractAddress: this.address,
entrypoint: 'isValidSignature',
calldata: compileCalldata({
calldata: CallData.compile({
hash: toBigInt(hash).toString(),
signature: formatSignature(signature),
}),
Expand Down Expand Up @@ -613,7 +609,7 @@ export class Account extends Provider implements AccountInterface {
unique = true,
constructorCalldata = [],
} = it as UniversalDeployerContractPayload;
const compiledConstructorCallData = compileCalldata(constructorCalldata);
const compiledConstructorCallData = CallData.compile(constructorCalldata);

return {
contractAddress: UDC.ADDRESS,
Expand Down
6 changes: 3 additions & 3 deletions src/provider/starknetId.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CallData } from '../utils/calldata';
import { BigNumberish } from '../utils/num';
import { compileCalldata } from '../utils/stark';
import { getStarknetIdContract, useDecoded, useEncoded } from '../utils/starknetId';
import { ProviderInterface } from './interface';

Expand All @@ -15,7 +15,7 @@ export async function getStarkName(
const hexDomain = await provider.callContract({
contractAddress: contract,
entrypoint: 'address_to_domain',
calldata: compileCalldata({
calldata: CallData.compile({
address,
}),
});
Expand Down Expand Up @@ -48,7 +48,7 @@ export async function getAddressFromStarkName(
const addressData = await provider.callContract({
contractAddress: contract,
entrypoint: 'domain_to_address',
calldata: compileCalldata({
calldata: CallData.compile({
domain: [useEncoded(name.replace('.stark', '')).toString(10)],
}),
});
Expand Down
10 changes: 5 additions & 5 deletions src/types/lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { StarknetChainId } from '../../constants';
import { weierstrass } from '../../utils/ec';
import type { BigNumberish } from '../../utils/num';
import { Uint256 } from '../../utils/uint256';
import { CompiledContract, CompiledSierraCasm, ContractClass } from './contract';

export type WeierstrassSignatureType = weierstrass.SignatureType;
Expand All @@ -11,12 +12,11 @@ export type RawCalldata = BigNumberish[];
export type AllowArray<T> = T | T[];
export type RawArgs =
| {
[inputName: string]:
| BigNumberish
| BigNumberish[]
| { type: 'struct'; [k: string]: BigNumberish };
[inputName: string]: MultiType | MultiType[] | RawArgs;
}
| BigNumberish[];
| Array<MultiType | MultiType[] | RawArgs>;

export type MultiType = BigNumberish | Uint256 | object | boolean;

export type UniversalDeployerContractPayload = {
classHash: BigNumberish;
Expand Down
20 changes: 16 additions & 4 deletions src/utils/calldata/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import { Abi, AbiEntry, AbiStructs, Args, Calldata, FunctionAbi, Result } from '../../types';
import {
Abi,
AbiEntry,
AbiStructs,
Args,
Calldata,
FunctionAbi,
RawArgs,
Result,
} from '../../types';
import assert from '../assert';
import { isBigInt } from '../num';
import { isLongText, splitLongString } from '../shortString';
Expand Down Expand Up @@ -83,7 +92,7 @@ export class CallData {
* @param data Object representing cairo method arguments or string array of compiled data
* @returns string[]
*/
static compile(data: object | string[]): Calldata {
static compile(data: RawArgs): Calldata {
const createTree = (obj: object) => {
const getEntries = (o: object, prefix = ''): any => {
const oe = Array.isArray(o) ? [o.length.toString(), ...o] : o;
Expand All @@ -107,8 +116,11 @@ export class CallData {
// convert to array
callTreeArray = Object.values(callTree);
} else {
// data are already compiled or some missuses
callTreeArray = data;
// already compiled data but modified or raw args provided as array, recompile it
// recreate three
const callObj = { ...data };
const callTree = createTree(callObj);
callTreeArray = Object.values(callTree);
}

// add compiled property to array object
Expand Down
30 changes: 1 addition & 29 deletions src/utils/stark.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
import { getStarkKey, utils } from 'micro-starknet';
import { gzip } from 'pako';

import {
ArraySignatureType,
Calldata,
CompressedProgram,
Program,
RawArgs,
Signature,
} from '../types';
import { ArraySignatureType, CompressedProgram, Program, Signature } from '../types';
import { addHexPrefix, btoaUniversal } from './encode';
import { stringify } from './json';
import {
Expand Down Expand Up @@ -62,27 +55,6 @@ export function signatureToHexArray(sig?: Signature): ArraySignatureType {
return bigNumberishArrayToHexadecimalStringArray(formatSignature(sig));
}

/**
* @deprecated this function is deprecated use callData instead from calldata.ts
*/
export function compileCalldata(args: RawArgs): Calldata {
const compiledData = Object.values(args).flatMap((value) => {
if (Array.isArray(value))
return [toBigInt(value.length).toString(), ...value.map((x) => toBigInt(x).toString())];
if (typeof value === 'object' && 'type' in value)
return Object.entries<BigNumberish>(value)
.filter(([k]) => k !== 'type')
.map(([, v]) => toBigInt(v).toString());
return toBigInt(value).toString();
});
Object.defineProperty(compiledData, 'compiled', {
enumerable: false,
writable: false,
value: true,
});
return compiledData;
}

export function estimatedFeeToMaxFee(estimatedFee: BigNumberish, overhead: number = 0.5): bigint {
// BN can only handle Integers, so we need to do all calulations with integers
const overHeadPercent = Math.round((1 + overhead) * 100);
Expand Down
4 changes: 2 additions & 2 deletions www/docs/API/account.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ const call = await account.execute(
{
contractAddress: '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7', // ETH contract address
entrypoint: 'approve',
calldata: starknet.stark.compileCalldata(
calldata: starknet.CallData.compile(
{
spender: "0x15e90f807a00a01df845460324fbcd33986f2df3cc9d981e9e8b5005b7f595e",
amount: {
Expand All @@ -201,7 +201,7 @@ const multiCall = await account.execute(
{
contractAddress: '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7', // ETH contract address
entrypoint: 'approve',
calldata: starknet.stark.compileCalldata(
calldata: starknet.CallData.compile(
{
spender: "0x15e90f807a00a01df845460324fbcd33986f2df3cc9d981e9e8b5005b7f595e",
amount: {
Expand Down
Loading

0 comments on commit e5adca4

Please sign in to comment.