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

starknet.js 6.0 #346

Closed
wants to merge 3 commits into from
Closed
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
3 changes: 1 addition & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,10 @@ test-integration-contracts: build-ts env-devnet-hardhat
yarn test

.PHONY: test-integration-gauntlet
# TODO: better network lifecycle setup - tests setup/run their own network (L1 + conflict w/ above if not cleaned up)
# TODO: fix example
# cd packages-ts/starknet-gauntlet-example/ && \
# yarn test
test-integration-gauntlet: build-ts env-devnet-hardhat-down
test-integration-gauntlet: build-ts env-devnet-hardhat
cd packages-ts/starknet-gauntlet/ && \
yarn test
cd packages-ts/starknet-gauntlet-argent/ && \
Expand Down
2 changes: 1 addition & 1 deletion examples/contracts/proxy-consumer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@
},
"license": "MIT",
"dependencies": {
"starknet": "^5.2.0"
"starknet": "^6.0.0-beta.11"
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,6 @@
"typescript": "4.7.2"
},
"dependencies": {
"starknet": "^5.17.0"
"starknet": "^6.0.0-beta.11"
}
}
22 changes: 13 additions & 9 deletions packages-ts/starknet-gauntlet-ledger/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,21 +72,25 @@ class LedgerSigner implements SignerInterface {
transactionsDetail: InvocationsSignerDetails,
abis?: Abi[],
): Promise<Signature> {
// TODO: match https://github.com/starknet-io/starknet.js/blob/0f8b266da6709ddb897860575e09578e547d185c/src/signer/default.ts#L46-L77

const calldata = transaction.fromCallsToExecuteCalldataWithNonce(
transactions,
transactionsDetail.nonce,
)

const msgHash = hash.calculateTransactionHash(
transactionsDetail.walletAddress,
transactionsDetail.version,
calldata,
transactionsDetail.maxFee,
transactionsDetail.chainId,
transactionsDetail.nonce,
)
// const msgHash = hash.calculateTransactionHash(
// transactionsDetail.walletAddress,
// transactionsDetail.version,
// calldata,
// transactionsDetail.maxFee,
// transactionsDetail.chainId,
// transactionsDetail.nonce,
// )

return this.sign(msgHash)
// return this.sign(msgHash)

throw 'unimplemented'
}

