Skip to main content
Version: Next

Class: Contract

Interface for interacting with Starknet smart contracts

Provides methods for calling contract functions, estimating fees, and managing contract state. Supports both read-only calls and state-changing invocations.

Remarks

The interface provides multiple ways to interact with contracts:

  • Direct method calls for convenience
  • Generic call/invoke methods for flexibility
  • Fee estimation and transaction population
  • Event parsing and contract validation

Implements

Indexable

[key: string]: AsyncContractFunction | any

Constructors

constructor

new Contract(options): Contract

Parameters

NameTypeDescription
optionsContractOptionsabi: Abi of the contract object (required) - address: address to connect to (required) - providerOrAccount?: Provider or Account to attach to (fallback to defaultProvider) - parseRequest?: compile and validate arguments (optional, default true) - parseResponse?: Parse elements of the response array and structuring them into response object (optional, default true) - parser?: Abi parser (optional, default createAbiParser(options.abi))

Returns

Contract

Defined in

src/contract/default.ts:148

Properties

abi

abi: Abi

Contract ABI (Application Binary Interface)

Implementation of

ContractInterface.abi

Defined in

src/contract/default.ts:107


address

address: string

Contract address on Starknet

Implementation of

ContractInterface.address

Defined in

src/contract/default.ts:109


providerOrAccount

providerOrAccount: ProviderOrAccount

Provider for read operations or Account for write operations

Implementation of

ContractInterface.providerOrAccount

Defined in

src/contract/default.ts:111


classHash

Optional classHash: string

Optional contract class hash for optimization

Implementation of

ContractInterface.classHash

Defined in

src/contract/default.ts:113


parseRequest

parseRequest: boolean

Defined in

src/contract/default.ts:115


parseResponse

parseResponse: boolean

Defined in

src/contract/default.ts:117


structs

Private structs: Object

Index signature

[name: string]: AbiStruct

Defined in

src/contract/default.ts:119


events

Private events: AbiEvents

Defined in

src/contract/default.ts:121


functions

Readonly functions: Object

Contract methods that return promises (async operations)

Index signature

[name: string]: AsyncContractFunction

Implementation of

ContractInterface.functions

Defined in

src/contract/default.ts:123


callStatic

Readonly callStatic: Object

Contract methods for read-only calls (state queries)

Index signature

[name: string]: AsyncContractFunction

Implementation of

ContractInterface.callStatic

Defined in

src/contract/default.ts:125


populateTransaction

Readonly populateTransaction: Object

Contract methods that return populated transactions for batching

Index signature

[name: string]: ContractFunction

Implementation of

ContractInterface.populateTransaction

Defined in

src/contract/default.ts:127


estimateFee

Readonly estimateFee: Object

Contract methods for fee estimation

Index signature

[name: string]: ContractFunction

Implementation of

ContractInterface.estimateFee

Defined in

src/contract/default.ts:129


callData

Private callData: CallData

Defined in

src/contract/default.ts:133


withOptionsProps

Optional withOptionsProps: WithOptions

Defined in

src/contract/default.ts:135


parsingStrategy

Private Optional parsingStrategy: ParsingStrategy

Defined in

src/contract/default.ts:137

Methods

factory

factory(params, details?): Promise<Contract>

Factory method to declare and/or deploy a contract creating a new Contract instance

It handles the entire lifecycle: compiles constructor calldata, optionally declares the contract class, deploys an instance, and returns a ready-to-use Contract object.

When classHash is provided, it will only deploy the contract without declaring. When contract is provided without classHash, it will declare and deploy.

Parameters

NameTypeDescription
paramsFactoryParamsFactory parameters containing Contract Class details and deployment options
detailsUniversalDetails-

Returns

Promise<Contract>

Promise that resolves to a deployed Contract instance with address and transaction hash

Throws

Error if deployment fails or contract_address is not returned

Example

