Class: Contract
Defined in: src/contract/default.ts:117
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]:any
Constructors
Constructor
new Contract(
options):Contract
Defined in: src/contract/default.ts:213
Parameters
options
abi: Abi of the contract object (required)
- address: address to connect to (required)
- providerOrAccount?: Provider or Account to attach to (optional, creates default RpcProvider on first use with auto node detection)
- 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
Properties
abi
abi:
Abi
Defined in: src/contract/default.ts:118
Contract ABI (Application Binary Interface)
Implementation of
address
address:
string
Defined in: src/contract/default.ts:120
Contract address on Starknet
Implementation of
providerOrAccount?
optionalproviderOrAccount?:ProviderOrAccount
Defined in: src/contract/default.ts:122
Provider for read operations or Account for write operations Optional - a default RpcProvider will be created on first async operation if not provided
Implementation of
ContractInterface.providerOrAccount
classHash?
optionalclassHash?:string
Defined in: src/contract/default.ts:124
Optional contract class hash for optimization
Implementation of
parseRequest
parseRequest:
boolean
Defined in: src/contract/default.ts:126
parseResponse
parseResponse:
boolean
Defined in: src/contract/default.ts:128
functions
readonlyfunctions:object
Defined in: src/contract/default.ts:136
Contract methods that return promises (async operations)
Index Signature
[name: string]: AsyncContractFunction
Implementation of
callStatic
readonlycallStatic:object
Defined in: src/contract/default.ts:138
Contract methods for read-only calls (state queries)
Index Signature
[name: string]: AsyncContractFunction
Implementation of
populateTransaction
readonlypopulateTransaction:object
Defined in: src/contract/default.ts:140
Contract methods that return populated transactions for batching
Index Signature
[name: string]: ContractFunction
Implementation of
ContractInterface.populateTransaction
estimateFee
readonlyestimateFee:object
Defined in: src/contract/default.ts:142
Contract methods for fee estimation
Index Signature
[name: string]: ContractFunction
Implementation of
callData
callData:
CallData
Defined in: src/contract/default.ts:159
The CallData this contract serializes and reads through.
Reachable because it is the end of a chain whose every other link is: building a Cairo type
over one of this contract's own types — a struct, a custom enum — takes the strategies the abi
parser assembled, and this is the only way to them. Rebuilding a CallData from abi is not
the same thing: a strategy given to this contract would be lost on the way.
const strategies = myContract.callData.parser.parsingStrategies;
const points = new CairoArray(list, 'core::array::Array::<my::Point>', strategies);
withOptionsProps?
optionalwithOptionsProps?:WithOptions
Defined in: src/contract/default.ts:161
Methods
factory()
staticfactory(params,details?):Promise<Contract>
Defined in: src/contract/default.ts:566
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
params
Factory parameters containing Contract Class details and deployment options
details?
UniversalDetails = {}
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);
```\
***
### withOptions()
> **withOptions**(`options`): `this`
Defined in: [src/contract/default.ts:278](https://github.com/starknet-io/starknet.js/blob/develop/src/contract/default.ts#L278)
Set execution options for subsequent contract interactions
#### Parameters
##### options
[`WithOptions`](../type-aliases/WithOptions.md)
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
attach()
attach(
address,abi?):void
Defined in: src/contract/default.ts:283
Attach the contract to a different address with optional new ABI
Parameters
address
string
New contract address to interact with
abi?
Optional new ABI to use (defaults to current ABI)
Returns
void
Example
contract.attach('0x123...', newAbi);
// Now contract.address === '0x123...' and uses newAbi
Implementation of
isDeployed()
isDeployed():
Promise<Contract>
Defined in: src/contract/default.ts:295
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
call()
call(
method,args?,options?):Promise<CallResult>
Defined in: src/contract/default.ts:307
Call a read-only contract method (view function)
Parameters
method
string
Name of the contract method to call
args?
ArgsOrCalldata = []
Method arguments as array or calldata
options?
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
invoke()
Call Signature
invoke(
method,args,options):Promise<SuccessfulTransactionReceiptResponseHelper>
Defined in: src/contract/default.ts:349
Invoke a state-changing contract method (external function)
Parameters
method
string
Name of the contract method to invoke
args
Method arguments as array or calldata
options
Pick<CommonContractOptions, "parseRequest"> & object & Partial<UniversalDetails> & object
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
Call Signature
invoke(
method,args,options):Promise<{transaction_hash:string; }>
Defined in: src/contract/default.ts:354
Parameters
method
string
args
options
Pick<CommonContractOptions, "parseRequest"> & object & Partial<UniversalDetails> & object
Returns
Promise<{ transaction_hash: string; }>
Implementation of
ContractInterface.invoke
Call Signature
invoke(
method,args?,options?):Promise<{transaction_hash:string; }>
Defined in: src/contract/default.ts:359
Parameters
method
string
args?
options?
Returns
Promise<{ transaction_hash: string; }>
Implementation of
ContractInterface.invoke
estimate()
estimate(
method,args?,estimateDetails?):Promise<EstimateFeeResponseOverhead|PaymasterFeeEstimate>
Defined in: src/contract/default.ts:435
Estimate fee for invoking a contract method
Parameters
method
string
Name of the contract method to estimate
args?
ArgsOrCalldata = []
Method arguments as array or calldata
estimateDetails?
ExecuteOptions = {}
Returns
Promise<EstimateFeeResponseOverhead | PaymasterFeeEstimate>
Fee estimation details
Example
const feeEstimate = await contract.estimate('transfer', [recipient, amount]);
console.log('Estimated fee:', feeEstimate.overall_fee);
Implementation of
compile()
compile(
method,args?):Calldata
Defined in: src/contract/default.ts:466
Compile the calldata for a contract method, using the contract abi.
Unlike populate, this returns only the compiled Calldata array, without wrapping it
in an Invocation object (no contractAddress nor entrypoint). It is the contract-bound
equivalent of myCallData.compile(method, args).
If args is already a compiled Calldata, it is returned as-is without recompilation.
Parameters
method
string
Name of the contract method, as defined in the abi
args?
RawArgs = []
Method arguments as array (in abi order) or object (free order), or an already compiled calldata
Returns
The compiled calldata
Example
// 'amount' is a u256: the abi splits it into 2 felts automatically
const calldata = contract.compile('transfer', { recipient: '0x123', amount: 100n });
// calldata = ['0x123', '100', '0']
Implementation of
populate()
populate(
method,args?):Call
Defined in: src/contract/default.ts:470
Populate transaction data for a contract method call
Parameters
method
string
Name of the contract method
args?
RawArgs = []
Method arguments as array or calldata
Returns
Invocation object for batching or inspection
Example
const invocation = contract.populate('transfer', [recipient, amount]);
// Use in account.execute([invocation1, invocation2, ...])
Implementation of
parseEvents()
parseEvents(
receipt):ParsedEvents
Defined in: src/contract/default.ts:478
Parse events from a transaction receipt using the contract's ABI
Parameters
receipt
Transaction receipt from waitForTransaction
Returns
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
isCairo1()
isCairo1():
boolean
Defined in: src/contract/default.ts:495
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
getVersion()
getVersion():
Promise<ContractVersion>
Defined in: src/contract/default.ts:499
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
typedv2()
typedv2<
TAbi>(tAbi):TypedContractV2<TAbi>
Defined in: src/contract/default.ts:504
Create a typed contract instance with full TypeScript support
Type Parameters
TAbi
TAbi extends Abi
Parameters
tAbi
TAbi
The 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