async signDeployAccountTransaction(transaction: DeployAccountSignerDetails): Promise<Signature> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@ export const getLatestOCRConfigEvent = async (
contractAddress: string,
) => {
// get block number in which the latest config was set
const res = (
await provider.provider.callContract({
contractAddress,
entrypoint: 'latest_config_details',
calldata: [],
})
).result
const res = await provider.provider.callContract({
contractAddress,
entrypoint: 'latest_config_details',
calldata: [],
})
const latestConfigDetails = {
configCount: parseInt(res[0]),
blockNumber: parseInt(res[1]),
Expand All @@ -21,25 +19,21 @@ export const getLatestOCRConfigEvent = async (
// if no config has been set yet, return empty config
if (latestConfigDetails.configCount === 0) return []

// retrieve all block traces in the block in which the latest config was set
const blockTraces = await provider.provider.getBlockTraces(latestConfigDetails.blockNumber)

// retrieve array of all events across all internal calls for each tx in the
// block, for which the contract address = aggregator contract and the first
// event key matches 'ConfigSet'
const configSetEvents = blockTraces.traces.flatMap((trace) => {
return trace.function_invocation.internal_calls
.filter((call) => call.contract_address === contractAddress)
.flatMap((call) => call.events)
.filter((event) => event.keys[0] === hash.getSelectorFromName('ConfigSet'))
const keyFilter = [hash.getSelectorFromName('ConfigSet')]
const chunk = await provider.provider.getEvents({
address: contractAddress,
from_block: { block_number: latestConfigDetails.blockNumber },
to_block: { block_number: latestConfigDetails.blockNumber },
keys: [keyFilter],
chunk_size: 10,
})

const events = chunk.events
// if no config set events found in the given block, throw error
// this should not happen if block number in latestConfigDetails is set correctly
if (configSetEvents.length === 0)
if (events.length === 0)
throw new Error(`No ConfigSet events found in block number ${latestConfigDetails.blockNumber}`)

// assume last event found is the latest config, in the event that multiple
// set_config transactions ended up in the same block
return configSetEvents[configSetEvents.length - 1].data
return events[events.length - 1].data
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const makeComparisionData = (provider: IStarknetProvider) => async (
})
transmitterInfo.push({
transmitter,
owedPayment: parseInt(owedPayment.result[0]).toString(),
owedPayment: parseInt(owedPayment[0]).toString(),
})
}
const billing = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { ocr2ContractLoader } from '../../lib/contracts'
import { SetConfig, encoding, SetConfigInput } from '@chainlink/gauntlet-contracts-ocr2'
import { decodeOffchainConfigFromEventData } from '../../lib/encoding'
import assert from 'assert'
import { InvokeTransactionReceiptResponse } from 'starknet'
import { getLatestOCRConfigEvent } from './inspection/configEvent'

type Oracle = {
Expand Down Expand Up @@ -157,10 +156,8 @@ const afterExecute: AfterExecute<SetConfigInput, ContractInput> = (context, inpu
result,
) => {
const txHash = result.responses[0].tx.hash
const txInfo = (await context.provider.provider.getTransactionReceipt(
txHash,
)) as InvokeTransactionReceiptResponse
if (txInfo.status === 'REJECTED') {
const txInfo = await context.provider.provider.getTransactionReceipt(txHash)
if (txInfo.execution_status === 'REVERTED') {
return { successfulConfiguration: false }
}
const eventData = txInfo.events[0].data
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ export const makeExecuteCommand = <UI, CI>(config: ExecuteCommandConfig<UI, CI>)
return tx
}

deps.logger.success(`Contract declared at ${tx.tx.class_hash}`)
deps.logger.success(`Contract declared at ${this.compiledContractHash}`)
return tx
}

Expand Down
12 changes: 6 additions & 6 deletions packages-ts/starknet-gauntlet/src/provider/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { TransactionResponse } from '../transaction'
import {
SequencerProvider as StarknetProvider,
RpcProvider as StarknetProvider,
InvokeFunctionResponse,
DeployContractResponse,
Sequencer,
CompiledContract,
Account,
Call,
Expand Down Expand Up @@ -44,7 +44,7 @@ export const makeProvider = (

export const wrapResponse = (
provider: IStarknetProvider,
response: Sequencer.AddTransactionResponse | DeployContractResponse,
response: InvokeFunctionResponse | DeployContractResponse,
address?: string,
): TransactionResponse => {
const txResponse: TransactionResponse = {
Expand All @@ -64,7 +64,7 @@ export const wrapResponse = (
success = false
}
const status = await provider.provider.getTransactionStatus(response.transaction_hash)
txResponse.tx.code = status.tx_status as any // For some reason, starknet does not consider any other status than "TRANSACTION_RECEIVED"
txResponse.code = status.finality_status // For some reason, starknet does not consider any other status than "TRANSACTION_RECEIVED"
return { success }
},
status: 'PENDING',
Expand All @@ -77,8 +77,8 @@ class Provider implements IStarknetProvider {
provider: StarknetProvider
account: Account

constructor(baseUrl: string, wallet?: IStarknetWallet) {
this.provider = new StarknetProvider({ baseUrl })
constructor(nodeUrl: string, wallet?: IStarknetWallet) {
this.provider = new StarknetProvider({ nodeUrl })
if (wallet) {
this.account = new Account(this.provider, wallet.getAccountAddress(), wallet.signer)
}
Expand Down
5 changes: 3 additions & 2 deletions packages-ts/starknet-gauntlet/src/transaction/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Sequencer } from 'starknet'
import { InvokeFunctionResponse, RPC } from 'starknet'

export type TransactionResponse = {
hash: string
address?: string
wait: () => Promise<{ success: boolean }>
tx?: Sequencer.AddTransactionResponse
tx?: InvokeFunctionResponse
code?: RPC.SPEC.TXN_STATUS
status: 'PENDING' | 'ACCEPTED' | 'REJECTED'
errorMessage?: string
}
21 changes: 4 additions & 17 deletions packages-ts/starknet-gauntlet/test/utils/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,19 +53,7 @@ class VenvDevnet extends IntegratedDevnet {

protected spawnChildProcess(): Promise<ChildProcess> {
return new Promise((resolve, reject) => {
const cairoSierraCompilerBuildPath = path.join(
__dirname,
'../../../../cairo-build/bin/starknet-sierra-compile',
)
const cargoManifest = path.join(__dirname, '../../../../vendor/cairo/Cargo.toml')
const args = ['--port', this.port, '--gas-price', '1', '--lite-mode']
if (fs.existsSync(cairoSierraCompilerBuildPath)) {
args.push('--sierra-compiler-path', cairoSierraCompilerBuildPath)
} else if (fs.existsSync(cargoManifest)) {
args.push('--cairo-compiler-manifest', cargoManifest)
} else {
return reject(new Error('Could not find cairo package'))
}
const args = ['--port', this.port, '--gas-price', '1']
if (this.opts?.seed) {
args.push('--seed', this.opts.seed.toString())
} else {
Expand All @@ -82,8 +70,7 @@ class VenvDevnet extends IntegratedDevnet {
let initialOutput = ''
childProcess.stdout.on('data', (chunk) => {
initialOutput += chunk
// Wait for the 1st account to be printed out. The 'Listening on ...' line doesn't seem to be output when started without a tty.
if (initialOutput.indexOf('Account #0') >= 0) {
if (initialOutput.indexOf('listening on') >= 0) {
console.log('Started starknet-devnet')
childProcess.stdout.removeAllListeners('data')
resolve(childProcess)
Expand All @@ -100,10 +87,10 @@ class VenvDevnet extends IntegratedDevnet {
export const startNetwork = async (opts?: {}): Promise<IntegratedDevnet> => {
const devnet = new VenvDevnet('5050', opts)

await devnet.start()
// await devnet.start()

// Starting to poll devnet too soon can result in ENOENT
await new Promise((f) => setTimeout(f, 2000))
// await new Promise((f) => setTimeout(f, 2000))

return devnet
}
6 changes: 3 additions & 3 deletions packages-ts/starknet/src/account.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Account, SequencerProvider, ec, uint256 } from 'starknet'
import { Account, RpcProvider, ec, uint256, constants } from 'starknet'

export const ERC20_ADDRESS = '0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7'

Expand Down Expand Up @@ -72,8 +72,8 @@ class DevnetFundingStrategy implements IFundingStrategy {
// Fund the Account on Testnet
class AllowanceFundingStrategy implements IFundingStrategy {
public async fund(accounts: FundAccounts[], opts: FunderOptions) {
const provider = new SequencerProvider({
baseUrl: 'https://alpha4.starknet.io',
const provider = new RpcProvider({
nodeUrl: constants.NetworkName.SN_GOERLI,
})

const operator = new Account(provider, opts.accountAddr, opts.keyPair)
Expand Down
14 changes: 7 additions & 7 deletions packages-ts/starknet/test/fundAccount.test.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import { assert } from 'chai'
import { account } from '@chainlink/starknet'
import { Account, ec, SequencerProvider, stark } from 'starknet'
import { Account, ec, RpcProvider, stark } from 'starknet'
import { DEVNET_URL, ERC20_ADDRESS } from '../src/account'

describe('fundAccount', function () {
this.timeout(900_000)
let alice: Account
let bob: Account
let provider: SequencerProvider
let provider: RpcProvider

const opts = account.makeFunderOptsFromEnv()
const funder = new account.Funder(opts)

before(async function () {
const gateway_url = process.env.NODE_URL || DEVNET_URL
provider = new SequencerProvider({ baseUrl: gateway_url })
provider = new RpcProvider({ nodeUrl: gateway_url })

const aliceStarkKeyPair = ec.starkCurve.utils.randomPrivateKey()
const bobStarkKeyPair = ec.starkCurve.utils.randomPrivateKey()
Expand All @@ -37,7 +37,7 @@ describe('fundAccount', function () {
entrypoint: 'balanceOf',
calldata: [BigInt(alice.address).toString(10)],
})
assert.deepEqual(balance.result, ['0x1388', '0x0'])
assert.deepEqual(balance, ['0x1388', '0x0'])
})

it('should have fund bob', async () => {
Expand All @@ -46,7 +46,7 @@ describe('fundAccount', function () {
entrypoint: 'balanceOf',
calldata: [BigInt(bob.address).toString(10)],
})
assert.deepEqual(balance.result, ['0x1f40', '0x0'])
assert.deepEqual(balance, ['0x1f40', '0x0'])
})

it("should increament alice's fees", async () => {
Expand All @@ -57,7 +57,7 @@ describe('fundAccount', function () {
entrypoint: 'balanceOf',
calldata: [BigInt(alice.address).toString(10)],
})
assert.deepEqual(balance.result, ['0x13ec', '0x0'])
assert.deepEqual(balance, ['0x13ec', '0x0'])
})

it("should increament bob's fees", async () => {
Expand All @@ -68,6 +68,6 @@ describe('fundAccount', function () {
entrypoint: 'balanceOf',
calldata: [BigInt(bob.address).toString(10)],
})
assert.deepEqual(balance.result, ['0x2328', '0x0'])
assert.deepEqual(balance, ['0x2328', '0x0'])
})
})
1 change: 1 addition & 0 deletions shell.nix
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
nodePackages.typescript
nodePackages.typescript-language-server
nodePackages.npm
python3

go_1_21
gopls
Expand Down
Loading
Loading