// Declare and deploy an ERC20 contract
const contract = await Contract.factory({
contract: erc20CompiledContract,
account: myAccount,
casm: erc20Casm,
constructorCalldata: {
name: 'MyToken',
symbol: 'MTK',
decimals: 18,
initial_supply: { low: 1000000, high: 0 },
recipient: myAccount.address
}
});

// Deploy-only mode with existing classHash (ABI will be fetched from network)
const contract2 = await Contract.factory({
classHash: '0x1234...',
account: myAccount,
constructorCalldata: {
name: 'AnotherToken',
symbol: 'ATK',
decimals: 18,
initial_supply: { low: 2000000, high: 0 },
recipient: myAccount.address
}
});

// Deploy-only mode with provided ABI (faster, no network call)
const contract3 = await Contract.factory({
classHash: '0x1234...',
abi: erc20Abi,
account: myAccount,
constructorCalldata: {
name: 'ThirdToken',
symbol: 'TTK',
decimals: 18,
initial_supply: { low: 3000000, high: 0 },
recipient: myAccount.address
}
});

console.log('Contract deployed at:', contract.address);
```\

#### Defined in

[src/contract/default.ts:494](https://github.com/starknet-io/starknet.js/blob/develop/src/contract/default.ts#L494)

___

### withOptions

▸ **withOptions**(`options`): `this`

Set execution options for subsequent contract interactions

#### Parameters

| Name | Type | Description |
| :------ | :------ | :------ |
| `options` | [`WithOptions`](/docs/next/API/modules#withoptions) | Options to override for contract interactions |

#### Returns

`this`

This contract instance with the specified options applied

**`Example`**

```typescript
contract.withOptions({
blockIdentifier: 'latest',
parseResponse: false
});
// Now all subsequent calls use these options

Implementation of

ContractInterface.withOptions

Defined in

src/contract/default.ts:213


attach

attach(address, abi?): void

Attach the contract to a different address with optional new ABI

Parameters

NameTypeDescription
addressstringNew contract address to interact with
abi?AbiOptional new ABI to use (defaults to current ABI)

Returns

void

Example

contract.attach('0x123...', newAbi);
// Now contract.address === '0x123...' and uses newAbi

Implementation of

ContractInterface.attach

Defined in

src/contract/default.ts:218


isDeployed

isDeployed(): Promise<Contract>

Verify that a contract is deployed at the current address

Returns

Promise<Contract>

Promise resolving to this contract instance if deployed

Throws

If no contract is found at the address

Example

try {
await contract.isDeployed();
console.log('Contract is deployed');
} catch (error) {
console.log('Contract not found at address');
}

Implementation of

ContractInterface.isDeployed

Defined in

src/contract/default.ts:230


call

call(method, args?, «destructured»?): Promise<CallResult>

Call a read-only contract method (view function)

Parameters

NameTypeDefault valueDescription
methodstringundefinedName of the contract method to call
argsArgsOrCalldata[]Method arguments as array or calldata
«destructured»CallOptions{}Call options including block identifier and parsing settings

Returns

Promise<CallResult>

Parsed result from the contract method

Example

const balance = await contract.call('balanceOf', [userAddress]);
const name = await contract.call('name', [], { blockIdentifier: 'latest' });

Implementation of

ContractInterface.call

Defined in

src/contract/default.ts:241


invoke

invoke(method, args, options): Promise<SuccessfulTransactionReceiptResponseHelper>

Invoke a state-changing contract method (external function)

Parameters

NameTypeDescription
methodstringName of the contract method to invoke
argsArgsOrCalldataMethod arguments as array or calldata
optionsPick<CommonContractOptions, "parseRequest"> & { signature?: Signature ; salt?: string ; waitForTransaction?: boolean } & Partial<UniversalDetails> & { waitForTransaction: true }Execution options including transaction details

Returns

Promise<SuccessfulTransactionReceiptResponseHelper>

Transaction response with hash

Example

const tx = await contract.invoke('transfer', [recipient, amount]);
const receipt = await provider.waitForTransaction(tx.transaction_hash);

