Skip to content

Commit

Permalink
Update starknet.js
Browse files Browse the repository at this point in the history
  • Loading branch information
archseer committed Jan 16, 2024
1 parent a4dcfdf commit 6c1b856
Show file tree
Hide file tree
Showing 13 changed files with 990 additions and 1,129 deletions.
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
}
17 changes: 2 additions & 15 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 Down
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'])
})
})
Loading

0 comments on commit 6c1b856

Please sign in to comment.