Implementation of

ContractInterface.invoke

Defined in

src/contract/default.ts:282

invoke(method, args, options): Promise<{ transaction_hash: string }>

Parameters

NameType
methodstring
argsArgsOrCalldata
optionsPick<CommonContractOptions, "parseRequest"> & { signature?: Signature ; salt?: string ; waitForTransaction?: boolean } & Partial<UniversalDetails> & { waitForTransaction: false }

Returns

Promise<{ transaction_hash: string }>

Implementation of

ContractInterface.invoke

Defined in

src/contract/default.ts:287

invoke(method, args?, options?): Promise<{ transaction_hash: string }>

Parameters

NameType
methodstring
args?ArgsOrCalldata
options?ExecuteOptions

Returns

Promise<{ transaction_hash: string }>

Implementation of

ContractInterface.invoke

Defined in

src/contract/default.ts:292


estimate

estimate(method, args?, estimateDetails?): Promise<EstimateFeeResponseOverhead>

Estimate fee for invoking a contract method

Parameters

NameTypeDefault valueDescription
methodstringundefinedName of the contract method to estimate
argsArgsOrCalldata[]Method arguments as array or calldata
estimateDetailsUniversalDetails{}Estimation options including block identifier

Returns

Promise<EstimateFeeResponseOverhead>

Fee estimation details

Example

const feeEstimate = await contract.estimate('transfer', [recipient, amount]);
console.log('Estimated fee:', feeEstimate.overall_fee);

Implementation of

ContractInterface.estimate

Defined in

src/contract/default.ts:350


populate

populate(method, args?): Call

Populate transaction data for a contract method call

Parameters

NameTypeDefault valueDescription
methodstringundefinedName of the contract method
argsRawArgs[]Method arguments as array or calldata

Returns

Call

Invocation object for batching or inspection

Example

const invocation = contract.populate('transfer', [recipient, amount]);
// Use in account.execute([invocation1, invocation2, ...])

Implementation of

ContractInterface.populate

Defined in

src/contract/default.ts:368


parseEvents

parseEvents(receipt): ParsedEvents

Parse events from a transaction receipt using the contract's ABI

Parameters

NameTypeDescription
receiptGetTransactionReceiptResponseTransaction receipt from waitForTransaction

Returns

ParsedEvents

Array of parsed events with decoded data

Example

const receipt = await provider.waitForTransaction(txHash);
const events = contract.parseEvents(receipt);
events.forEach(event => {
console.log('Event:', event.name, event.data);
});

Implementation of

ContractInterface.parseEvents

Defined in

src/contract/default.ts:379


isCairo1

isCairo1(): boolean

Check if the contract is implemented in Cairo 1

Returns

boolean

True if the contract uses Cairo 1, false for Cairo 0 (legacy)

Example

if (contract.isCairo1()) {
console.log('Using Cairo 1 features');
}

Implementation of

ContractInterface.isCairo1

Defined in

src/contract/default.ts:424


getVersion

getVersion(): Promise<ContractVersion>

Get the Cairo and compiler version of the contract

Returns

Promise<ContractVersion>

Object containing cairo version and compiler version

Example

const version = await contract.getVersion();
console.log(`Cairo ${version.cairo}, Compiler ${version.compiler}`);

Implementation of

ContractInterface.getVersion

Defined in

src/contract/default.ts:428


typedv2

typedv2<TAbi>(tAbi): TypedContractV2<TAbi>

Create a typed contract instance with full TypeScript support

Type parameters

NameType
TAbiextends Abi

Parameters

NameTypeDescription
tAbiTAbiThe typed ABI interface for compile-time type checking

Returns

TypedContractV2<TAbi>

Typed contract instance with IntelliSense support

Example

const typedContract = contract.typedv2(erc20Abi);
// Now typedContract.transfer() has full type safety

Implementation of

ContractInterface.typedv2

Defined in

src/contract/default.ts:432