diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index a49f89b5b..9ac4fa6dd 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -14,12 +14,12 @@ jobs: name: lint runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-go@v4.1.0 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 #v5 + - uses: actions/setup-go@44694675825211faa026b3c33043df3e48a5fa00 #v5 with: go-version-file: go.mod cache: false - name: golangci-lint - uses: golangci/golangci-lint-action@v8 + uses: golangci/golangci-lint-action@4afd733a84b1f43292c63897423277bb7f4313a9 #v8 with: - version: v2.4.0 \ No newline at end of file + version: v2.5.0 \ No newline at end of file diff --git a/.golangci.yaml b/.golangci.yaml index 74d4c5902..59e5610d6 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -48,30 +48,16 @@ linters: min-len: 2 min-occurrences: 3 gocritic: - disabled-checks: - - sloppyReassign - - dupImport - - ifElseChain - - octalLiteral - - whyNoLint - - unnamedResult - enabled-tags: - - diagnostic - - experimental - - opinionated - - performance - - style + enable-all: true gocyclo: min-complexity: 15 - gosec: - excludes: - - G115 govet: - enable: - - nilness - - shadow + enable-all: true + disable: + # Since we are a library, we need to also take into account the UX when aligning fields. + - fieldalignment lll: - line-length: 140 + line-length: 100 misspell: locale: UK mnd: @@ -85,12 +71,13 @@ linters: - "1" - "2" - "3" - ignored-functions: - - strings.SplitN nolintlint: - require-explanation: false - require-specific: false allow-unused: false + require-explanation: true + require-specific: true + staticcheck: + checks: + - "all" exclusions: paths: - client/ # it comes from go-ethereum, let's refactor it another time @@ -98,8 +85,6 @@ linters: presets: - comments - common-false-positives - - legacy - - std-error-handling rules: - linters: - exhaustruct @@ -133,6 +118,9 @@ linters: - linters: - lll source: '^//go:generate ' + - linters: + - staticcheck + path: rpc/mock_test.go formatters: enable: - gci @@ -142,7 +130,10 @@ formatters: - golines settings: golines: - max-len: 140 + max-len: 100 goimports: local-prefixes: - - github.com/golangci/golangci-lint \ No newline at end of file + - github.com/golangci/golangci-lint +issues: + max-issues-per-linter: 0 + max-same-issues: 0 \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index a432221ff..974806609 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - New `curve.SignFelts` function for signing messages with felt.Felt parameters. ### Changed +- Major refactoring in the codebase to match Golang conventions. + - Renaming: + - All type/function names that contained `_` have been renamed to remove the underscore. + - The `typedData` pkg was renamed to `typedata`. + - The `rpc.Provider.GetStorageProof` method was renamed to `rpc.Provider.StorageProof`. + - The `rpc.Provider.GetTransactionStatus` method was renamed to `rpc.Provider.TransactionStatus`. + - The `rpc.Provider.GetMessagesStatus` method was renamed to `rpc.Provider.MessagesStatus`. + - The `rpc.Provider.TransactionByBlockIdAndIndex` method was renamed to `rpc.Provider.TransactionByBlockIDAndIndex` (see the 'ID'). + - The `rpc.RpcProvider` interface was renamed to `rpc.RPCProvider`. + - Other renames in exported types/fields/variables: + - `typedData.Domain.ChainId` -> `typedData.Domain.ChainID` + - `rpc.SKIP_FEE_CHARGE` -> `rpc.SkipFeeCharge` + - `rpc.SKIP_VALIDATE` -> `rpc.SkipValidate` + - `account.Account.ChainId` -> `account.Account.ChainID` + - Variables `hash.PREFIX_TRANSACTION`, `hash.PREFIX_DECLARE`, and `hash.PREFIX_DEPLOY_ACCOUNT` were renamed and + are no longer exported. + - Variable `contracts.PREFIX_CONTRACT_ADDRESS` was renamed and is no longer exported. + - Changed types: + - `contracts.SierraEntryPoint.FunctionIdx` is now of type `uint` + - `contracts.CasmEntryPoint.Offset` is now of type `uint` - The `rpc.RPCError` type and logic was refactored and moved to the new `client/rpcerr` package. There are some changes in the new package: - The internal `tryUnwrapToRPCErr` func of the `rpc` pkg was renamed to `UnwrapToRPCErr` and moved to the new package. @@ -37,6 +57,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 old `rpc/spy_test.go` file was removed. - New `mocks/mock_client.go` file containing a mock of the `client.Client` type (`client.ClientI` interface). - New benchmarks and tests for the `typedData` pkg. +- New linter rules in the `.golangci.yaml` file, thus, a lot of changes in the codebase to fix the new rules. +- Updated `golangci-lint` to v2.5.0. ## [0.15.0](https://github.com/NethermindEth/starknet.go/releases/tag/v0.15.0) - 2025-09-03 ### Changed diff --git a/Makefile b/Makefile index b5856ecf6..17047bd30 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -GOLANGCI_LINT_VERSION := v2.4.0 +GOLANGCI_LINT_VERSION := v2.5.0 MOCKGEN_VERSION := v0.6.0 .PHONY: test lint format diff --git a/account/account.go b/account/account.go index c53a9a47c..e5a009726 100644 --- a/account/account.go +++ b/account/account.go @@ -15,8 +15,9 @@ import ( var ( ErrTxnTypeUnSupported = errors.New("unsupported transaction type") ErrTxnVersionUnSupported = errors.New("unsupported transaction version") - BRAAVOS_WARNING_MESSAGE = `WARNING: Currently, Braavos accounts are incompatible with transactions sent via - RPC 0.8.0. Ref: https://community.starknet.io/t/starknet-devtools-for-0-13-5/115495#p-2359168-braavos-compatibility-issues-3` + + //nolint:lll // The line break would be outputted in the warning message + BraavosWarningMessage = `WARNING: Currently, Braavos accounts are incompatible with transactions sent via RPC 0.8.0. Ref: https://community.starknet.io/t/starknet-devtools-for-0-13-5/115495#p-2359168-braavos-compatibility-issues-3` ) //go:generate mockgen -destination=../mocks/mock_account.go -package=mocks -source=account.go AccountInterface @@ -50,10 +51,17 @@ type AccountInterface interface { SendTransaction(ctx context.Context, txn rpc.BroadcastTxn) (rpc.TransactionResponse, error) Sign(ctx context.Context, msg *felt.Felt) ([]*felt.Felt, error) SignInvokeTransaction(ctx context.Context, tx rpc.InvokeTxnType) error - SignDeployAccountTransaction(ctx context.Context, tx rpc.DeployAccountType, precomputeAddress *felt.Felt) error + SignDeployAccountTransaction( + ctx context.Context, + tx rpc.DeployAccountType, + precomputeAddress *felt.Felt, + ) error SignDeclareTransaction(ctx context.Context, tx rpc.DeclareTxnType) error TransactionHashInvoke(invokeTxn rpc.InvokeTxnType) (*felt.Felt, error) - TransactionHashDeployAccount(tx rpc.DeployAccountType, contractAddress *felt.Felt) (*felt.Felt, error) + TransactionHashDeployAccount( + tx rpc.DeployAccountType, + contractAddress *felt.Felt, + ) (*felt.Felt, error) TransactionHashDeclare(tx rpc.DeclareTxnType) (*felt.Felt, error) Verify(msgHash *felt.Felt, signature []*felt.Felt) (bool, error) WaitForTransactionReceipt( @@ -63,11 +71,11 @@ type AccountInterface interface { ) (*rpc.TransactionReceiptWithBlockInfo, error) } -var _ AccountInterface = &Account{} //nolint:exhaustruct +var _ AccountInterface = (*Account)(nil) type Account struct { - Provider rpc.RpcProvider - ChainId *felt.Felt + Provider rpc.RPCProvider + ChainID *felt.Felt Address *felt.Felt publicKey string CairoVersion CairoVersion @@ -98,19 +106,26 @@ const ( // - *Account: a pointer to newly created Account // - error: an error if any func NewAccount( - provider rpc.RpcProvider, + provider rpc.RPCProvider, accountAddress *felt.Felt, publicKey string, keystore Keystore, cairoVersion CairoVersion, ) (*Account, error) { // TODO: Remove this temporary check once solved (starknet v0.14.0 should do it) - // This temporary check is to warn the user that Braavos account restricts transactions to have exactly two resource fields. + // This temporary check is to warn the user that Braavos account restricts + // transactions to have exactly two resource fields. // This makes them incompatible with transactions sent via RPC 0.8.0 - accClassHash, err := provider.ClassHashAt(context.Background(), rpc.WithBlockTag("latest"), accountAddress) - // ignoring the error to not break mock tests (if the provider is not working, it will return an error in the next ChainID call anyway) + accClassHash, err := provider.ClassHashAt( + context.Background(), + rpc.WithBlockTag("latest"), + accountAddress, + ) + // ignoring the error to not break mock tests (if the provider is not + // working, it will return an error in the next ChainID call anyway) if err == nil { - // Since felt.Felt.String() returns a string without leading zeros, we need to remove them from the + // Since felt.Felt.String() returns a string without leading zeros, we + // need to remove them from the class hashes for the comparison // class hashes for the comparison braavosClassHashes := []string{ // Original class hash: 0x02c8c7e6fbcfb3e8e15a46648e8914c6aa1fc506fc1e7fb3d1e19630716174bc @@ -121,7 +136,7 @@ func NewAccount( "0x41bf1e71792aecb9df3e9d04e1540091c5e13122a731e02bec588f71dc1a5c3", } if slices.Contains(braavosClassHashes, accClassHash.String()) { - fmt.Print(BRAAVOS_WARNING_MESSAGE + "\n\n") + fmt.Print(BraavosWarningMessage + "\n\n") } } @@ -136,7 +151,7 @@ func NewAccount( publicKey: publicKey, ks: keystore, CairoVersion: cairoVersion, - ChainId: new(felt.Felt).SetBytes([]byte(chainID)), + ChainID: new(felt.Felt).SetBytes([]byte(chainID)), } return account, nil @@ -158,7 +173,10 @@ func (account *Account) Nonce(ctx context.Context) (*felt.Felt, error) { // Returns: // - *felt.Felt: the precomputed address as a *felt.Felt // - error: an error if any -func PrecomputeAccountAddress(salt, classHash *felt.Felt, constructorCalldata []*felt.Felt) *felt.Felt { +func PrecomputeAccountAddress( + salt, classHash *felt.Felt, + constructorCalldata []*felt.Felt, +) *felt.Felt { return contracts.PrecomputeAddress(&felt.Zero, salt, classHash, constructorCalldata) } @@ -181,7 +199,8 @@ func (account *Account) FmtCalldata(fnCalls []rpc.FunctionCall) ([]*felt.Felt, e } } -// FmtCallDataCairo0 generates a slice of *felt.Felt that represents the calldata for the given function calls in Cairo 0 format. +// FmtCallDataCairo0 generates a slice of *felt.Felt that represents the +// calldata for the given function calls in Cairo 0 format. // // Parameters: // - fnCalls: a slice of rpc.FunctionCall containing the function calls. @@ -190,15 +209,22 @@ func (account *Account) FmtCalldata(fnCalls []rpc.FunctionCall) ([]*felt.Felt, e // - a slice of *felt.Felt representing the generated calldata. // // https://github.com/project3fusion/StarkSharp/blob/main/StarkSharp/StarkSharp.Rpc/Modules/Transactions/Hash/TransactionHash.cs#L27 +// +//nolint:lll // The link would be unclickable if we break the line. func FmtCallDataCairo0(callArray []rpc.FunctionCall) []*felt.Felt { - calldata := make([]*felt.Felt, 0, 10) //nolint:mnd - calls := make([]*felt.Felt, 0, 10) //nolint:mnd + calldata := make([]*felt.Felt, 0, 10) //nolint:mnd // Randomly chosen + calls := make([]*felt.Felt, 0, 10) //nolint:mnd // Randomly chosen calldata = append(calldata, new(felt.Felt).SetUint64(uint64(len(callArray)))) offset := uint64(0) for _, call := range callArray { - calldata = append(calldata, call.ContractAddress, call.EntryPointSelector, new(felt.Felt).SetUint64(offset)) + calldata = append( + calldata, + call.ContractAddress, + call.EntryPointSelector, + new(felt.Felt).SetUint64(offset), + ) callDataLen := uint64(len(call.Calldata)) calldata = append(calldata, new(felt.Felt).SetUint64(callDataLen)) offset += callDataLen @@ -212,7 +238,8 @@ func FmtCallDataCairo0(callArray []rpc.FunctionCall) []*felt.Felt { return calldata } -// FmtCallDataCairo2 generates the calldata for the given function calls for Cairo 2 contracts. +// FmtCallDataCairo2 generates the calldata for the given function calls for +// Cairo 2 contracts. // // Parameters: // - fnCalls: a slice of rpc.FunctionCall containing the function calls. @@ -221,8 +248,10 @@ func FmtCallDataCairo0(callArray []rpc.FunctionCall) []*felt.Felt { // - a slice of *felt.Felt representing the generated calldata. // // https://github.com/project3fusion/StarkSharp/blob/main/StarkSharp/StarkSharp.Rpc/Modules/Transactions/Hash/TransactionHash.cs#L22 +// +//nolint:lll // The link would be unclickable if we break the line. func FmtCallDataCairo2(callArray []rpc.FunctionCall) []*felt.Felt { - result := make([]*felt.Felt, 0, 10) //nolint:mnd + result := make([]*felt.Felt, 0, 10) //nolint:mnd // Randomly chosen result = append(result, new(felt.Felt).SetUint64(uint64(len(callArray)))) diff --git a/account/account_test.go b/account/account_test.go index 279e95874..a6f0d8e1f 100644 --- a/account/account_test.go +++ b/account/account_test.go @@ -33,7 +33,7 @@ func TestFmtCallData(t *testing.T) { tests.RunTestOn(t, tests.MockEnv) mockCtrl := gomock.NewController(t) - mockRpcProvider := mocks.NewMockRpcProvider(mockCtrl) + mockRPCProvider := mocks.NewMockRPCProvider(mockCtrl) type testSetType struct { CairoVersion account.CairoVersion @@ -46,7 +46,10 @@ func TestFmtCallData(t *testing.T) { CairoVersion: account.CairoV2, ChainID: "SN_SEPOLIA", FnCall: rpc.FunctionCall{ - ContractAddress: internalUtils.TestHexToFelt(t, "0x04daadb9d30c887e1ab2cf7d78dfe444a77aab5a49c3353d6d9977e7ed669902"), + ContractAddress: internalUtils.TestHexToFelt( + t, + "0x04daadb9d30c887e1ab2cf7d78dfe444a77aab5a49c3353d6d9977e7ed669902", + ), EntryPointSelector: internalUtils.GetSelectorFromNameFelt("name_set"), Calldata: []*felt.Felt{ internalUtils.TestHexToFelt(t, "0x617279616e5f676f64617261"), @@ -64,7 +67,10 @@ func TestFmtCallData(t *testing.T) { CairoVersion: account.CairoV2, ChainID: "SN_SEPOLIA", FnCall: rpc.FunctionCall{ - ContractAddress: internalUtils.TestHexToFelt(t, "0x017cE9DffA7C87a03EB496c96e04ac36c4902085030763A83a35788d475e15CA"), + ContractAddress: internalUtils.TestHexToFelt( + t, + "0x017cE9DffA7C87a03EB496c96e04ac36c4902085030763A83a35788d475e15CA", + ), EntryPointSelector: internalUtils.GetSelectorFromNameFelt("name_set"), Calldata: []*felt.Felt{ internalUtils.TestHexToFelt(t, "0x737461726b6e6574"), @@ -81,10 +87,18 @@ func TestFmtCallData(t *testing.T) { } for _, test := range testSet { - mockRpcProvider.EXPECT().ChainID(context.Background()).Return(test.ChainID, nil) + mockRPCProvider.EXPECT().ChainID(context.Background()).Return(test.ChainID, nil) // TODO: remove this once the braavos bug is fixed. Ref: https://github.com/NethermindEth/starknet.go/pull/691 - mockRpcProvider.EXPECT().ClassHashAt(context.Background(), gomock.Any(), gomock.Any()).Return(internalUtils.RANDOM_FELT, nil) - acc, err := account.NewAccount(mockRpcProvider, &felt.Zero, "pubkey", account.NewMemKeystore(), test.CairoVersion) + mockRPCProvider.EXPECT(). + ClassHashAt(context.Background(), gomock.Any(), gomock.Any()). + Return(internalUtils.DeadBeef, nil) + acc, err := account.NewAccount( + mockRPCProvider, + &felt.Zero, + "pubkey", + account.NewMemKeystore(), + test.CairoVersion, + ) require.NoError(t, err) fmtCallData, err := acc.FmtCalldata([]rpc.FunctionCall{test.FnCall}) @@ -98,7 +112,7 @@ func TestFmtCallData(t *testing.T) { // It creates a mock controller and a mock RpcProvider. It defines a test set // consisting of different ChainID and ExpectedID pairs. It then iterates over // the test set and sets the expected behaviour for the ChainID method of the -// mockRpcProvider. It creates a new account using the mockRpcProvider, +// mockRPCProvider. It creates a new account using the mockRPCProvider, // Zero value, "pubkey", and a new in-memory keystore. It asserts that the // account's ChainId matches the expected ID for each test case in the test set. // @@ -112,7 +126,7 @@ func TestChainIdMOCK(t *testing.T) { tests.RunTestOn(t, tests.MockEnv) mockCtrl := gomock.NewController(t) - mockRpcProvider := mocks.NewMockRpcProvider(mockCtrl) + mockRPCProvider := mocks.NewMockRPCProvider(mockCtrl) type testSetType struct { ChainID string @@ -132,12 +146,20 @@ func TestChainIdMOCK(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { - mockRpcProvider.EXPECT().ChainID(context.Background()).Return(test.ChainID, nil) + mockRPCProvider.EXPECT().ChainID(context.Background()).Return(test.ChainID, nil) // TODO: remove this once the braavos bug is fixed. Ref: https://github.com/NethermindEth/starknet.go/pull/691 - mockRpcProvider.EXPECT().ClassHashAt(context.Background(), gomock.Any(), gomock.Any()).Return(internalUtils.RANDOM_FELT, nil) - acc, err := account.NewAccount(mockRpcProvider, &felt.Zero, "pubkey", account.NewMemKeystore(), account.CairoV0) + mockRPCProvider.EXPECT(). + ClassHashAt(context.Background(), gomock.Any(), gomock.Any()). + Return(internalUtils.DeadBeef, nil) + acc, err := account.NewAccount( + mockRPCProvider, + &felt.Zero, + "pubkey", + account.NewMemKeystore(), + account.CairoV0, + ) require.NoError(t, err) - require.Equal(t, test.ExpectedID, acc.ChainId.String()) + require.Equal(t, test.ExpectedID, acc.ChainID.String()) } } @@ -173,9 +195,15 @@ func TestChainId(t *testing.T) { client, err := rpc.NewProvider(tConfig.providerURL) require.NoError(t, err, "Error in rpc.NewClient") - acc, err := account.NewAccount(client, &felt.Zero, "pubkey", account.NewMemKeystore(), account.CairoV0) + acc, err := account.NewAccount( + client, + &felt.Zero, + "pubkey", + account.NewMemKeystore(), + account.CairoV0, + ) require.NoError(t, err) - require.Equal(t, acc.ChainId.String(), test.ExpectedID) + require.Equal(t, acc.ChainID.String(), test.ExpectedID) } } @@ -183,7 +211,7 @@ func TestBraavosAccountWarning(t *testing.T) { tests.RunTestOn(t, tests.MockEnv) mockCtrl := gomock.NewController(t) - mockRpcProvider := mocks.NewMockRpcProvider(mockCtrl) + mockRPCProvider := mocks.NewMockRPCProvider(mockCtrl) type testSetType struct { ClassHash *felt.Felt @@ -212,7 +240,7 @@ func TestBraavosAccountWarning(t *testing.T) { ExpectedOutput: true, }, { - ClassHash: internalUtils.RANDOM_FELT, + ClassHash: internalUtils.DeadBeef, ExpectedOutput: false, }, }, @@ -221,8 +249,10 @@ func TestBraavosAccountWarning(t *testing.T) { for _, test := range testSet { t.Run("ClassHash_"+test.ClassHash.String(), func(t *testing.T) { // Set up the mock to return the Braavos class hash - mockRpcProvider.EXPECT().ClassHashAt(context.Background(), gomock.Any(), gomock.Any()).Return(test.ClassHash, nil) - mockRpcProvider.EXPECT().ChainID(context.Background()).Return("SN_SEPOLIA", nil) + mockRPCProvider.EXPECT(). + ClassHashAt(context.Background(), gomock.Any(), gomock.Any()). + Return(test.ClassHash, nil) + mockRPCProvider.EXPECT().ChainID(context.Background()).Return("SN_SEPOLIA", nil) // Create a buffer to capture stdout oldStdout := os.Stdout @@ -231,11 +261,17 @@ func TestBraavosAccountWarning(t *testing.T) { os.Stdout = w // Create the account - _, err = account.NewAccount(mockRpcProvider, internalUtils.RANDOM_FELT, "pubkey", account.NewMemKeystore(), account.CairoV2) + _, err = account.NewAccount( + mockRPCProvider, + internalUtils.DeadBeef, + "pubkey", + account.NewMemKeystore(), + account.CairoV2, + ) require.NoError(t, err) // Close the writer and restore stdout - w.Close() + require.NoError(t, w.Close()) os.Stdout = oldStdout // Read the captured output @@ -245,10 +281,10 @@ func TestBraavosAccountWarning(t *testing.T) { if test.ExpectedOutput { // Check if the warning message was printed - assert.Contains(t, buf.String(), account.BRAAVOS_WARNING_MESSAGE) + assert.Contains(t, buf.String(), account.BraavosWarningMessage) } else { // Check if the warning message was not printed - assert.NotContains(t, buf.String(), account.BRAAVOS_WARNING_MESSAGE) + assert.NotContains(t, buf.String(), account.BraavosWarningMessage) } }) } diff --git a/account/keystore.go b/account/keystore.go index 14376780c..ce45d1add 100644 --- a/account/keystore.go +++ b/account/keystore.go @@ -38,7 +38,8 @@ func NewMemKeystore() *MemKeystore { } } -// SetNewMemKeystore returns a new instance of MemKeystore and sets the given public key and private key in it. +// SetNewMemKeystore returns a new instance of MemKeystore and sets the given +// public key and private key in it. // // Parameters: // - pub: a string representing the public key @@ -79,7 +80,11 @@ func (ks *MemKeystore) Get(senderAddress string) (*big.Int, error) { defer ks.mu.Unlock() k, exists := ks.keys[senderAddress] if !exists { - return nil, fmt.Errorf("error getting key for sender %s: %w", senderAddress, ErrSenderNoExist) + return nil, fmt.Errorf( + "error getting key for sender %s: %w", + senderAddress, + ErrSenderNoExist, + ) } return k, nil @@ -96,13 +101,19 @@ func (ks *MemKeystore) Get(senderAddress string) (*big.Int, error) { // - *big.Int: the R component of the signature as *big.Int // - *big.Int: the S component of the signature as *big.Int // - error: an error if any -func (ks *MemKeystore) Sign(ctx context.Context, id string, msgHash *big.Int) (*big.Int, *big.Int, error) { +func (ks *MemKeystore) Sign( + ctx context.Context, + id string, + msgHash *big.Int, +) (r, s *big.Int, err error) { k, err := ks.Get(id) if err != nil { return nil, nil, err } - return sign(ctx, msgHash, k) + r, s, err = sign(ctx, msgHash, k) + + return r, s, err } // sign signs the given message hash with the provided key using the Curve. @@ -137,7 +148,7 @@ func sign(ctx context.Context, msgHash, key *big.Int) (x, y *big.Int, err error) // - *MemKeystore: a pointer to a MemKeystore instance // - *felt.Felt: a pointer to a public key as a felt.Felt // - *felt.Felt: a pointer to a private key as a felt.Felt -func GetRandomKeys() (*MemKeystore, *felt.Felt, *felt.Felt) { +func GetRandomKeys() (ks *MemKeystore, pubKey, privKey *felt.Felt) { // Get random keys privateKey, pubX, _, err := curve.GetRandomKeys() if err != nil { @@ -145,12 +156,12 @@ func GetRandomKeys() (*MemKeystore, *felt.Felt, *felt.Felt) { os.Exit(1) } - privFelt := internalUtils.BigIntToFelt(privateKey) - pubFelt := internalUtils.BigIntToFelt(pubX) + privKey = internalUtils.BigIntToFelt(privateKey) + pubKey = internalUtils.BigIntToFelt(pubX) // set up keystore - ks := NewMemKeystore() - ks.Put(pubFelt.String(), privateKey) + ks = NewMemKeystore() + ks.Put(pubKey.String(), privateKey) - return ks, pubFelt, privFelt + return ks, pubKey, privKey } diff --git a/account/main_test.go b/account/main_test.go index 1dbe33fed..262de3622 100644 --- a/account/main_test.go +++ b/account/main_test.go @@ -47,7 +47,7 @@ func TestMain(m *testing.M) { } // returns a new account type from the provided account data in the tConfig -func setupAcc(t *testing.T, provider rpc.RpcProvider) (*account.Account, error) { +func setupAcc(t *testing.T, provider rpc.RPCProvider) (*account.Account, error) { t.Helper() ks := account.NewMemKeystore() diff --git a/account/signature.go b/account/signature.go index 66069cc28..c4b9435ab 100644 --- a/account/signature.go +++ b/account/signature.go @@ -41,7 +41,10 @@ func (account *Account) Sign(ctx context.Context, msg *felt.Felt) ([]*felt.Felt, // // Returns: // - error: an error if there was an error in the signing or invoking process -func (account *Account) SignInvokeTransaction(ctx context.Context, invokeTx rpc.InvokeTxnType) error { +func (account *Account) SignInvokeTransaction( + ctx context.Context, + invokeTx rpc.InvokeTxnType, +) error { switch invoke := invokeTx.(type) { case *rpc.InvokeTxnV0: signature, err := signInvokeTransaction(ctx, account, invoke) @@ -62,14 +65,21 @@ func (account *Account) SignInvokeTransaction(ctx context.Context, invokeTx rpc. } invoke.Signature = signature default: - return fmt.Errorf("invalid invoke txn of type %T, did you pass a valid invoke txn pointer?", invoke) + return fmt.Errorf( + "invalid invoke txn of type %T, did you pass a valid invoke txn pointer?", + invoke, + ) } return nil } // signInvokeTransaction is a generic helper function that signs an invoke transaction. -func signInvokeTransaction[T rpc.InvokeTxnType](ctx context.Context, account *Account, invokeTx *T) ([]*felt.Felt, error) { +func signInvokeTransaction[T rpc.InvokeTxnType]( + ctx context.Context, + account *Account, + invokeTx *T, +) ([]*felt.Felt, error) { txHash, err := account.TransactionHashInvoke(*invokeTx) if err != nil { return nil, err @@ -91,7 +101,11 @@ func signInvokeTransaction[T rpc.InvokeTxnType](ctx context.Context, account *Ac // // Returns: // - error: an error if any -func (account *Account) SignDeployAccountTransaction(ctx context.Context, tx rpc.DeployAccountType, precomputeAddress *felt.Felt) error { +func (account *Account) SignDeployAccountTransaction( + ctx context.Context, + tx rpc.DeployAccountType, + precomputeAddress *felt.Felt, +) error { switch deployAcc := tx.(type) { case *rpc.DeployAccountTxnV1: signature, err := signDeployAccountTransaction(ctx, account, deployAcc, precomputeAddress) @@ -106,13 +120,17 @@ func (account *Account) SignDeployAccountTransaction(ctx context.Context, tx rpc } deployAcc.Signature = signature default: - return fmt.Errorf("invalid deploy account txn of type %T, did you pass a valid deploy account txn pointer?", deployAcc) + return fmt.Errorf( + "invalid deploy account txn of type %T, did you pass a valid deploy account txn pointer?", + deployAcc, + ) } return nil } -// signDeployAccountTransaction is a generic helper function that signs a deploy account transaction. +// signDeployAccountTransaction is a generic helper function that signs a deploy +// account transaction. func signDeployAccountTransaction[T rpc.DeployAccountType]( ctx context.Context, account *Account, @@ -166,14 +184,22 @@ func (account *Account) SignDeclareTransaction(ctx context.Context, tx rpc.Decla } declare.Signature = signature default: - return fmt.Errorf("invalid declare txn of type %T, did you pass a valid declare txn pointer?", declare) + return fmt.Errorf( + "invalid declare txn of type %T, did you pass a valid declare txn pointer?", + declare, + ) } return nil } -// signDeclareTransaction is a generic helper function that signs a declare transaction. -func signDeclareTransaction[T rpc.DeclareTxnType](ctx context.Context, account *Account, tx *T) ([]*felt.Felt, error) { +// signDeclareTransaction is a generic helper function that signs a declare +// transaction. +func signDeclareTransaction[T rpc.DeclareTxnType]( + ctx context.Context, + account *Account, + tx *T, +) ([]*felt.Felt, error) { txHash, err := account.TransactionHashDeclare(*tx) if err != nil { return nil, err @@ -186,7 +212,8 @@ func signDeclareTransaction[T rpc.DeclareTxnType](ctx context.Context, account * return signature, nil } -// Verifies the validity of the signature for a given message hash using the account's public key. +// Verifies the validity of the signature for a given message hash using the +// account's public key. // // Parameters: // - msgHash: The message hash to be verified diff --git a/account/signature_test.go b/account/signature_test.go index bc5b893bf..e659308f6 100644 --- a/account/signature_test.go +++ b/account/signature_test.go @@ -22,17 +22,20 @@ func TestVerify(t *testing.T) { // setup mock account mockCtrl := gomock.NewController(t) - mockRpcProvider := mocks.NewMockRpcProvider(mockCtrl) - mockRpcProvider.EXPECT().ChainID(context.Background()).Return(gomock.Any().String(), nil) + mockRPCProvider := mocks.NewMockRPCProvider(mockCtrl) + mockRPCProvider.EXPECT().ChainID(context.Background()).Return(gomock.Any().String(), nil) // TODO: remove this once the braavos bug is fixed. Ref: https://github.com/NethermindEth/starknet.go/pull/691 - mockRpcProvider.EXPECT(). + mockRPCProvider.EXPECT(). ClassHashAt(context.Background(), gomock.Any(), gomock.Any()). - Return(internalUtils.RANDOM_FELT, nil) + Return(internalUtils.DeadBeef, nil) ks := account.NewMemKeystore() - accAddress := internalUtils.TestHexToFelt(t, "0x2d54b7dc47eafa80f8e451cf39e7601f51fef6f1bfe5cea44ff12fa563e5457") + accAddress := internalUtils.TestHexToFelt( + t, + "0x2d54b7dc47eafa80f8e451cf39e7601f51fef6f1bfe5cea44ff12fa563e5457", + ) acc, err := account.NewAccount( - mockRpcProvider, + mockRPCProvider, accAddress, "0x3904dda2cdd58e15dd8667b51a49deec6ce9c53e17b28fffb28fe9ccfddda92", ks, diff --git a/account/transaction.go b/account/transaction.go index cc84d2649..c16e0cdcd 100644 --- a/account/transaction.go +++ b/account/transaction.go @@ -12,14 +12,18 @@ import ( "github.com/NethermindEth/starknet.go/utils" ) -// BuildAndSendInvokeTxn builds and sends a v3 invoke transaction with the given function calls. -// It automatically calculates the nonce, formats the calldata, estimates fees, and signs the transaction with the account's private key. +// BuildAndSendInvokeTxn builds and sends a v3 invoke transaction with the +// given function calls. It automatically calculates the nonce, formats the +// calldata, estimates fees, and signs the transaction with the account's private +// key. // // Parameters: // - ctx: The context.Context for the request. -// - functionCalls: A slice of rpc.InvokeFunctionCall representing the function calls for the transaction, allowing either single or -// multiple function calls in the same transaction. -// - opts: options for building/estimating the transaction. Pass `nil` to use default values. +// - functionCalls: A slice of rpc.InvokeFunctionCall representing the function +// calls for the transaction, allowing either single or multiple function calls +// in the same transaction. +// - opts: options for building/estimating the transaction. Pass `nil` to use +// default values. // // Returns: // - rpc.AddInvokeTransactionResponse: the response of the submitted transaction. @@ -75,10 +79,12 @@ func (account *Account) BuildAndSendInvokeTxn( txnFee := estimateFee[0] broadcastInvokeTxnV3.ResourceBounds = utils.FeeEstToResBoundsMap(txnFee, opts.Multiplier) - // assuring the signed txn version will be rpc.TransactionV3, since queryBit txn version is only used for estimation/simulation + // assuring the signed txn version will be rpc.TransactionV3, since queryBit + // txn version is only used for estimation/simulation broadcastInvokeTxnV3.Version = rpc.TransactionV3 - // signing the txn again with the estimated fee, as the fee value is used in the txn hash calculation + // signing the txn again with the estimated fee, as the fee value is used in + // the txn hash calculation err = account.SignInvokeTransaction(ctx, broadcastInvokeTxnV3) if err != nil { return response, err @@ -92,14 +98,16 @@ func (account *Account) BuildAndSendInvokeTxn( return response, nil } -// BuildAndSendDeclareTxn builds and sends a v3 declare transaction. -// It automatically calculates the nonce, formats the calldata, estimates fees, and signs the transaction with the account's private key. +// BuildAndSendDeclareTxn builds and sends a v3 declare transaction. It +// automatically calculates the nonce, formats the calldata, estimates fees, and +// signs the transaction with the account's private key. // // Parameters: // - ctx: The context.Context for the request. // - casmClass: The casm class of the contract to be declared // - contractClass: The sierra contract class of the contract to be declared -// - opts: options for building/estimating the transaction. Pass `nil` to use default values. +// - opts: options for building/estimating the transaction. Pass `nil` to use +// default values. // // Returns: // - rpc.AddDeclareTransactionResponse: the response of the submitted transaction. @@ -155,10 +163,12 @@ func (account *Account) BuildAndSendDeclareTxn( txnFee := estimateFee[0] broadcastDeclareTxnV3.ResourceBounds = utils.FeeEstToResBoundsMap(txnFee, opts.Multiplier) - // assuring the signed txn version will be rpc.TransactionV3, since queryBit txn version is only used for estimation/simulation + // assuring the signed txn version will be rpc.TransactionV3, since queryBit + // txn version is only used for estimation/simulation broadcastDeclareTxnV3.Version = rpc.TransactionV3 - // signing the txn again with the estimated fee, as the fee value is used in the txn hash calculation + // signing the txn again with the estimated fee, as the fee value is used in + // the txn hash calculation err = account.SignDeclareTransaction(ctx, broadcastDeclareTxnV3) if err != nil { return response, err @@ -172,22 +182,28 @@ func (account *Account) BuildAndSendDeclareTxn( return response, nil } -// BuildAndEstimateDeployAccountTxn builds and signs a v3 deploy account transaction, estimates the fee, and computes the address. +// BuildAndEstimateDeployAccountTxn builds and signs a v3 deploy account +// transaction, estimates the fee, and computes the address. // -// This function doesn't send the transaction because the precomputed account address requires funding first. This address is calculated -// deterministically and returned by this function, and must be funded with the appropriate amount of STRK tokens. Without sufficient -// funds, the transaction will fail. See the 'examples/deployAccount/' for more details on how to do this. +// This function doesn't send the transaction because the precomputed account +// address requires funding first. This address is calculated deterministically +// and returned by this function, and must be funded with the appropriate amount +// of STRK tokens. Without sufficient funds, the transaction will fail. See the +// 'examples/deployAccount/' for more details on how to do this. // // Parameters: // - ctx: The context.Context for the request. // - salt: the salt for the address of the deployed contract // - classHash: the class hash of the contract to be deployed // - constructorCalldata: the parameters passed to the constructor -// - opts: options for building/estimating the transaction. Pass `nil` to use default values. +// - opts: options for building/estimating the transaction. Pass `nil` to use +// default values. // // Returns: -// - *rpc.BroadcastDeployAccountTxnV3: the transaction to be broadcasted, signed and with the estimated fee based on the multiplier -// - *felt.Felt: the precomputed account address as a *felt.Felt, it needs to be funded with appropriate amount of tokens +// - *rpc.BroadcastDeployAccountTxnV3: the transaction to be broadcasted, signed +// and with the estimated fee based on the multiplier +// - *felt.Felt: the precomputed account address as a *felt.Felt, it needs to be +// funded with appropriate amount of tokens // - error: an error if any func (account *Account) BuildAndEstimateDeployAccountTxn( ctx context.Context, @@ -234,10 +250,12 @@ func (account *Account) BuildAndEstimateDeployAccountTxn( txnFee := estimateFee[0] broadcastDepAccTxnV3.ResourceBounds = utils.FeeEstToResBoundsMap(txnFee, opts.Multiplier) - // assuring the signed txn version will be rpc.TransactionV3, since queryBit txn version is only used for estimation/simulation + // assuring the signed txn version will be rpc.TransactionV3, since queryBit + // txn version is only used for estimation/simulation broadcastDepAccTxnV3.Version = rpc.TransactionV3 - // signing the txn again with the estimated fee, as the fee value is used in the txn hash calculation + // signing the txn again with the estimated fee, as the fee value is used in + // the txn hash calculation err = account.SignDeployAccountTransaction(ctx, broadcastDepAccTxnV3, precomputedAddress) if err != nil { return nil, nil, err @@ -251,13 +269,18 @@ func (account *Account) BuildAndEstimateDeployAccountTxn( // Parameters: // - ctx: The context.Context for the request. // - classHash: The class hash of the contract to be deployed. -// - constructorCalldata: The parameters passed to the constructor. Pass `nil` if the constructor has no arguments. -// - txnOpts: The options for building/estimating the transaction. Pass `nil` to use default values. -// - udcOpts: The options for building the UDC calldata. Pass `nil` to use default values. +// - constructorCalldata: The parameters passed to the constructor. Pass `nil` if +// the constructor has no arguments. +// - txnOpts: The options for building/estimating the transaction. Pass `nil` to +// use default values. +// - udcOpts: The options for building the UDC calldata. Pass `nil` to use +// default values. // // Returns: -// - *rpc.AddInvokeTransactionResponse: the response of the submitted UDC transaction. -// - *felt.Felt: the salt used for the UDC deployment (either the provided one or the random one) +// - *rpc.AddInvokeTransactionResponse: the response of the submitted UDC +// transaction. +// - *felt.Felt: the salt used for the UDC deployment (either the provided one or +// the random one) // - error: An error if any. func (account *Account) DeployContractWithUDC( ctx context.Context, @@ -272,7 +295,11 @@ func (account *Account) DeployContractWithUDC( return response, nil, err } - response, err = account.BuildAndSendInvokeTxn(context.Background(), []rpc.InvokeFunctionCall{udcCallData}, txnOpts) + response, err = account.BuildAndSendInvokeTxn( + context.Background(), + []rpc.InvokeFunctionCall{udcCallData}, + txnOpts, + ) if err != nil { return response, nil, err } @@ -280,17 +307,23 @@ func (account *Account) DeployContractWithUDC( return response, salt, nil } -// SendTransaction can send Invoke, Declare, and Deploy transactions. It provides a unified way to send different transactions. -// It can only send v3 transactions. +// SendTransaction can send Invoke, Declare, and Deploy transactions. It +// provides a unified way to send different transactions. It can only send v3 +// transactions. // // Parameters: // - ctx: the context.Context object for the transaction. -// - txn: the Broadcast V3 Transaction to be sent. +// - txn: the Broadcast V3 Transaction to be sent // // Returns: -// - rpc.TransactionResponse: the transaction response. -// - error: an error if any. -func (account *Account) SendTransaction(ctx context.Context, txn rpc.BroadcastTxn) (rpc.TransactionResponse, error) { +// - rpc.TransactionResponse: the transaction response for each TransactionResponse +// - error: an error if any +// +//nolint:exhaustruct // Setting only the correct fields +func (account *Account) SendTransaction( + ctx context.Context, + txn rpc.BroadcastTxn, +) (rpc.TransactionResponse, error) { var response rpc.TransactionResponse switch tx := txn.(type) { // broadcast invoke v3, pointer and struct @@ -300,14 +333,14 @@ func (account *Account) SendTransaction(ctx context.Context, txn rpc.BroadcastTx return response, err } - return rpc.TransactionResponse{Hash: resp.Hash}, nil //nolint:exhaustruct + return rpc.TransactionResponse{Hash: resp.Hash}, nil case rpc.BroadcastInvokeTxnV3: resp, err := account.Provider.AddInvokeTransaction(ctx, &tx) if err != nil { return response, err } - return rpc.TransactionResponse{Hash: resp.Hash}, nil //nolint:exhaustruct + return rpc.TransactionResponse{Hash: resp.Hash}, nil // broadcast declare v3, pointer and struct case *rpc.BroadcastDeclareTxnV3: resp, err := account.Provider.AddDeclareTransaction(ctx, tx) @@ -315,14 +348,20 @@ func (account *Account) SendTransaction(ctx context.Context, txn rpc.BroadcastTx return response, err } - return rpc.TransactionResponse{Hash: resp.Hash, ClassHash: resp.ClassHash}, nil //nolint:exhaustruct + return rpc.TransactionResponse{ + Hash: resp.Hash, + ClassHash: resp.ClassHash, + }, nil case rpc.BroadcastDeclareTxnV3: resp, err := account.Provider.AddDeclareTransaction(ctx, &tx) if err != nil { return response, err } - return rpc.TransactionResponse{Hash: resp.Hash, ClassHash: resp.ClassHash}, nil //nolint:exhaustruct + return rpc.TransactionResponse{ + Hash: resp.Hash, + ClassHash: resp.ClassHash, + }, nil // broadcast deploy account v3, pointer and struct case *rpc.BroadcastDeployAccountTxnV3: resp, err := account.Provider.AddDeployAccountTransaction(ctx, tx) @@ -330,29 +369,39 @@ func (account *Account) SendTransaction(ctx context.Context, txn rpc.BroadcastTx return response, err } - return rpc.TransactionResponse{Hash: resp.Hash, ContractAddress: resp.ContractAddress}, nil //nolint:exhaustruct + return rpc.TransactionResponse{ + Hash: resp.Hash, + ContractAddress: resp.ContractAddress, + }, nil case rpc.BroadcastDeployAccountTxnV3: resp, err := account.Provider.AddDeployAccountTransaction(ctx, &tx) if err != nil { return response, err } - return rpc.TransactionResponse{Hash: resp.Hash, ContractAddress: resp.ContractAddress}, nil //nolint:exhaustruct + return rpc.TransactionResponse{ + Hash: resp.Hash, + ContractAddress: resp.ContractAddress, + }, nil default: - return response, fmt.Errorf("unsupported transaction type: should be a v3 transaction, instead got %T", tx) + return response, fmt.Errorf( + "unsupported transaction type: should be a v3 transaction, instead got %T", + tx, + ) } } -// WaitForTransactionReceipt waits for the transaction receipt of the given transaction hash to succeed or fail. +// WaitForTransactionReceipt waits for the transaction receipt of the given +// transaction hash to succeed or fail. // // Parameters: // - ctx: The context // - transactionHash: The hash // - pollInterval: The time interval to poll the transaction receipt // -// It returns: +// Returns: // - *rpc.TransactionReceiptWithBlockInfo: the transaction receipt -// - error: an error +// - error: an error if any func (account *Account) WaitForTransactionReceipt( ctx context.Context, transactionHash *felt.Felt, @@ -367,7 +416,8 @@ func (account *Account) WaitForTransactionReceipt( receiptWithBlockInfo, err := account.Provider.TransactionReceipt(ctx, transactionHash) if err != nil { rpcErr := err.(*rpc.RPCError) - if rpcErr.Code == rpc.ErrHashNotFound.Code && rpcErr.Message == rpc.ErrHashNotFound.Message { + if rpcErr.Code == rpc.ErrHashNotFound.Code && + rpcErr.Message == rpc.ErrHashNotFound.Message { continue } else { return nil, err diff --git a/account/transaction_test.go b/account/transaction_test.go index abfe421d5..8bb3ec887 100644 --- a/account/transaction_test.go +++ b/account/transaction_test.go @@ -39,9 +39,12 @@ func TestBuildAndSendInvokeTxn(t *testing.T) { resp, err := acc.BuildAndSendInvokeTxn(context.Background(), []rpc.InvokeFunctionCall{ { // same ERC20 contract as in examples/simpleInvoke - ContractAddress: internalUtils.TestHexToFelt(t, "0x0669e24364ce0ae7ec2864fb03eedbe60cfbc9d1c74438d10fa4b86552907d54"), - FunctionName: "mint", - CallData: []*felt.Felt{new(felt.Felt).SetUint64(10000), &felt.Zero}, + ContractAddress: internalUtils.TestHexToFelt( + t, + "0x0669e24364ce0ae7ec2864fb03eedbe60cfbc9d1c74438d10fa4b86552907d54", + ), + FunctionName: "mint", + CallData: []*felt.Felt{new(felt.Felt).SetUint64(10000), &felt.Zero}, }, }, nil) require.NoError(t, err, "Error building and sending invoke txn") @@ -50,7 +53,11 @@ func TestBuildAndSendInvokeTxn(t *testing.T) { require.NotNil(t, resp.Hash) t.Logf("Invoke transaction hash: %s", resp.Hash) - txReceipt, err := acc.WaitForTransactionReceipt(context.Background(), resp.Hash, 500*time.Millisecond) + txReceipt, err := acc.WaitForTransactionReceipt( + context.Background(), + resp.Hash, + 500*time.Millisecond, + ) require.NoError(t, err, "Error waiting for invoke transaction receipt") assert.Equal(t, rpc.TxnExecutionStatusSUCCEEDED, txReceipt.ExecutionStatus) @@ -100,7 +107,11 @@ func TestBuildAndSendDeclareTxn(t *testing.T) { t.Logf("Declare transaction hash: %s", resp.Hash) t.Logf("Class hash: %s", resp.ClassHash) - txReceipt, err := acc.WaitForTransactionReceipt(context.Background(), resp.Hash, 500*time.Millisecond) + txReceipt, err := acc.WaitForTransactionReceipt( + context.Background(), + resp.Hash, + 500*time.Millisecond, + ) require.NoError(t, err, "Error waiting for declare transaction receipt") assert.Equal(t, rpc.TxnExecutionStatusSUCCEEDED, txReceipt.ExecutionStatus) @@ -132,7 +143,10 @@ func TestBuildAndEstimateDeployAccountTxn(t *testing.T) { } // OpenZeppelin Account Class Hash in Sepolia - classHash := internalUtils.TestHexToFelt(t, "0x61dac032f228abef9c6626f995015233097ae253a7f72d68552db02f2971b8f") + classHash := internalUtils.TestHexToFelt( + t, + "0x61dac032f228abef9c6626f995015233097ae253a7f72d68552db02f2971b8f", + ) // Build, estimate the fee and precompute the address of the new account deployAccTxn, precomputedAddress, err := tempAcc.BuildAndEstimateDeployAccountTxn( @@ -165,7 +179,11 @@ func TestBuildAndEstimateDeployAccountTxn(t *testing.T) { t.Logf("Deploy account transaction hash: %s", resp.Hash) require.NotNil(t, resp.ContractAddress) - txReceipt, err := acc.WaitForTransactionReceipt(context.Background(), resp.Hash, 500*time.Millisecond) + txReceipt, err := acc.WaitForTransactionReceipt( + context.Background(), + resp.Hash, + 500*time.Millisecond, + ) require.NoError(t, err, "Error waiting for deploy account transaction receipt") assert.Equal(t, rpc.TxnExecutionStatusSUCCEEDED, txReceipt.ExecutionStatus) @@ -173,7 +191,11 @@ func TestBuildAndEstimateDeployAccountTxn(t *testing.T) { // a helper function that transfers STRK tokens to a given address and waits for confirmation, // used to fund the new account with STRK tokens in the TestBuildAndEstimateDeployAccountTxn test -func transferSTRKAndWaitConfirmation(t *testing.T, acc *account.Account, amount, recipient *felt.Felt) { +func transferSTRKAndWaitConfirmation( + t *testing.T, + acc *account.Account, + amount, recipient *felt.Felt, +) { t.Helper() // Build and send invoke txn u256Amount, err := internalUtils.HexToU256Felt(amount.String()) @@ -181,9 +203,12 @@ func transferSTRKAndWaitConfirmation(t *testing.T, acc *account.Account, amount, resp, err := acc.BuildAndSendInvokeTxn(context.Background(), []rpc.InvokeFunctionCall{ { // STRK contract address in Sepolia - ContractAddress: internalUtils.TestHexToFelt(t, "0x04718f5a0Fc34cC1AF16A1cdee98fFB20C31f5cD61D6Ab07201858f4287c938D"), - FunctionName: "transfer", - CallData: append([]*felt.Felt{recipient}, u256Amount...), + ContractAddress: internalUtils.TestHexToFelt( + t, + "0x04718f5a0Fc34cC1AF16A1cdee98fFB20C31f5cD61D6Ab07201858f4287c938D", + ), + FunctionName: "transfer", + CallData: append([]*felt.Felt{recipient}, u256Amount...), }, }, nil) require.NoError(t, err, "Error transferring STRK tokens") @@ -192,10 +217,20 @@ func transferSTRKAndWaitConfirmation(t *testing.T, acc *account.Account, amount, require.NotNil(t, resp.Hash) t.Logf("Transfer transaction hash: %s", resp.Hash) - txReceipt, err := acc.WaitForTransactionReceipt(context.Background(), resp.Hash, 500*time.Millisecond) + txReceipt, err := acc.WaitForTransactionReceipt( + context.Background(), + resp.Hash, + 500*time.Millisecond, + ) require.NoError(t, err, "Error waiting for transfer transaction receipt") - err = waitForTransactionStatus(context.Background(), acc.Provider, resp.Hash, rpc.TxnStatus_Accepted_On_L2, 500*time.Millisecond) + err = waitForTransactionStatus( + context.Background(), + acc.Provider, + resp.Hash, + rpc.TxnStatusAcceptedOnL2, + 500*time.Millisecond, + ) require.NoError(t, err, "Error waiting for transfer transaction status") assert.Equal(t, rpc.TxnExecutionStatusSUCCEEDED, txReceipt.ExecutionStatus) @@ -204,7 +239,7 @@ func transferSTRKAndWaitConfirmation(t *testing.T, acc *account.Account, amount, // TODO: make it an exported utility function func waitForTransactionStatus( ctx context.Context, - provider rpc.RpcProvider, + provider rpc.RPCProvider, transactionHash *felt.Felt, txnStatus rpc.TxnStatus, pollInterval time.Duration, @@ -215,10 +250,11 @@ func waitForTransactionStatus( case <-ctx.Done(): return rpcerr.Err(rpcerr.InternalError, rpc.StringErrData(ctx.Err().Error())) case <-t.C: - returnedTxnStatus, err := provider.GetTransactionStatus(ctx, transactionHash) + returnedTxnStatus, err := provider.TransactionStatus(ctx, transactionHash) if err != nil { rpcErr := err.(*rpc.RPCError) - if rpcErr.Code == rpc.ErrHashNotFound.Code && rpcErr.Message == rpc.ErrHashNotFound.Message { + if rpcErr.Code == rpc.ErrHashNotFound.Code && + rpcErr.Message == rpc.ErrHashNotFound.Message { continue } else { return err @@ -250,46 +286,61 @@ func TestBuildAndSendMethodsWithQueryBit(t *testing.T) { tests.RunTestOn(t, tests.MockEnv) ctrl := gomock.NewController(t) - mockRpcProvider := mocks.NewMockRpcProvider(ctrl) + mockRPCProvider := mocks.NewMockRPCProvider(ctrl) - mockRpcProvider.EXPECT().Nonce(gomock.Any(), gomock.Any(), gomock.Any()).Return(new(felt.Felt).SetUint64(1), nil).Times(2) + mockRPCProvider.EXPECT(). + Nonce(gomock.Any(), gomock.Any(), gomock.Any()). + Return(new(felt.Felt).SetUint64(1), nil). + Times(2) ks, pub, _ := account.GetRandomKeys() // called when instantiating the account - mockRpcProvider.EXPECT().ClassHashAt(gomock.Any(), gomock.Any(), gomock.Any()).Return(internalUtils.RANDOM_FELT, nil).Times(1) - mockRpcProvider.EXPECT().ChainID(gomock.Any()).Return("SN_SEPOLIA", nil).Times(1) - acnt, err := account.NewAccount(mockRpcProvider, internalUtils.RANDOM_FELT, pub.String(), ks, account.CairoV2) + mockRPCProvider.EXPECT(). + ClassHashAt(gomock.Any(), gomock.Any(), gomock.Any()). + Return(internalUtils.DeadBeef, nil). + Times(1) + mockRPCProvider.EXPECT().ChainID(gomock.Any()).Return("SN_SEPOLIA", nil).Times(1) + acnt, err := account.NewAccount( + mockRPCProvider, + internalUtils.DeadBeef, + pub.String(), + ks, + account.CairoV2, + ) require.NoError(t, err) // setting the expected behaviour for each call to EstimateFee, // asserting if the passed txn has the query bit version - mockRpcProvider.EXPECT().EstimateFee(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( - func(_, request, _, _ any) ([]rpc.FeeEstimation, error) { - reqArr, ok := request.([]rpc.BroadcastTxn) - require.True(t, ok) - txn, ok := reqArr[0].(rpc.Transaction) - require.True(t, ok) + mockRPCProvider.EXPECT(). + EstimateFee(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + DoAndReturn( + func(_, request, _, _ any) ([]rpc.FeeEstimation, error) { + reqArr, ok := request.([]rpc.BroadcastTxn) + require.True(t, ok) + txn, ok := reqArr[0].(rpc.Transaction) + require.True(t, ok) - // assert that the transaction being estimated has the query bit version - assert.Equal(t, txn.GetVersion(), rpc.TransactionV3WithQueryBit) - - return []rpc.FeeEstimation{ - { - FeeEstimationCommon: rpc.FeeEstimationCommon{ - L1GasPrice: new(felt.Felt).SetUint64(10), - L1GasConsumed: new(felt.Felt).SetUint64(100), - L1DataGasPrice: new(felt.Felt).SetUint64(5), - L1DataGasConsumed: new(felt.Felt).SetUint64(50), - L2GasPrice: new(felt.Felt).SetUint64(3), - L2GasConsumed: new(felt.Felt).SetUint64(200), + // assert that the transaction being estimated has the query bit version + assert.Equal(t, txn.GetVersion(), rpc.TransactionV3WithQueryBit) + + return []rpc.FeeEstimation{ + { + FeeEstimationCommon: rpc.FeeEstimationCommon{ + L1GasPrice: new(felt.Felt).SetUint64(10), + L1GasConsumed: new(felt.Felt).SetUint64(100), + L1DataGasPrice: new(felt.Felt).SetUint64(5), + L1DataGasConsumed: new(felt.Felt).SetUint64(50), + L2GasPrice: new(felt.Felt).SetUint64(3), + L2GasConsumed: new(felt.Felt).SetUint64(200), + }, }, - }, - }, nil - }, - ).Times(3) + }, nil + }, + ). + Times(3) t.Run("BuildAndSendInvokeTxn", func(t *testing.T) { - mockRpcProvider.EXPECT().AddInvokeTransaction(gomock.Any(), gomock.Any()).DoAndReturn( + mockRPCProvider.EXPECT().AddInvokeTransaction(gomock.Any(), gomock.Any()).DoAndReturn( func(_, txn any) (rpc.AddInvokeTransactionResponse, error) { bcTxn, ok := txn.(*rpc.BroadcastInvokeTxnV3) require.True(t, ok) @@ -303,7 +354,7 @@ func TestBuildAndSendMethodsWithQueryBit(t *testing.T) { _, err = acnt.BuildAndSendInvokeTxn(context.Background(), []rpc.InvokeFunctionCall{ { - ContractAddress: internalUtils.RANDOM_FELT, + ContractAddress: internalUtils.DeadBeef, FunctionName: "transfer", }, }, &account.TxnOptions{ @@ -313,7 +364,7 @@ func TestBuildAndSendMethodsWithQueryBit(t *testing.T) { }) t.Run("BuildAndSendDeclareTxn", func(t *testing.T) { - mockRpcProvider.EXPECT().AddDeclareTransaction(gomock.Any(), gomock.Any()).DoAndReturn( + mockRPCProvider.EXPECT().AddDeclareTransaction(gomock.Any(), gomock.Any()).DoAndReturn( func(_, txn any) (rpc.AddDeclareTransactionResponse, error) { bcTxn, ok := txn.(*rpc.BroadcastDeclareTxnV3) require.True(t, ok) @@ -325,9 +376,14 @@ func TestBuildAndSendMethodsWithQueryBit(t *testing.T) { }, ) - _, err = acnt.BuildAndSendDeclareTxn(context.Background(), &casmClass, &class, &account.TxnOptions{ - UseQueryBit: true, - }) + _, err = acnt.BuildAndSendDeclareTxn( + context.Background(), + &casmClass, + &class, + &account.TxnOptions{ + UseQueryBit: true, + }, + ) require.NoError(t, err) }) @@ -335,7 +391,7 @@ func TestBuildAndSendMethodsWithQueryBit(t *testing.T) { txn, _, err := acnt.BuildAndEstimateDeployAccountTxn( context.Background(), pub, - internalUtils.RANDOM_FELT, + internalUtils.DeadBeef, []*felt.Felt{pub}, &account.TxnOptions{ UseQueryBit: true, @@ -360,9 +416,14 @@ func TestBuildAndSendMethodsWithQueryBit(t *testing.T) { acnt := newDevnetAccount(t, client, acnts[0], account.CairoV2) t.Run("BuildAndSendDeclareTxn", func(t *testing.T) { - resp, err := acnt.BuildAndSendDeclareTxn(context.Background(), &casmClass, &class, &account.TxnOptions{ - UseQueryBit: true, - }) + resp, err := acnt.BuildAndSendDeclareTxn( + context.Background(), + &casmClass, + &class, + &account.TxnOptions{ + UseQueryBit: true, + }, + ) require.NoError(t, err) txn, err := client.TransactionByHash(context.Background(), resp.Hash) @@ -381,9 +442,12 @@ func TestBuildAndSendMethodsWithQueryBit(t *testing.T) { resp, err := acnt.BuildAndSendInvokeTxn(context.Background(), []rpc.InvokeFunctionCall{ { // STRK contract address in Sepolia - ContractAddress: internalUtils.TestHexToFelt(t, "0x04718f5a0Fc34cC1AF16A1cdee98fFB20C31f5cD61D6Ab07201858f4287c938D"), - FunctionName: "transfer", - CallData: append([]*felt.Felt{acntaddr2}, u256Amount...), + ContractAddress: internalUtils.TestHexToFelt( + t, + "0x04718f5a0Fc34cC1AF16A1cdee98fFB20C31f5cD61D6Ab07201858f4287c938D", + ), + FunctionName: "transfer", + CallData: append([]*felt.Felt{acntaddr2}, u256Amount...), }, }, &account.TxnOptions{ UseQueryBit: true, @@ -461,7 +525,7 @@ func TestSendInvokeTxn(t *testing.T) { PrivKey: internalUtils.TestHexToFelt(t, "0x04818374f8071c3b4c3070ff7ce766e7b9352628df7b815ea4de26e0fadb5cc9"), // InvokeTx: rpc.BroadcastInvokeTxnV3{ Nonce: internalUtils.TestHexToFelt(t, "0xd"), - Type: rpc.TransactionType_Invoke, + Type: rpc.TransactionTypeInvoke, Version: rpc.TransactionV3, Signature: []*felt.Felt{ internalUtils.TestHexToFelt(t, "0x7bff07f1c2f6dc0eeaa9e622a0ee35f6e2e9855b39ed757236970a71b7c9e2e"), @@ -512,7 +576,13 @@ func TestSendInvokeTxn(t *testing.T) { ks.Put(test.PubKey.String(), fakePrivKeyBI) } - acnt, err := account.NewAccount(client, test.AccountAddress, test.PubKey.String(), ks, account.CairoV2) + acnt, err := account.NewAccount( + client, + test.AccountAddress, + test.PubKey.String(), + ks, + account.CairoV2, + ) require.NoError(t, err) err = acnt.SignInvokeTransaction(context.Background(), &test.InvokeTx) @@ -521,7 +591,12 @@ func TestSendInvokeTxn(t *testing.T) { resp, err := acnt.SendTransaction(context.Background(), test.InvokeTx) if err != nil { rpcErr := err.(*rpc.RPCError) - require.Equal(t, test.ExpectedErr.Code, rpcErr.Code, "AddInvokeTransaction returned an unexpected error") + require.Equal( + t, + test.ExpectedErr.Code, + rpcErr.Code, + "AddInvokeTransaction returned an unexpected error", + ) require.Zero(t, resp) } } @@ -541,12 +616,27 @@ func TestSendInvokeTxn(t *testing.T) { func TestSendDeclareTxn(t *testing.T) { tests.RunTestOn(t, tests.TestnetEnv) - expectedTxHash := internalUtils.TestHexToFelt(t, "0x1c3df33f06f0da7f5df72bbc02fb8caf33e91bdd2433305dd007c6cd6acc6d0") - expectedClassHash := internalUtils.TestHexToFelt(t, "0x06ff9f7df06da94198ee535f41b214dce0b8bafbdb45e6c6b09d4b3b693b1f17") + expectedTxHash := internalUtils.TestHexToFelt( + t, + "0x1c3df33f06f0da7f5df72bbc02fb8caf33e91bdd2433305dd007c6cd6acc6d0", + ) + expectedClassHash := internalUtils.TestHexToFelt( + t, + "0x06ff9f7df06da94198ee535f41b214dce0b8bafbdb45e6c6b09d4b3b693b1f17", + ) - AccountAddress := internalUtils.TestHexToFelt(t, "0x01AE6Fe02FcD9f61A3A8c30D68a8a7c470B0d7dD6F0ee685d5BBFa0d79406ff9") - PubKey := internalUtils.TestHexToFelt(t, "0x022288424ec8116c73d2e2ed3b0663c5030d328d9c0fb44c2b54055db467f31e") - PrivKey := internalUtils.TestHexToFelt(t, "0x04818374f8071c3b4c3070ff7ce766e7b9352628df7b815ea4de26e0fadb5cc9") + AccountAddress := internalUtils.TestHexToFelt( + t, + "0x01AE6Fe02FcD9f61A3A8c30D68a8a7c470B0d7dD6F0ee685d5BBFa0d79406ff9", + ) + PubKey := internalUtils.TestHexToFelt( + t, + "0x022288424ec8116c73d2e2ed3b0663c5030d328d9c0fb44c2b54055db467f31e", + ) + PrivKey := internalUtils.TestHexToFelt( + t, + "0x04818374f8071c3b4c3070ff7ce766e7b9352628df7b815ea4de26e0fadb5cc9", + ) ks := account.NewMemKeystore() fakePrivKeyBI, ok := new(big.Int).SetString(PrivKey.String(), 0) @@ -568,13 +658,19 @@ func TestSendDeclareTxn(t *testing.T) { require.NoError(t, err) broadcastTx := rpc.BroadcastDeclareTxnV3{ - Type: rpc.TransactionType_Declare, + Type: rpc.TransactionTypeDeclare, SenderAddress: AccountAddress, CompiledClassHash: compClassHash, Version: rpc.TransactionV3, Signature: []*felt.Felt{ - internalUtils.TestHexToFelt(t, "0x74a20e84469ecf7bfaa7eb82a803621357b695af5ac6f857c0615c7e9fa94e3"), - internalUtils.TestHexToFelt(t, "0x3a79c411c05fc60fe6da68bd4a1cc57745a7e1e6cfa95dd7c3466fae384cfc3"), + internalUtils.TestHexToFelt( + t, + "0x74a20e84469ecf7bfaa7eb82a803621357b695af5ac6f857c0615c7e9fa94e3", + ), + internalUtils.TestHexToFelt( + t, + "0x3a79c411c05fc60fe6da68bd4a1cc57745a7e1e6cfa95dd7c3466fae384cfc3", + ), }, Nonce: internalUtils.TestHexToFelt(t, "0xe"), ContractClass: &class, @@ -606,7 +702,12 @@ func TestSendDeclareTxn(t *testing.T) { if err != nil { rpcErr := err.(*rpc.RPCError) - require.Equal(t, rpc.ErrInvalidTransactionNonce.Code, rpcErr.Code, "AddDeclareTransaction error not what expected") + require.Equal( + t, + rpc.ErrInvalidTransactionNonce.Code, + rpcErr.Code, + "AddDeclareTransaction error not what expected", + ) } else { require.Equal(t, expectedTxHash.String(), resp.Hash.String(), "AddDeclareTransaction TxHash not what expected") require.Equal(t, expectedClassHash.String(), resp.ClassHash.String(), "AddDeclareTransaction ClassHash not what expected") @@ -650,7 +751,7 @@ func TestSendDeployAccountDevnet(t *testing.T) { require.NoError(t, err) tx := rpc.DeployAccountTxnV3{ - Type: rpc.TransactionType_DeployAccount, + Type: rpc.TransactionTypeDeployAccount, Version: rpc.TransactionV3, Signature: []*felt.Felt{}, Nonce: &felt.Zero, // Contract accounts start with nonce zero. @@ -677,8 +778,15 @@ func TestSendDeployAccountDevnet(t *testing.T) { FeeMode: rpc.DAModeL1, } - precomputedAddress := account.PrecomputeAccountAddress(fakeUserPub, classHash, tx.ConstructorCalldata) - require.NoError(t, acnt.SignDeployAccountTransaction(context.Background(), &tx, precomputedAddress)) + precomputedAddress := account.PrecomputeAccountAddress( + fakeUserPub, + classHash, + tx.ConstructorCalldata, + ) + require.NoError( + t, + acnt.SignDeployAccountTransaction(context.Background(), &tx, precomputedAddress), + ) _, err = devnetClient.Mint(precomputedAddress, new(big.Int).SetUint64(10000000000000000000)) require.NoError(t, err) @@ -712,12 +820,20 @@ func TestWaitForTransactionReceiptMOCK(t *testing.T) { tests.RunTestOn(t, tests.MockEnv) mockCtrl := gomock.NewController(t) - mockRpcProvider := mocks.NewMockRpcProvider(mockCtrl) + mockRPCProvider := mocks.NewMockRPCProvider(mockCtrl) - mockRpcProvider.EXPECT().ChainID(context.Background()).Return("SN_SEPOLIA", nil) + mockRPCProvider.EXPECT().ChainID(context.Background()).Return("SN_SEPOLIA", nil) // TODO: remove this once the braavos bug is fixed. Ref: https://github.com/NethermindEth/starknet.go/pull/691 - mockRpcProvider.EXPECT().ClassHashAt(context.Background(), gomock.Any(), gomock.Any()).Return(internalUtils.RANDOM_FELT, nil) - acnt, err := account.NewAccount(mockRpcProvider, &felt.Zero, "", account.NewMemKeystore(), account.CairoV0) + mockRPCProvider.EXPECT(). + ClassHashAt(context.Background(), gomock.Any(), gomock.Any()). + Return(internalUtils.DeadBeef, nil) + acnt, err := account.NewAccount( + mockRPCProvider, + &felt.Zero, + "", + account.NewMemKeystore(), + account.CairoV0, + ) require.NoError(t, err, "error returned from account.NewAccount()") type testSetType struct { @@ -763,7 +879,9 @@ func TestWaitForTransactionReceiptMOCK(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), test.Timeout*time.Second) defer cancel() if test.ShouldCallTransactionReceipt { - mockRpcProvider.EXPECT().TransactionReceipt(ctx, test.Hash).Return(test.ExpectedReceipt, test.ExpectedErr) + mockRPCProvider.EXPECT(). + TransactionReceipt(ctx, test.Hash). + Return(test.ExpectedReceipt, test.ExpectedErr) } resp, err := acnt.WaitForTransactionReceipt(ctx, test.Hash, 2*time.Second) @@ -805,7 +923,13 @@ func TestWaitForTransactionReceipt(t *testing.T) { client, err := rpc.NewProvider(tConfig.providerURL) require.NoError(t, err, "Error in rpc.NewProvider") - acnt, err := account.NewAccount(client, &felt.Zero, "pubkey", account.NewMemKeystore(), account.CairoV0) + acnt, err := account.NewAccount( + client, + &felt.Zero, + "pubkey", + account.NewMemKeystore(), + account.CairoV0, + ) require.NoError(t, err, "error returned from account.NewAccount()") type testSetType struct { @@ -827,7 +951,10 @@ func TestWaitForTransactionReceipt(t *testing.T) { for _, test := range testSet { go func() { - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(test.Timeout)*time.Second) + ctx, cancel := context.WithTimeout( + context.Background(), + time.Duration(test.Timeout)*time.Second, + ) defer cancel() resp, err := acnt.WaitForTransactionReceipt(ctx, test.Hash, 1*time.Second) @@ -857,59 +984,95 @@ func TestDeployContractWithUDC(t *testing.T) { require.NoError(t, err, "Error in setupAcc") t.Run("UDCCairoV0, no constructor, udcOptions nil", func(t *testing.T) { - classHash, _ := utils.HexToFelt("0x0387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8") + classHash, _ := utils.HexToFelt( + "0x0387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8", + ) resp, _, err := accnt.DeployContractWithUDC(context.Background(), classHash, nil, nil, nil) require.NoError(t, err, "DeployContractUDC failed") t.Logf("Transaction hash: %s", resp.Hash) - txReceipt, err := accnt.WaitForTransactionReceipt(context.Background(), resp.Hash, 500*time.Millisecond) + txReceipt, err := accnt.WaitForTransactionReceipt( + context.Background(), + resp.Hash, + 500*time.Millisecond, + ) require.NoError(t, err, "Waiting for tx receipt failed") assert.Equal(t, rpc.TxnExecutionStatusSUCCEEDED, txReceipt.ExecutionStatus) }) t.Run("error, UDCCairoV0, no constructor, all udcOptions set", func(t *testing.T) { - classHash, _ := utils.HexToFelt("0x0387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8") + classHash, _ := utils.HexToFelt( + "0x0387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8", + ) - _, _, err := accnt.DeployContractWithUDC(context.Background(), classHash, nil, nil, &utils.UDCOptions{ - Salt: internalUtils.RANDOM_FELT, - UDCVersion: utils.UDCCairoV0, - OriginIndependent: true, - }) + _, _, err := accnt.DeployContractWithUDC( + context.Background(), + classHash, + nil, + nil, + &utils.UDCOptions{ + Salt: internalUtils.DeadBeef, + UDCVersion: utils.UDCCairoV0, + OriginIndependent: true, + }, + ) assert.ErrorContains(t, err, "contract already deployed") }) t.Run("UDCCairoV2, no constructor, only UDCVersion set", func(t *testing.T) { - classHash, _ := utils.HexToFelt("0x0387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8") + classHash, _ := utils.HexToFelt( + "0x0387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8", + ) - resp, _, err := accnt.DeployContractWithUDC(context.Background(), classHash, nil, nil, &utils.UDCOptions{ - UDCVersion: utils.UDCCairoV2, - }) + resp, _, err := accnt.DeployContractWithUDC( + context.Background(), + classHash, + nil, + nil, + &utils.UDCOptions{ + UDCVersion: utils.UDCCairoV2, + }, + ) require.NoError(t, err, "DeployContractUDC failed") t.Logf("Transaction hash: %s", resp.Hash) - txReceipt, err := accnt.WaitForTransactionReceipt(context.Background(), resp.Hash, 500*time.Millisecond) + txReceipt, err := accnt.WaitForTransactionReceipt( + context.Background(), + resp.Hash, + 500*time.Millisecond, + ) require.NoError(t, err, "Waiting for tx receipt failed") assert.Equal(t, rpc.TxnExecutionStatusSUCCEEDED, txReceipt.ExecutionStatus) }) t.Run("error, UDCCairoV2, no constructor, all udcOptions set", func(t *testing.T) { - classHash, _ := utils.HexToFelt("0x0387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8") + classHash, _ := utils.HexToFelt( + "0x0387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8", + ) - _, _, err := accnt.DeployContractWithUDC(context.Background(), classHash, nil, nil, &utils.UDCOptions{ - Salt: internalUtils.RANDOM_FELT, - UDCVersion: utils.UDCCairoV2, - OriginIndependent: true, - }) + _, _, err := accnt.DeployContractWithUDC( + context.Background(), + classHash, + nil, + nil, + &utils.UDCOptions{ + Salt: internalUtils.DeadBeef, + UDCVersion: utils.UDCCairoV2, + OriginIndependent: true, + }, + ) assert.ErrorContains(t, err, "contract already deployed") }) // erc20 calldata: - classHash, _ := utils.HexToFelt("0x73d71c37e20c569186445d2c497d2195b4c0be9a255d72dbad86662fcc63ae6") + classHash, _ := utils.HexToFelt( + "0x73d71c37e20c569186445d2c497d2195b4c0be9a255d72dbad86662fcc63ae6", + ) name, _ := utils.StringToByteArrFelt("My Test Token") symbol, _ := utils.StringToByteArrFelt("MTT") supply, _ := utils.HexToU256Felt("0x200000000000000000") @@ -924,46 +1087,78 @@ func TestDeployContractWithUDC(t *testing.T) { constructorCalldata = append(constructorCalldata, recipient, owner) t.Run("UDCCairoV0, with constructor - ERC20, udcOptions nil", func(t *testing.T) { - resp, _, err := accnt.DeployContractWithUDC(context.Background(), classHash, constructorCalldata, nil, nil) + resp, _, err := accnt.DeployContractWithUDC( + context.Background(), + classHash, + constructorCalldata, + nil, + nil, + ) require.NoError(t, err, "DeployContractUDC failed") t.Logf("Transaction hash: %s", resp.Hash) - txReceipt, err := accnt.WaitForTransactionReceipt(context.Background(), resp.Hash, 500*time.Millisecond) + txReceipt, err := accnt.WaitForTransactionReceipt( + context.Background(), + resp.Hash, + 500*time.Millisecond, + ) require.NoError(t, err, "Waiting for tx receipt failed") assert.Equal(t, rpc.TxnExecutionStatusSUCCEEDED, txReceipt.ExecutionStatus) }) t.Run("error, UDCCairoV0, with constructor - ERC20, all udcOptions set", func(t *testing.T) { - _, _, err := accnt.DeployContractWithUDC(context.Background(), classHash, constructorCalldata, nil, &utils.UDCOptions{ - Salt: internalUtils.RANDOM_FELT, - UDCVersion: utils.UDCCairoV0, - OriginIndependent: true, - }) + _, _, err := accnt.DeployContractWithUDC( + context.Background(), + classHash, + constructorCalldata, + nil, + &utils.UDCOptions{ + Salt: internalUtils.DeadBeef, + UDCVersion: utils.UDCCairoV0, + OriginIndependent: true, + }, + ) assert.ErrorContains(t, err, "contract already deployed") }) t.Run("UDCCairoV2, with constructor - ERC20, udcOptions nil", func(t *testing.T) { - resp, _, err := accnt.DeployContractWithUDC(context.Background(), classHash, constructorCalldata, nil, &utils.UDCOptions{ - UDCVersion: utils.UDCCairoV2, - }) + resp, _, err := accnt.DeployContractWithUDC( + context.Background(), + classHash, + constructorCalldata, + nil, + &utils.UDCOptions{ + UDCVersion: utils.UDCCairoV2, + }, + ) require.NoError(t, err, "DeployContractUDC failed") t.Logf("Transaction hash: %s", resp.Hash) - txReceipt, err := accnt.WaitForTransactionReceipt(context.Background(), resp.Hash, 500*time.Millisecond) + txReceipt, err := accnt.WaitForTransactionReceipt( + context.Background(), + resp.Hash, + 500*time.Millisecond, + ) require.NoError(t, err, "Waiting for tx receipt failed") assert.Equal(t, rpc.TxnExecutionStatusSUCCEEDED, txReceipt.ExecutionStatus) }) t.Run("error, UDCCairoV2, with constructor - ERC20, all udcOptions set", func(t *testing.T) { - _, _, err := accnt.DeployContractWithUDC(context.Background(), classHash, constructorCalldata, nil, &utils.UDCOptions{ - Salt: internalUtils.RANDOM_FELT, - UDCVersion: utils.UDCCairoV2, - OriginIndependent: true, - }) + _, _, err := accnt.DeployContractWithUDC( + context.Background(), + classHash, + constructorCalldata, + nil, + &utils.UDCOptions{ + Salt: internalUtils.DeadBeef, + UDCVersion: utils.UDCCairoV2, + OriginIndependent: true, + }, + ) assert.ErrorContains(t, err, "contract already deployed") }) } diff --git a/account/txn_hash.go b/account/txn_hash.go index 5033a7f91..f766f56b6 100644 --- a/account/txn_hash.go +++ b/account/txn_hash.go @@ -8,37 +8,49 @@ import ( "github.com/NethermindEth/starknet.go/rpc" ) -// TransactionHashDeployAccount calculates the transaction hash for a deploy account transaction. +// TransactionHashDeployAccount calculates the transaction hash for a deploy +// account transaction. // // Parameters: -// - tx: The deploy account transaction to calculate the hash for. Can be of type DeployAccountTxn or DeployAccountTxnV3. +// - tx: The deploy account transaction to calculate the hash for. Can be of +// type DeployAccountTxn or DeployAccountTxnV3. // - contractAddress: The contract address as parameters as a *felt.Felt // // Returns: // - *felt.Felt: the calculated transaction hash // - error: an error if any -func (account *Account) TransactionHashDeployAccount(tx rpc.DeployAccountType, contractAddress *felt.Felt) (*felt.Felt, error) { +func (account *Account) TransactionHashDeployAccount( + tx rpc.DeployAccountType, + contractAddress *felt.Felt, +) (*felt.Felt, error) { + //nolint:lll // The link would be unclickable if we break the line. // https://docs.starknet.io/architecture-and-concepts/network-architecture/transactions/#deploy_account_transaction switch txn := tx.(type) { // deployAccTxn v1, pointer and struct case *rpc.DeployAccountTxnV1: - return hash.TransactionHashDeployAccountV1(txn, contractAddress, account.ChainId) + return hash.TransactionHashDeployAccountV1(txn, contractAddress, account.ChainID) case rpc.DeployAccountTxnV1: - return hash.TransactionHashDeployAccountV1(&txn, contractAddress, account.ChainId) + return hash.TransactionHashDeployAccountV1(&txn, contractAddress, account.ChainID) // deployAccTxn v3, pointer and struct case *rpc.DeployAccountTxnV3: - return hash.TransactionHashDeployAccountV3(txn, contractAddress, account.ChainId) + return hash.TransactionHashDeployAccountV3(txn, contractAddress, account.ChainID) case rpc.DeployAccountTxnV3: - return hash.TransactionHashDeployAccountV3(&txn, contractAddress, account.ChainId) + return hash.TransactionHashDeployAccountV3(&txn, contractAddress, account.ChainID) default: - return nil, fmt.Errorf("%w: got '%T' instead of a valid invoke txn type", ErrTxnTypeUnSupported, txn) + return nil, fmt.Errorf( + "%w: got '%T' instead of a valid invoke txn type", + ErrTxnTypeUnSupported, + txn, + ) } } -// TransactionHashInvoke calculates the transaction hash for the given invoke transaction. +// TransactionHashInvoke calculates the transaction hash for the given invoke +// transaction. // // Parameters: -// - tx: The invoke transaction to calculate the hash for. Can be of type InvokeTxnV0, InvokeTxnV1, or InvokeTxnV3. +// - tx: The invoke transaction to calculate the hash for. Can be of type +// InvokeTxnV0, InvokeTxnV1, or InvokeTxnV3. // // Returns: // - *felt.Felt: The calculated transaction hash as a *felt.Felt @@ -49,34 +61,41 @@ func (account *Account) TransactionHashInvoke(tx rpc.InvokeTxnType) (*felt.Felt, switch txn := tx.(type) { // invoke v0, pointer and struct case *rpc.InvokeTxnV0: - return hash.TransactionHashInvokeV0(txn, account.ChainId) + return hash.TransactionHashInvokeV0(txn, account.ChainID) case rpc.InvokeTxnV0: - return hash.TransactionHashInvokeV0(&txn, account.ChainId) + return hash.TransactionHashInvokeV0(&txn, account.ChainID) // invoke v1, pointer and struct case *rpc.InvokeTxnV1: - return hash.TransactionHashInvokeV1(txn, account.ChainId) + return hash.TransactionHashInvokeV1(txn, account.ChainID) case rpc.InvokeTxnV1: - return hash.TransactionHashInvokeV1(&txn, account.ChainId) + return hash.TransactionHashInvokeV1(&txn, account.ChainID) // invoke v3, pointer and struct case *rpc.InvokeTxnV3: - return hash.TransactionHashInvokeV3(txn, account.ChainId) + return hash.TransactionHashInvokeV3(txn, account.ChainID) case rpc.InvokeTxnV3: - return hash.TransactionHashInvokeV3(&txn, account.ChainId) + return hash.TransactionHashInvokeV3(&txn, account.ChainID) default: - return nil, fmt.Errorf("%w: got '%T' instead of a valid invoke txn type", ErrTxnTypeUnSupported, txn) + return nil, fmt.Errorf( + "%w: got '%T' instead of a valid invoke txn type", + ErrTxnTypeUnSupported, + txn, + ) } } -// TransactionHashDeclare calculates the transaction hash for declaring a transaction type. +// TransactionHashDeclare calculates the transaction hash for declaring a +// transaction type. // // Parameters: -// - tx: The `tx` parameter of type `rpc.DeclareTxnType`. Can be one of the types DeclareTxnV1/V2/V3, and BroadcastDeclareTxnV3 +// - tx: The `tx` parameter of type `rpc.DeclareTxnType`. Can be one of the +// types DeclareTxnV1/V2/V3, and BroadcastDeclareTxnV3 // // Returns: // - *felt.Felt: the calculated transaction hash as `*felt.Felt` value // - error: an error, if any // -// If the `tx` parameter is not one of the supported types, the function returns an error `ErrTxnTypeUnSupported`. +// If the `tx` parameter is not one of the supported types, the function returns +// an error `ErrTxnTypeUnSupported`. func (account *Account) TransactionHashDeclare(tx rpc.DeclareTxnType) (*felt.Felt, error) { switch txn := tx.(type) { // Due to inconsistencies in version 0 hash calculation we don't calculate the hash @@ -84,25 +103,29 @@ func (account *Account) TransactionHashDeclare(tx rpc.DeclareTxnType) (*felt.Fel return nil, ErrTxnVersionUnSupported // declare v1, pointer and struct case *rpc.DeclareTxnV1: - return hash.TransactionHashDeclareV1(txn, account.ChainId) + return hash.TransactionHashDeclareV1(txn, account.ChainID) case rpc.DeclareTxnV1: - return hash.TransactionHashDeclareV1(&txn, account.ChainId) + return hash.TransactionHashDeclareV1(&txn, account.ChainID) // declare v2, pointer and struct case *rpc.DeclareTxnV2: - return hash.TransactionHashDeclareV2(txn, account.ChainId) + return hash.TransactionHashDeclareV2(txn, account.ChainID) case rpc.DeclareTxnV2: - return hash.TransactionHashDeclareV2(&txn, account.ChainId) + return hash.TransactionHashDeclareV2(&txn, account.ChainID) // declare v3, pointer and struct case *rpc.DeclareTxnV3: - return hash.TransactionHashDeclareV3(txn, account.ChainId) + return hash.TransactionHashDeclareV3(txn, account.ChainID) case rpc.DeclareTxnV3: - return hash.TransactionHashDeclareV3(&txn, account.ChainId) + return hash.TransactionHashDeclareV3(&txn, account.ChainID) // broadcast declare v3, pointer and struct case *rpc.BroadcastDeclareTxnV3: - return hash.TransactionHashBroadcastDeclareV3(txn, account.ChainId) + return hash.TransactionHashBroadcastDeclareV3(txn, account.ChainID) case rpc.BroadcastDeclareTxnV3: - return hash.TransactionHashBroadcastDeclareV3(&txn, account.ChainId) + return hash.TransactionHashBroadcastDeclareV3(&txn, account.ChainID) default: - return nil, fmt.Errorf("%w: got '%T' instead of a valid declare txn type", ErrTxnTypeUnSupported, txn) + return nil, fmt.Errorf( + "%w: got '%T' instead of a valid declare txn type", + ErrTxnTypeUnSupported, + txn, + ) } } diff --git a/account/txn_hash_test.go b/account/txn_hash_test.go index 4999e49ba..5f119a1f1 100644 --- a/account/txn_hash_test.go +++ b/account/txn_hash_test.go @@ -35,7 +35,7 @@ func TestTransactionHashInvoke(t *testing.T) { tests.RunTestOn(t, tests.MockEnv, tests.TestnetEnv) mockCtrl := gomock.NewController(t) - mockRpcProvider := mocks.NewMockRpcProvider(mockCtrl) + mockRPCProvider := mocks.NewMockRPCProvider(mockCtrl) type testSetType struct { ExpectedHash *felt.Felt @@ -127,16 +127,28 @@ func TestTransactionHashInvoke(t *testing.T) { var client *rpc.Provider client, err = rpc.NewProvider(tConfig.providerURL) require.NoError(t, err, "Error in rpc.NewClient") - acc, err = account.NewAccount(client, test.AccountAddress, test.PubKey, ks, account.CairoV0) + acc, err = account.NewAccount( + client, + test.AccountAddress, + test.PubKey, + ks, + account.CairoV0, + ) require.NoError(t, err, "error returned from account.NewAccount()") } if tests.TEST_ENV == "mock" { - mockRpcProvider.EXPECT().ChainID(context.Background()).Return(test.ChainID, nil) + mockRPCProvider.EXPECT().ChainID(context.Background()).Return(test.ChainID, nil) // TODO: remove this once the braavos bug is fixed. Ref: https://github.com/NethermindEth/starknet.go/pull/691 - mockRpcProvider.EXPECT(). + mockRPCProvider.EXPECT(). ClassHashAt(context.Background(), gomock.Any(), gomock.Any()). - Return(internalUtils.RANDOM_FELT, nil) - acc, err = account.NewAccount(mockRpcProvider, test.AccountAddress, test.PubKey, ks, account.CairoV0) + Return(internalUtils.DeadBeef, nil) + acc, err = account.NewAccount( + mockRPCProvider, + test.AccountAddress, + test.PubKey, + ks, + account.CairoV0, + ) require.NoError(t, err, "error returned from account.NewAccount()") } invokeTxn := rpc.InvokeTxnV1{ @@ -148,9 +160,14 @@ func TestTransactionHashInvoke(t *testing.T) { } hashResp, err := acc.TransactionHashInvoke(invokeTxn) require.NoError(t, err, "error returned from account.TransactionHash()") - require.Equal(t, test.ExpectedHash.String(), hashResp.String(), "transaction hash does not match expected") + require.Equal( + t, + test.ExpectedHash.String(), + hashResp.String(), + "transaction hash does not match expected", + ) - hash2, err := hash.TransactionHashInvokeV1(&invokeTxn, acc.ChainId) + hash2, err := hash.TransactionHashInvokeV1(&invokeTxn, acc.ChainID) require.NoError(t, err) assert.Equal(t, hashResp, hash2) }) @@ -185,17 +202,31 @@ func TestTransactionHashDeclare(t *testing.T) { if tests.TEST_ENV == "mock" { mockCtrl := gomock.NewController(t) - mockRpcProvider := mocks.NewMockRpcProvider(mockCtrl) - mockRpcProvider.EXPECT().ChainID(context.Background()).Return("SN_SEPOLIA", nil) + mockRPCProvider := mocks.NewMockRPCProvider(mockCtrl) + mockRPCProvider.EXPECT().ChainID(context.Background()).Return("SN_SEPOLIA", nil) // TODO: remove this once the braavos bug is fixed. Ref: https://github.com/NethermindEth/starknet.go/pull/691 - mockRpcProvider.EXPECT().ClassHashAt(context.Background(), gomock.Any(), gomock.Any()).Return(internalUtils.RANDOM_FELT, nil) - acnt, err = account.NewAccount(mockRpcProvider, &felt.Zero, "", account.NewMemKeystore(), account.CairoV0) + mockRPCProvider.EXPECT(). + ClassHashAt(context.Background(), gomock.Any(), gomock.Any()). + Return(internalUtils.DeadBeef, nil) + acnt, err = account.NewAccount( + mockRPCProvider, + &felt.Zero, + "", + account.NewMemKeystore(), + account.CairoV0, + ) require.NoError(t, err) } if tests.TEST_ENV == "testnet" { client, err := rpc.NewProvider(tConfig.providerURL) require.NoError(t, err, "Error in rpc.NewClient") - acnt, err = account.NewAccount(client, &felt.Zero, "", account.NewMemKeystore(), account.CairoV0) + acnt, err = account.NewAccount( + client, + &felt.Zero, + "", + account.NewMemKeystore(), + account.CairoV0, + ) require.NoError(t, err) } @@ -210,7 +241,7 @@ func TestTransactionHashDeclare(t *testing.T) { // https://sepolia.voyager.online/tx/0x28e430cc73715bd1052e8db4f17b053c53dd8174341cba4b1a337b9fecfa8c3 Txn: rpc.DeclareTxnV2{ Nonce: internalUtils.TestHexToFelt(t, "0x1"), - Type: rpc.TransactionType_Declare, + Type: rpc.TransactionTypeDeclare, Version: rpc.TransactionV2, Signature: []*felt.Felt{ internalUtils.TestHexToFelt(t, "0x713765e220325edfaf5e033ad77b1ba4eceabe66333893b89845c2ddc744d34"), @@ -228,7 +259,7 @@ func TestTransactionHashDeclare(t *testing.T) { // https://sepolia.voyager.online/tx/0x30c852c522274765e1d681bc8a84ce7c41118370ef2ba7d18a427ed29f5b155 Txn: rpc.DeclareTxnV3{ Nonce: internalUtils.TestHexToFelt(t, "0x2b"), - Type: rpc.TransactionType_Declare, + Type: rpc.TransactionTypeDeclare, Version: rpc.TransactionV3, Signature: []*felt.Felt{ internalUtils.TestHexToFelt(t, "0x5c6a94302ef4b6d80a4c6a3eaf5ad30e11fa13aa78f7397a4f69901ceb12b7"), @@ -266,7 +297,7 @@ func TestTransactionHashDeclare(t *testing.T) { // https://sepolia.voyager.online/tx/0x28e430cc73715bd1052e8db4f17b053c53dd8174341cba4b1a337b9fecfa8c3 Txn: rpc.DeclareTxnV2{ Nonce: internalUtils.TestHexToFelt(t, "0x1"), - Type: rpc.TransactionType_Declare, + Type: rpc.TransactionTypeDeclare, Version: rpc.TransactionV2, Signature: []*felt.Felt{ internalUtils.TestHexToFelt(t, "0x713765e220325edfaf5e033ad77b1ba4eceabe66333893b89845c2ddc744d34"), @@ -285,14 +316,19 @@ func TestTransactionHashDeclare(t *testing.T) { for _, test := range testSet { hashResp, err := acnt.TransactionHashDeclare(test.Txn) require.Equal(t, test.ExpectedErr, err) - require.Equal(t, test.ExpectedHash.String(), hashResp.String(), "TransactionHashDeclare not what expected") + require.Equal( + t, + test.ExpectedHash.String(), + hashResp.String(), + "TransactionHashDeclare not what expected", + ) var hash2 *felt.Felt switch txn := test.Txn.(type) { case rpc.DeclareTxnV2: - hash2, err = hash.TransactionHashDeclareV2(&txn, acnt.ChainId) + hash2, err = hash.TransactionHashDeclareV2(&txn, acnt.ChainID) case rpc.DeclareTxnV3: - hash2, err = hash.TransactionHashDeclareV3(&txn, acnt.ChainId) + hash2, err = hash.TransactionHashDeclareV3(&txn, acnt.ChainID) } require.NoError(t, err) assert.Equal(t, hashResp, hash2) @@ -304,11 +340,19 @@ func TestTransactionHashInvokeV3(t *testing.T) { mockCtrl := gomock.NewController(t) - mockRpcProvider := mocks.NewMockRpcProvider(mockCtrl) - mockRpcProvider.EXPECT().ChainID(context.Background()).Return("SN_SEPOLIA", nil) + mockRPCProvider := mocks.NewMockRPCProvider(mockCtrl) + mockRPCProvider.EXPECT().ChainID(context.Background()).Return("SN_SEPOLIA", nil) // TODO: remove this once the braavos bug is fixed. Ref: https://github.com/NethermindEth/starknet.go/pull/691 - mockRpcProvider.EXPECT().ClassHashAt(context.Background(), gomock.Any(), gomock.Any()).Return(internalUtils.RANDOM_FELT, nil) - acnt, err := account.NewAccount(mockRpcProvider, &felt.Zero, "", account.NewMemKeystore(), account.CairoV0) + mockRPCProvider.EXPECT(). + ClassHashAt(context.Background(), gomock.Any(), gomock.Any()). + Return(internalUtils.DeadBeef, nil) + acnt, err := account.NewAccount( + mockRPCProvider, + &felt.Zero, + "", + account.NewMemKeystore(), + account.CairoV0, + ) require.NoError(t, err) type testSetType struct { @@ -321,11 +365,17 @@ func TestTransactionHashInvokeV3(t *testing.T) { // https://sepolia.voyager.online/tx/0x76b52e17bc09064bd986ead34263e6305ef3cecfb3ae9e19b86bf4f1a1a20ea Txn: rpc.InvokeTxnV3{ Nonce: internalUtils.TestHexToFelt(t, "0x9803"), - Type: rpc.TransactionType_Invoke, + Type: rpc.TransactionTypeInvoke, Version: rpc.TransactionV3, Signature: []*felt.Felt{ - internalUtils.TestHexToFelt(t, "0x17bacc700df6c82682139e8e550078a5daa75dfe356577f78f7e57fd7c56245"), - internalUtils.TestHexToFelt(t, "0x4eb8734727eb9412b79ba6d14ff1c9a6beb0dc0b811e3f97168c747f8d427b3"), + internalUtils.TestHexToFelt( + t, + "0x17bacc700df6c82682139e8e550078a5daa75dfe356577f78f7e57fd7c56245", + ), + internalUtils.TestHexToFelt( + t, + "0x4eb8734727eb9412b79ba6d14ff1c9a6beb0dc0b811e3f97168c747f8d427b3", + ), }, ResourceBounds: &rpc.ResourceBoundsMapping{ L1Gas: rpc.ResourceBounds{ @@ -344,7 +394,10 @@ func TestTransactionHashInvokeV3(t *testing.T) { Tip: "0x0", PayMasterData: []*felt.Felt{}, AccountDeploymentData: []*felt.Felt{}, - SenderAddress: internalUtils.TestHexToFelt(t, "0x745d525a3582e91299d8d7c71730ffc4b1f191f5b219d800334bc0edad0983b"), + SenderAddress: internalUtils.TestHexToFelt( + t, + "0x745d525a3582e91299d8d7c71730ffc4b1f191f5b219d800334bc0edad0983b", + ), Calldata: internalUtils.TestHexArrToFelt(t, []string{ "0x1", "0x4138fd51f90d171df37e9d4419c8cdb67d525840c58f8a5c347be93a1c5277d", @@ -354,17 +407,25 @@ func TestTransactionHashInvokeV3(t *testing.T) { NonceDataMode: rpc.DAModeL1, FeeMode: rpc.DAModeL1, }, - ExpectedHash: internalUtils.TestHexToFelt(t, "0x76b52e17bc09064bd986ead34263e6305ef3cecfb3ae9e19b86bf4f1a1a20ea"), - ExpectedErr: nil, + ExpectedHash: internalUtils.TestHexToFelt( + t, + "0x76b52e17bc09064bd986ead34263e6305ef3cecfb3ae9e19b86bf4f1a1a20ea", + ), + ExpectedErr: nil, }, } for _, test := range testSet { hashResp, err := acnt.TransactionHashInvoke(test.Txn) require.Equal(t, test.ExpectedErr, err) - require.Equal(t, test.ExpectedHash.String(), hashResp.String(), "TransactionHashInvoke not what expected") + require.Equal( + t, + test.ExpectedHash.String(), + hashResp.String(), + "TransactionHashInvoke not what expected", + ) - hash2, err := hash.TransactionHashInvokeV3(&test.Txn, acnt.ChainId) + hash2, err := hash.TransactionHashInvokeV3(&test.Txn, acnt.ChainID) require.NoError(t, err) assert.Equal(t, hashResp, hash2) } @@ -375,12 +436,20 @@ func TestTransactionHashdeployAccount(t *testing.T) { mockCtrl := gomock.NewController(t) - mockRpcProvider := mocks.NewMockRpcProvider(mockCtrl) - mockRpcProvider.EXPECT().ChainID(context.Background()).Return("SN_SEPOLIA", nil) + mockRPCProvider := mocks.NewMockRPCProvider(mockCtrl) + mockRPCProvider.EXPECT().ChainID(context.Background()).Return("SN_SEPOLIA", nil) // TODO: remove this once the braavos bug is fixed. Ref: https://github.com/NethermindEth/starknet.go/pull/691 - mockRpcProvider.EXPECT().ClassHashAt(context.Background(), gomock.Any(), gomock.Any()).Return(internalUtils.RANDOM_FELT, nil) + mockRPCProvider.EXPECT(). + ClassHashAt(context.Background(), gomock.Any(), gomock.Any()). + Return(internalUtils.DeadBeef, nil) - acnt, err := account.NewAccount(mockRpcProvider, &felt.Zero, "", account.NewMemKeystore(), account.CairoV0) + acnt, err := account.NewAccount( + mockRPCProvider, + &felt.Zero, + "", + account.NewMemKeystore(), + account.CairoV0, + ) require.NoError(t, err) type testSetType struct { @@ -394,32 +463,59 @@ func TestTransactionHashdeployAccount(t *testing.T) { // https://sepolia.voyager.online/tx/0x66d1d9d50d308a9eb16efedbad208b0672769a545a0b828d357757f444e9188 Txn: rpc.DeployAccountTxnV1{ Nonce: internalUtils.TestHexToFelt(t, "0x0"), - Type: rpc.TransactionType_DeployAccount, + Type: rpc.TransactionTypeDeployAccount, MaxFee: internalUtils.TestHexToFelt(t, "0x1d2109b99cf94"), Version: rpc.TransactionV1, Signature: []*felt.Felt{ - internalUtils.TestHexToFelt(t, "0x427df9a1a4a0b7b9011a758524b8a6c2595aac9140608fe24c66efe04b340d7"), - internalUtils.TestHexToFelt(t, "0x4edc73cd97dab7458a08fec6d7c0e1638c3f1111646fc8a91508b4f94b36310"), + internalUtils.TestHexToFelt( + t, + "0x427df9a1a4a0b7b9011a758524b8a6c2595aac9140608fe24c66efe04b340d7", + ), + internalUtils.TestHexToFelt( + t, + "0x4edc73cd97dab7458a08fec6d7c0e1638c3f1111646fc8a91508b4f94b36310", + ), }, - ClassHash: internalUtils.TestHexToFelt(t, "0x1e60c8722677cfb7dd8dbea5be86c09265db02cdfe77113e77da7d44c017388"), - ContractAddressSalt: internalUtils.TestHexToFelt(t, "0x15d621f9515c6197d3117eb1a25c7a4a669317be8f49831e03fcc00d855352e"), + ClassHash: internalUtils.TestHexToFelt( + t, + "0x1e60c8722677cfb7dd8dbea5be86c09265db02cdfe77113e77da7d44c017388", + ), + ContractAddressSalt: internalUtils.TestHexToFelt( + t, + "0x15d621f9515c6197d3117eb1a25c7a4a669317be8f49831e03fcc00d855352e", + ), ConstructorCalldata: []*felt.Felt{ - internalUtils.TestHexToFelt(t, "0x960532cfba33384bbec41aa669727a9c51e995c87e101c86706aaf244f7e4e"), + internalUtils.TestHexToFelt( + t, + "0x960532cfba33384bbec41aa669727a9c51e995c87e101c86706aaf244f7e4e", + ), }, }, - SenderAddress: internalUtils.TestHexToFelt(t, "0x05dd5faeddd4a9e01231f3bb9b95ec93426d08977b721c222e45fd98c5f353ff"), - ExpectedHash: internalUtils.TestHexToFelt(t, "0x66d1d9d50d308a9eb16efedbad208b0672769a545a0b828d357757f444e9188"), - ExpectedErr: nil, + SenderAddress: internalUtils.TestHexToFelt( + t, + "0x05dd5faeddd4a9e01231f3bb9b95ec93426d08977b721c222e45fd98c5f353ff", + ), + ExpectedHash: internalUtils.TestHexToFelt( + t, + "0x66d1d9d50d308a9eb16efedbad208b0672769a545a0b828d357757f444e9188", + ), + ExpectedErr: nil, }, { // https://sepolia.voyager.online/tx/0x32413f8cee053089d6d7026a72e4108262ca3cfe868dd9159bc1dd160aec975 Txn: rpc.DeployAccountTxnV3{ Nonce: internalUtils.TestHexToFelt(t, "0x0"), - Type: rpc.TransactionType_DeployAccount, + Type: rpc.TransactionTypeDeployAccount, Version: rpc.TransactionV3, Signature: []*felt.Felt{ - internalUtils.TestHexToFelt(t, "0x3ef7f047c95592a04d4d754888dd8f125480a48dee23ee86c115d5da2a86573"), - internalUtils.TestHexToFelt(t, "0x65e8661ab1526b4f8ea50b76fea1a0e82543de1eb3885e415790d7e1b5a93c7"), + internalUtils.TestHexToFelt( + t, + "0x3ef7f047c95592a04d4d754888dd8f125480a48dee23ee86c115d5da2a86573", + ), + internalUtils.TestHexToFelt( + t, + "0x65e8661ab1526b4f8ea50b76fea1a0e82543de1eb3885e415790d7e1b5a93c7", + ), }, ResourceBounds: &rpc.ResourceBoundsMapping{ L1Gas: rpc.ResourceBounds{ @@ -439,29 +535,46 @@ func TestTransactionHashdeployAccount(t *testing.T) { PayMasterData: []*felt.Felt{}, NonceDataMode: rpc.DAModeL1, FeeMode: rpc.DAModeL1, - ClassHash: internalUtils.TestHexToFelt(t, "0x61dac032f228abef9c6626f995015233097ae253a7f72d68552db02f2971b8f"), + ClassHash: internalUtils.TestHexToFelt( + t, + "0x61dac032f228abef9c6626f995015233097ae253a7f72d68552db02f2971b8f", + ), ConstructorCalldata: internalUtils.TestHexArrToFelt(t, []string{ "0x2e94ba2293dfa45f86dfcf9952d7a33dc50ce2b00b932999fbe0844772604f3", }), - ContractAddressSalt: internalUtils.TestHexToFelt(t, "0x2e94ba2293dfa45f86dfcf9952d7a33dc50ce2b00b932999fbe0844772604f3"), + ContractAddressSalt: internalUtils.TestHexToFelt( + t, + "0x2e94ba2293dfa45f86dfcf9952d7a33dc50ce2b00b932999fbe0844772604f3", + ), }, - SenderAddress: internalUtils.TestHexToFelt(t, "0x48419d3cc27f158917b45255d5376c06a9524484e19a1102279cbdc715c5522"), - ExpectedHash: internalUtils.TestHexToFelt(t, "0x32413f8cee053089d6d7026a72e4108262ca3cfe868dd9159bc1dd160aec975"), - ExpectedErr: nil, + SenderAddress: internalUtils.TestHexToFelt( + t, + "0x48419d3cc27f158917b45255d5376c06a9524484e19a1102279cbdc715c5522", + ), + ExpectedHash: internalUtils.TestHexToFelt( + t, + "0x32413f8cee053089d6d7026a72e4108262ca3cfe868dd9159bc1dd160aec975", + ), + ExpectedErr: nil, }, } for _, test := range testSet { hashResp, err := acnt.TransactionHashDeployAccount(test.Txn, test.SenderAddress) require.Equal(t, test.ExpectedErr, err) - assert.Equal(t, test.ExpectedHash.String(), hashResp.String(), "TransactionHashDeployAccount not what expected") + assert.Equal( + t, + test.ExpectedHash.String(), + hashResp.String(), + "TransactionHashDeployAccount not what expected", + ) var hash2 *felt.Felt switch txn := test.Txn.(type) { case rpc.DeployAccountTxnV1: - hash2, err = hash.TransactionHashDeployAccountV1(&txn, test.SenderAddress, acnt.ChainId) + hash2, err = hash.TransactionHashDeployAccountV1(&txn, test.SenderAddress, acnt.ChainID) case rpc.DeployAccountTxnV3: - hash2, err = hash.TransactionHashDeployAccountV3(&txn, test.SenderAddress, acnt.ChainId) + hash2, err = hash.TransactionHashDeployAccountV3(&txn, test.SenderAddress, acnt.ChainID) } require.NoError(t, err) assert.Equal(t, hashResp, hash2) diff --git a/account/txn_options.go b/account/txn_options.go index 0916956a2..758ddc30e 100644 --- a/account/txn_options.go +++ b/account/txn_options.go @@ -47,7 +47,7 @@ func (opts *TxnOptions) BlockID() rpc.BlockID { return rpc.WithBlockTag(rpc.BlockTagLatest) } - return rpc.WithBlockTag(rpc.BlockTagPre_confirmed) + return rpc.WithBlockTag(rpc.BlockTagPreConfirmed) } // Returns a `[]rpc.SimulationFlag` containing the SimulationFlag. @@ -60,7 +60,8 @@ func (opts *TxnOptions) SimulationFlags() []rpc.SimulationFlag { return []rpc.SimulationFlag{opts.SimulationFlag} } -// takes a pointer to a TxnOptions struct and formats the tip and multiplier according to the default values +// takes a pointer to a TxnOptions struct and formats the tip and multiplier according +// to the default values func fmtTipAndMultiplier(opts *TxnOptions) { if opts.Multiplier <= 0 { opts.Multiplier = 1.5 diff --git a/account/txn_options_test.go b/account/txn_options_test.go index f8633b926..082a45c48 100644 --- a/account/txn_options_test.go +++ b/account/txn_options_test.go @@ -78,7 +78,7 @@ func TestTxnOptions(t *testing.T) { { name: "Default value (nil)", opts: nil, - expectedBlockID: rpc.WithBlockTag(rpc.BlockTagPre_confirmed), + expectedBlockID: rpc.WithBlockTag(rpc.BlockTagPreConfirmed), }, { name: "latest set to true", @@ -92,7 +92,7 @@ func TestTxnOptions(t *testing.T) { opts: &TxnOptions{ UseLatest: false, }, - expectedBlockID: rpc.WithBlockTag(rpc.BlockTagPre_confirmed), + expectedBlockID: rpc.WithBlockTag(rpc.BlockTagPreConfirmed), }, } @@ -127,16 +127,16 @@ func TestTxnOptions(t *testing.T) { { name: "SKIP_VALIDATE flag", opts: &TxnOptions{ - SimulationFlag: rpc.SKIP_VALIDATE, + SimulationFlag: rpc.SkipValidate, }, - expectedSimFlags: []rpc.SimulationFlag{rpc.SKIP_VALIDATE}, + expectedSimFlags: []rpc.SimulationFlag{rpc.SkipValidate}, }, { name: "SKIP_FEE_CHARGE flag", opts: &TxnOptions{ - SimulationFlag: rpc.SKIP_FEE_CHARGE, + SimulationFlag: rpc.SkipFeeCharge, }, - expectedSimFlags: []rpc.SimulationFlag{rpc.SKIP_FEE_CHARGE}, + expectedSimFlags: []rpc.SimulationFlag{rpc.SkipFeeCharge}, }, } diff --git a/contracts/contracts.go b/contracts/contracts.go index b41802582..251a65596 100644 --- a/contracts/contracts.go +++ b/contracts/contracts.go @@ -8,12 +8,13 @@ import ( "github.com/NethermindEth/starknet.go/curve" ) -var PREFIX_CONTRACT_ADDRESS = new(felt.Felt).SetBytes([]byte("STARKNET_CONTRACT_ADDRESS")) +var prefixContractAddress = new(felt.Felt).SetBytes([]byte("STARKNET_CONTRACT_ADDRESS")) // UnmarshalCasmClass is a function that unmarshals a CasmClass object from a file. // CASM = Cairo instructions // -// It takes a file path as a parameter and returns a pointer to the unmarshaled CasmClass object and an error. +// It takes a file path as a parameter and returns a pointer to the +// unmarshaled CasmClass object and an error. func UnmarshalCasmClass(filePath string) (*CasmClass, error) { content, err := os.ReadFile(filePath) if err != nil { @@ -40,9 +41,14 @@ func UnmarshalCasmClass(filePath string) (*CasmClass, error) { // // Returns: // - *felt.Felt: the precomputed address as a *felt.Felt -func PrecomputeAddress(deployerAddress, salt, classHash *felt.Felt, constructorCalldata []*felt.Felt) *felt.Felt { +// +//nolint:lll // The link would be unclickable if we break the line. +func PrecomputeAddress( + deployerAddress, salt, classHash *felt.Felt, + constructorCalldata []*felt.Felt, +) *felt.Felt { return curve.PedersenArray( - PREFIX_CONTRACT_ADDRESS, + prefixContractAddress, deployerAddress, salt, classHash, diff --git a/contracts/contracts_test.go b/contracts/contracts_test.go index d8cebed9c..db66d4ef6 100644 --- a/contracts/contracts_test.go +++ b/contracts/contracts_test.go @@ -89,12 +89,18 @@ func TestUnmarshalCasmClass(t *testing.T) { EntryPointByType: CasmEntryPointsByType{ External: []CasmEntryPoint{ { - Selector: internalUtils.TestHexToFelt(t, "0x362398bec32bc0ebb411203221a35a0301193a96f317ebe5e40be9f60d15320"), + Selector: internalUtils.TestHexToFelt( + t, + "0x362398bec32bc0ebb411203221a35a0301193a96f317ebe5e40be9f60d15320", + ), Offset: 0, Builtins: []string{"range_check"}, }, { - Selector: internalUtils.TestHexToFelt(t, "0x39e11d48192e4333233c7eb19d10ad67c362bb28580c604d67884c85da39695"), + Selector: internalUtils.TestHexToFelt( + t, + "0x39e11d48192e4333233c7eb19d10ad67c362bb28580c604d67884c85da39695", + ), Offset: 130, Builtins: []string{"range_check"}, }, @@ -113,12 +119,18 @@ func TestUnmarshalCasmClass(t *testing.T) { EntryPointByType: CasmEntryPointsByType{ External: []CasmEntryPoint{ { - Selector: internalUtils.TestHexToFelt(t, "0x26813d396fdb198e9ead934e4f7a592a8b88a059e45ab0eb6ee53494e8d45b0"), + Selector: internalUtils.TestHexToFelt( + t, + "0x26813d396fdb198e9ead934e4f7a592a8b88a059e45ab0eb6ee53494e8d45b0", + ), Offset: 0, Builtins: []string{"range_check"}, }, { - Selector: internalUtils.TestHexToFelt(t, "0x3d7905601c217734671143d457f0db37f7f8883112abd34b92c4abfeafde0c3"), + Selector: internalUtils.TestHexToFelt( + t, + "0x3d7905601c217734671143d457f0db37f7f8883112abd34b92c4abfeafde0c3", + ), Offset: 162, Builtins: []string{"range_check"}, }, @@ -140,13 +152,24 @@ func TestUnmarshalCasmClass(t *testing.T) { assert.Equal(t, casmClass.Prime, testCase.ExpectedCasmClass.Prime) assert.Equal(t, casmClass.CompilerVersion, testCase.ExpectedCasmClass.Version) - assert.EqualValues(t, casmClass.EntryPointsByType, testCase.ExpectedCasmClass.EntryPointByType) - assert.Equal(t, testCase.ExpectedCasmClass.BytecodeSegmentLengths, casmClass.BytecodeSegmentLengths) + assert.EqualValues( + t, + casmClass.EntryPointsByType, + testCase.ExpectedCasmClass.EntryPointByType, + ) + assert.Equal( + t, + testCase.ExpectedCasmClass.BytecodeSegmentLengths, + casmClass.BytecodeSegmentLengths, + ) // compare JSONs rawExpectedCasmClass, err := os.ReadFile(testCase.CasmPath) require.NoError(t, err) - require.NoError(t, internalUtils.RemoveFieldFromJSON(&rawExpectedCasmClass, "pythonic_hints")) + require.NoError( + t, + internalUtils.RemoveFieldFromJSON(&rawExpectedCasmClass, "pythonic_hints"), + ) rawActualCasmClass, err := json.Marshal(casmClass) require.NoError(t, err) @@ -182,7 +205,10 @@ func TestPrecomputeAddress(t *testing.T) { Salt: "0x0702e82f1ec15656ad4502268dad530197141f3b59f5529835af9318ef399da5", ClassHash: "0x064728e0c0713811c751930f8d3292d683c23f107c89b0a101425d9e80adb1c0", ConstructorCalldata: []*felt.Felt{ - internalUtils.TestHexToFelt(t, "0x022f3e55b61d86c2ac5239fa3b3b8761f26b9a5c0b5f61ddbd5d756ced498b46"), + internalUtils.TestHexToFelt( + t, + "0x022f3e55b61d86c2ac5239fa3b3b8761f26b9a5c0b5f61ddbd5d756ced498b46", + ), }, ExpectedPrecomputedAddress: "0x31463b5263a6631be4d1fe92d64d13e3a8498c440bf789e69ccb951eb8ad5da", }, @@ -191,7 +217,10 @@ func TestPrecomputeAddress(t *testing.T) { Salt: "0x023a851e8aeba201772098e1a1db3448f6238b20f928527242eb383905d91a87", ClassHash: "0x061dac032f228abef9c6626f995015233097ae253a7f72d68552db02f2971b8f", ConstructorCalldata: []*felt.Felt{ - internalUtils.TestHexToFelt(t, "0x023a851e8aeba201772098e1a1db3448f6238b20f928527242eb383905d91a87"), + internalUtils.TestHexToFelt( + t, + "0x023a851e8aeba201772098e1a1db3448f6238b20f928527242eb383905d91a87", + ), }, ExpectedPrecomputedAddress: "0x28771beb7a2522a07d2ae6fc1fa5af942e8e863f70e6d7d74f9600ea3d5c242", }, @@ -200,7 +229,10 @@ func TestPrecomputeAddress(t *testing.T) { Salt: "0x0702e82f1ec15656ad4502268dad530197141f3b59f5529835af9318ef399da5", ClassHash: "0xf6f44afb3cacbcc01a371aff62c86ca9a45feba065424c99f7cd8637514d8f", ConstructorCalldata: []*felt.Felt{ - internalUtils.TestHexToFelt(t, "0x022f3e55b61d86c2ac5239fa3b3b8761f26b9a5c0b5f61ddbd5d756ced498b46"), + internalUtils.TestHexToFelt( + t, + "0x022f3e55b61d86c2ac5239fa3b3b8761f26b9a5c0b5f61ddbd5d756ced498b46", + ), }, ExpectedPrecomputedAddress: "0x50cb9257feb7e960c8ab7d1cf48f33cfbe21de138409be476f63203383ece63", }, @@ -248,7 +280,9 @@ func newNestedFieldArray(val ...NestedUints) *NestedUints { // // none func TestDeprecatedContractClass_UnmarshalValidJSON_Successful(t *testing.T) { - content, err := os.ReadFile("./testData/0x01b661756bf7d16210fc611626e1af4569baa1781ffc964bd018f4585ae241c1.json") + content, err := os.ReadFile( + "./testData/0x01b661756bf7d16210fc611626e1af4569baa1781ffc964bd018f4585ae241c1.json", + ) if err != nil { t.Fatal("should be able to read file", err) } @@ -272,7 +306,9 @@ func TestDeprecatedContractClass_UnmarshalValidJSON_Successful(t *testing.T) { // // none func TestContractClass_UnmarshalValidJSON_Successful(t *testing.T) { - content, err := os.ReadFile("./testData/0x03e9b96873987da76121f74a3df71e38c44527d8ce2ad115bcfda3cba0548cc3.json") + content, err := os.ReadFile( + "./testData/0x03e9b96873987da76121f74a3df71e38c44527d8ce2ad115bcfda3cba0548cc3.json", + ) if err != nil { t.Fatal("should be able to read file", err) } diff --git a/contracts/types_casm_class.go b/contracts/types_casm_class.go index 8e5a30cab..ce67bc74f 100644 --- a/contracts/types_casm_class.go +++ b/contracts/types_casm_class.go @@ -8,14 +8,16 @@ import ( "github.com/NethermindEth/juno/core/felt" ) -// CasmClass (AKA CASM_COMPILED_CONTRACT_CLASS) is the struct that represents the compiled Cairo contract class. +// CasmClass (AKA CASM_COMPILED_CONTRACT_CLASS) is the struct that represents the +// compiled Cairo contract class. type CasmClass struct { EntryPointsByType CasmEntryPointsByType `json:"entry_points_by_type"` ByteCode []*felt.Felt `json:"bytecode"` Prime NumAsHex `json:"prime"` CompilerVersion string `json:"compiler_version"` Hints []Hints `json:"hints"` - // a list of sizes of segments in the bytecode, each segment is hashed individually when computing the bytecode hash + // a list of sizes of segments in the bytecode, each segment is hashed + // individually when computing the bytecode hash BytecodeSegmentLengths *NestedUints `json:"bytecode_segment_lengths,omitempty"` } @@ -53,7 +55,8 @@ func (c *CasmClass) UnmarshalJSON(data []byte) error { } // An unsigned integer number in hex format (0x...) -// TODO: duplicate of rpc.NumAsHex to avoid import cycle. Maybe move to a shared 'types' package? +// TODO: duplicate of rpc.NumAsHex to avoid import cycle. Maybe move to a +// shared 'types' package? type NumAsHex string type CasmEntryPointsByType struct { @@ -64,7 +67,7 @@ type CasmEntryPointsByType struct { type CasmEntryPoint struct { Selector *felt.Felt `json:"selector"` - Offset int `json:"offset"` + Offset uint `json:"offset"` Builtins []string `json:"builtins"` } @@ -189,7 +192,7 @@ type Hints struct { // UnmarshalJSON implements json.Unmarshaler interface // -//nolint:dupl +//nolint:dupl // Just a small similarity with DoubleDeref UnmarshalJSON. func (h *Hints) UnmarshalJSON(data []byte) error { var tuple []json.RawMessage if err := json.Unmarshal(data, &tuple); err != nil { @@ -218,16 +221,19 @@ func (h Hints) MarshalJSON() ([]byte, error) { return json.Marshal([2]interface{}{h.Int, h.HintArr}) } -func (hints *Hints) Values() (int, []Hint) { - return hints.Int, hints.HintArr +func (h *Hints) Values() (int, []Hint) { + return h.Int, h.HintArr } -func (hints *Hints) Tuple() [2]any { - return [2]any{hints.Int, hints.HintArr} +func (h *Hints) Tuple() [2]any { + return [2]any{h.Int, h.HintArr} } -// Can be one of various hint types described in the spec and in the UnmarshalJSON method +// Can be one of various hint types described in the spec and in the +// UnmarshalJSON method // Ref: https://github.com/starkware-libs/starknet-specs/blob/d70a2e57c9a66db1bbf86c388f38d6295a6a2a75/api/starknet_executables.json#L276 +// +//nolint:lll // The link would be unclickable if we break the line. type Hint struct { Type string Data interface{} @@ -241,7 +247,8 @@ func (h *Hint) UnmarshalJSON(data []byte) error { var enumVal string if err := json.Unmarshal(data, &enumVal); err == nil { switch DeprecatedHintEnum(enumVal) { - case AssertCurrentAccessIndicesIsEmpty, AssertAllKeysUsed, AssertLeAssertThirdArcExcluded: + case AssertCurrentAccessIndicesIsEmpty, + AssertAllKeysUsed, AssertLeAssertThirdArcExcluded: h.Type = "enum" h.Data = DeprecatedHintEnum(enumVal) @@ -569,7 +576,7 @@ type DoubleDeref struct { // UnmarshalJSON implements json.Unmarshaler // -//nolint:dupl +//nolint:dupl // Just a small similarity with Hints UnmarshalJSON. func (dd *DoubleDeref) UnmarshalJSON(data []byte) error { var tuple []json.RawMessage if err := json.Unmarshal(data, &tuple); err != nil { @@ -598,7 +605,7 @@ func (dd DoubleDeref) MarshalJSON() ([]byte, error) { return json.Marshal([2]interface{}{dd.CellRef, dd.Offset}) } -func (dd *DoubleDeref) Values() (CellRef, int) { +func (dd *DoubleDeref) Values() (cellRef CellRef, offset int) { return dd.CellRef, dd.Offset } diff --git a/contracts/types_contract_class.go b/contracts/types_contract_class.go index 2bb4c910b..e38076ccd 100644 --- a/contracts/types_contract_class.go +++ b/contracts/types_contract_class.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "fmt" + "log" "github.com/NethermindEth/juno/core/felt" ) @@ -78,7 +79,7 @@ func (c *DeprecatedContractClass) UnmarshalJSON(content []byte) error { if !ok { return fmt.Errorf("unknown abi type %v", checkABI["type"]) } - //nolint:exhaustruct + //nolint:exhaustruct // Just assigning the type switch abiType { case string(ABITypeConstructor), string(ABITypeFunction), string(ABITypeL1Handler): ab = &FunctionABIEntry{} @@ -122,7 +123,9 @@ func encodeProgram(content []byte) (string, error) { if err != nil { return "", err } - gzipContent.Close() + if err := gzipContent.Close(); err != nil { + log.Printf("Error closing gzip content: %v", err) + } program := base64.StdEncoding.EncodeToString(buf.Bytes()) return program, nil @@ -174,13 +177,13 @@ func (ns *NestedString) UnmarshalJSON(data []byte) error { } // Replace '\n' to '' - out_str := bytes.ReplaceAll(out.Bytes(), []byte{10}, []byte{}) + outStr := bytes.ReplaceAll(out.Bytes(), []byte{10}, []byte{}) // Replace ',"' to ', "' - out_str = bytes.ReplaceAll(out_str, []byte{44, 34}, []byte{44, 32, 34}) + outStr = bytes.ReplaceAll(outStr, []byte{44, 34}, []byte{44, 32, 34}) // Replace ',{' to ', {' - out_str = bytes.ReplaceAll(out_str, []byte{44, 123}, []byte{44, 32, 123}) + outStr = bytes.ReplaceAll(outStr, []byte{44, 123}, []byte{44, 32, 123}) - *ns = NestedString(out_str) + *ns = NestedString(outStr) } return nil @@ -188,7 +191,7 @@ func (ns *NestedString) UnmarshalJSON(data []byte) error { type SierraEntryPoint struct { // The index of the function in the program - FunctionIdx int `json:"function_idx"` + FunctionIdx uint `json:"function_idx"` // A unique identifier of the entry point (function) in the program Selector *felt.Felt `json:"selector"` } diff --git a/curve/curve.go b/curve/curve.go index 2537b9976..4e97e49e6 100644 --- a/curve/curve.go +++ b/curve/curve.go @@ -14,7 +14,8 @@ import ( "github.com/consensys/gnark-crypto/ecc/stark-curve/fp" ) -// Verify verifies the validity of the signature for a given message hash using the StarkCurve. +// Verify verifies the validity of the signature for a given message hash using +// the StarkCurve. // // Parameters: // - msgHash: The message hash to be verified @@ -35,7 +36,8 @@ func Verify(msgHash, r, s, pubX *big.Int) (bool, error) { return pubKey.Verify(&junoCrypto.Signature{R: *rFelt, S: *sFelt}, msgHashFelt) } -// VerifyFelts verifies the validity of the signature for a given message hash using the StarkCurve. +// VerifyFelts verifies the validity of the signature for a given message hash +// using the StarkCurve. // It does the same as Verify, but with felt.Felt parameters. // // Parameters: @@ -65,7 +67,7 @@ func VerifyFelts(msgHash, r, s, pubX *felt.Felt) (bool, error) { // - s: The s component of the signature // - error: An error if any occurred during the signing process func Sign(msgHash, privKey *big.Int) (r, s *big.Int, err error) { - g1Affline := starkcurve.G1Affine{} //nolint:exhaustruct // just a struct initialization + var g1Affline starkcurve.G1Affine // generating pub and priv key types from the 'privKey' parameter g1a := g1Affline.ScalarMultiplicationBase(privKey) @@ -159,7 +161,7 @@ func GetRandomKeys() (privKey, x, y *big.Int, err error) { // - x: The x-coordinate of the point on the curve // - y: The y-coordinate of the point on the curve func PrivateKeyToPoint(privKey *big.Int) (x, y *big.Int) { - g1Affline := starkcurve.G1Affine{} //nolint:exhaustruct // just a struct initialization + var g1Affline starkcurve.G1Affine res := g1Affline.ScalarMultiplicationBase(privKey) return res.X.BigInt(new(big.Int)), res.Y.BigInt(new(big.Int)) @@ -173,6 +175,7 @@ func PrivateKeyToPoint(privKey *big.Int) (x, y *big.Int) { // Returns: // - *big.Int: The y-coordinate of the point func GetYCoordinate(starkX *felt.Felt) *felt.Felt { + //nolint:lll // The link would be unclickable if we break the line. // ref: https://github.com/NethermindEth/juno/blob/7d64642de90b6957c40a3b3ea75e6ad548a37f39/core/crypto/ecdsa.go#L26 xEl := starkX.Impl() @@ -189,7 +192,9 @@ func GetYCoordinate(starkX *felt.Felt) *felt.Felt { return &yFelt } -// HashPedersenElements calculates the hash of a list of elements using a golang Pedersen Hash. +// HashPedersenElements calculates the hash of a list of elements using a +// golang Pedersen Hash. +// // Parameters: // - elems: slice of big.Int pointers to be hashed // @@ -208,13 +213,15 @@ func HashPedersenElements(elems []*big.Int) (hash *big.Int) { hash = internalUtils.FeltToBigInt(feltHash) - return + return hash } -// ComputeHashOnElements computes the hash on the given elements using a golang Pedersen Hash implementation. +// ComputeHashOnElements computes the hash on the given elements using a +// golang Pedersen Hash implementation. // -// The function appends the length of `elems` to the slice and then calls the `HashPedersenElements` method -// passing in `elems` as an argument. The resulting hash is returned. +// The function appends the length of `elems` to the slice and then calls the +// `HashPedersenElements` method passing in `elems` as an argument. The +// resulting hash is returned. // // Parameters: // - elems: slice of big.Int pointers to be hashed @@ -251,8 +258,9 @@ func Poseidon(a, b *felt.Felt) *felt.Felt { return junoCrypto.Poseidon(a, b) } -// PedersenArray is a function that takes a variadic number of felt.Felt pointers as parameters and -// calls the PedersenArray function from the junoCrypto package with the provided parameters. +// PedersenArray is a function that takes a variadic number of felt.Felt +// pointers as parameters and calls the PedersenArray function from the +// junoCrypto package with the provided parameters. // // Parameters: // - felts: A variadic number of pointers to felt.Felt @@ -263,8 +271,9 @@ func PedersenArray(felts ...*felt.Felt) *felt.Felt { return junoCrypto.PedersenArray(felts...) } -// PoseidonArray is a function that takes a variadic number of felt.Felt pointers as parameters and -// calls the PoseidonArray function from the junoCrypto package with the provided parameters. +// PoseidonArray is a function that takes a variadic number of felt.Felt +// pointers as parameters and calls the PoseidonArray function from the +// junoCrypto package with the provided parameters. // // Parameters: // - felts: A variadic number of pointers to felt.Felt @@ -290,5 +299,5 @@ func StarknetKeccak(b []byte) *felt.Felt { // fmtPrivKey formats a private key to a 32 bytes array by padding it // with leading zeroes if necessary, which is required by the ecdsa.PrivateKey type. func fmtPrivKey(privKey *big.Int) ([]byte, error) { - return hex.DecodeString(fmt.Sprintf("%064s", privKey.Text(16))) //nolint:mnd + return hex.DecodeString(fmt.Sprintf("%064s", privKey.Text(16))) //nolint:mnd // hex base } diff --git a/curve/curve_test.go b/curve/curve_test.go index 6a39b8676..1445939f4 100644 --- a/curve/curve_test.go +++ b/curve/curve_test.go @@ -44,7 +44,7 @@ func BenchmarkSignatureVerify(b *testing.B) { randFelt, err := new(felt.Felt).SetRandom() require.NoError(b, err) hash := Pedersen( - internalUtils.RANDOM_FELT, + internalUtils.DeadBeef, randFelt, ) hashBigInt := internalUtils.FeltToBigInt(hash) @@ -64,7 +64,9 @@ func BenchmarkSignatureVerify(b *testing.B) { func TestPrivateToPoint(t *testing.T) { t.Parallel() x, _ := PrivateKeyToPoint(big.NewInt(2)) - expectedX, ok := new(big.Int).SetString("3324833730090626974525872402899302150520188025637965566623476530814354734325", 10) + expectedX, ok := new( + big.Int, + ).SetString("3324833730090626974525872402899302150520188025637965566623476530814354734325", 10) require.True(t, ok) assert.Equal(t, expectedX, x) @@ -234,9 +236,16 @@ func TestComputeHashOnElements(t *testing.T) { hashEmptyArray := ComputeHashOnElements([]*big.Int{}) hashEmptyArrayFelt := PedersenArray([]*felt.Felt{}...) - expectedHashEmmptyArray := internalUtils.HexToBN("0x49ee3eba8c1600700ee1b87eb599f16716b0b1022947733551fde4050ca6804") + expectedHashEmmptyArray := internalUtils.HexToBN( + "0x49ee3eba8c1600700ee1b87eb599f16716b0b1022947733551fde4050ca6804", + ) require.Equal(t, hashEmptyArray, expectedHashEmmptyArray, "Hash empty array wrong value.") - require.Equal(t, internalUtils.FeltToBigInt(hashEmptyArrayFelt), expectedHashEmmptyArray, "Hash empty array wrong value.") + require.Equal( + t, + internalUtils.FeltToBigInt(hashEmptyArrayFelt), + expectedHashEmmptyArray, + "Hash empty array wrong value.", + ) filledArray := []*big.Int{ big.NewInt(123782376), @@ -247,16 +256,26 @@ func TestComputeHashOnElements(t *testing.T) { hashFilledArray := ComputeHashOnElements(filledArray) hashFilledArrayFelt := PedersenArray(internalUtils.BigIntArrToFeltArr(filledArray)...) - expectedHashFilledArray := internalUtils.HexToBN("0x7b422405da6571242dfc245a43de3b0fe695e7021c148b918cd9cdb462cac59") + expectedHashFilledArray := internalUtils.HexToBN( + "0x7b422405da6571242dfc245a43de3b0fe695e7021c148b918cd9cdb462cac59", + ) require.Equal(t, hashFilledArray, expectedHashFilledArray, "Hash filled array wrong value.") - require.Equal(t, internalUtils.FeltToBigInt(hashFilledArrayFelt), expectedHashFilledArray, "Hash filled array wrong value.") + require.Equal( + t, + internalUtils.FeltToBigInt(hashFilledArrayFelt), + expectedHashFilledArray, + "Hash filled array wrong value.", + ) } // TestSignature tests the behaviour of the Sign and Verify functions against // the expected values. func TestSignature(t *testing.T) { t.Parallel() - hash := Pedersen(internalUtils.TestHexToFelt(t, "0x12773"), internalUtils.TestHexToFelt(t, "0x872362")) + hash := Pedersen( + internalUtils.TestHexToFelt(t, "0x12773"), + internalUtils.TestHexToFelt(t, "0x872362"), + ) hashBigInt := internalUtils.FeltToBigInt(hash) priv, x, _, err := GetRandomKeys() @@ -305,17 +324,32 @@ func TestVerifySignature(t *testing.T) { t.Parallel() // values verified with starknet.js - msgHash := internalUtils.TestHexToFelt(t, "0x2789daed76c8b750d5a609a706481034db9dc8b63ae01f505d21e75a8fc2336") - r := internalUtils.TestHexToFelt(t, "0x13e4e383af407f7ccc1f13195ff31a58cad97bbc6cf1d532798b8af616999d4") - s := internalUtils.TestHexToFelt(t, "0x44dd06cf67b2ba7ea4af346d80b0b439e02a0b5893c6e4dfda9ee204211c879") - pubKey := internalUtils.TestHexToFelt(t, "0x6c7c4408e178b2999cef9a5b3fa2a3dffc876892ad6a6bd19d1451a2256906c") + msgHash := internalUtils.TestHexToFelt( + t, + "0x2789daed76c8b750d5a609a706481034db9dc8b63ae01f505d21e75a8fc2336", + ) + r := internalUtils.TestHexToFelt( + t, + "0x13e4e383af407f7ccc1f13195ff31a58cad97bbc6cf1d532798b8af616999d4", + ) + s := internalUtils.TestHexToFelt( + t, + "0x44dd06cf67b2ba7ea4af346d80b0b439e02a0b5893c6e4dfda9ee204211c879", + ) + pubKey := internalUtils.TestHexToFelt( + t, + "0x6c7c4408e178b2999cef9a5b3fa2a3dffc876892ad6a6bd19d1451a2256906c", + ) resp, err := VerifyFelts(msgHash, r, s, pubKey) require.NoError(t, err) require.True(t, resp) // Change the last digit of the message hash to test invalid signature - wrongMsgHash := internalUtils.TestHexToFelt(t, "0x2789daed76c8b750d5a609a706481034db9dc8b63ae01f505d21e75a8fc2337") + wrongMsgHash := internalUtils.TestHexToFelt( + t, + "0x2789daed76c8b750d5a609a706481034db9dc8b63ae01f505d21e75a8fc2337", + ) resp, err = VerifyFelts(wrongMsgHash, r, s, pubKey) require.NoError(t, err) require.False(t, resp) diff --git a/devnet/devnet.go b/devnet/devnet.go index 46dc02e04..9439a6918 100644 --- a/devnet/devnet.go +++ b/devnet/devnet.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "fmt" + "log" "math/big" "net/http" "strings" @@ -24,8 +25,9 @@ type TestAccount struct { // NewDevNet creates a new DevNet instance. // -// It accepts an optional baseURL parameter, which is a string representing the base URL of the DevNet server. -// If no baseURL is provided, the default value of "http://localhost:5050" is used. +// It accepts an optional baseURL parameter, which is a string representing +// the base URL of the DevNet server. If no baseURL is provided, the default +// value of "http://localhost:5050" is used. // // Parameters: // - baseURL: a string representing the base URL of the DevNet server @@ -70,7 +72,11 @@ func (devnet *DevNet) api(uri string) string { // Returns: // - []TestAccount: a slice of TestAccount structs func (devnet *DevNet) Accounts() ([]TestAccount, error) { - req, err := http.NewRequest(http.MethodGet, devnet.api("/predeployed_accounts"), http.NoBody) + req, err := http.NewRequest( + http.MethodGet, + devnet.api("/predeployed_accounts"), + http.NoBody, + ) if err != nil { return nil, err } @@ -79,7 +85,7 @@ func (devnet *DevNet) Accounts() ([]TestAccount, error) { if err != nil { return nil, err } - defer resp.Body.Close() + defer closeBody(resp) var accounts []TestAccount err = json.NewDecoder(resp.Body).Decode(&accounts) @@ -112,7 +118,7 @@ func (devnet *DevNet) IsAlive() bool { if err != nil { return false } - defer resp.Body.Close() + defer closeBody(resp) return resp.StatusCode == http.StatusOK } @@ -155,7 +161,7 @@ func (devnet *DevNet) Mint(address *felt.Felt, amount *big.Int) (*MintResponse, if err != nil { return nil, err } - defer resp.Body.Close() + defer closeBody(resp) var mint MintResponse err = json.NewDecoder(resp.Body).Decode(&mint) @@ -190,10 +196,17 @@ func (devnet *DevNet) FeeToken() (*FeeToken, error) { if err != nil { return nil, err } - defer resp.Body.Close() + defer closeBody(resp) var token FeeToken err = json.NewDecoder(resp.Body).Decode(&token) return &token, err } + +// closeBody closes the response body and logs any errors. +func closeBody(resp *http.Response) { + if err := resp.Body.Close(); err != nil { + log.Printf("Error closing response body: %v", err) + } +} diff --git a/examples/deployAccount/main.go b/examples/deployAccount/main.go index e125439a1..44e24d75e 100644 --- a/examples/deployAccount/main.go +++ b/examples/deployAccount/main.go @@ -22,10 +22,10 @@ var predeployedClassHash = "0x61dac032f228abef9c6626f995015233097ae253a7f72d6855 // and prepares for the account deployment transaction. func main() { // Load variables from '.env' file - rpcProviderUrl := setup.GetRpcProviderUrl() + rpcProviderURL := setup.GetRPCProviderURL() // Initialise the client. - client, err := rpc.NewProvider(rpcProviderUrl) + client, err := rpc.NewProvider(rpcProviderURL) if err != nil { panic(err) } @@ -74,10 +74,18 @@ func main() { // At this point you need to add funds to precomputed address to use it. var input string - fmt.Println("\nThe `precomputedAddress` account needs to have enough STRK to perform a transaction.") - fmt.Printf("You can use the starknet faucet or send STRK to your `precomputedAddress`. You need approximately %f STRK. \n", feeInSTRK) + fmt.Println( + "\nThe `precomputedAddress` account needs to have enough STRK to perform a transaction.", + ) + fmt.Printf( + "You can use the starknet faucet or send STRK to your `precomputedAddress`. You need approximately %f STRK. \n", + feeInSTRK, + ) fmt.Println("When your account has been funded, press any key, then `enter` to continue: ") - fmt.Scan(&input) //nolint:errcheck + _, err = fmt.Scan(&input) + if err != nil { + panic(err) + } // Send transaction to the network resp, err := accnt.SendTransaction(context.Background(), deployAccountTxn) @@ -86,7 +94,9 @@ func main() { panic(err) } - fmt.Println("BroadcastDeployAccountTxn successfully submitted! Wait a few minutes to see it in Voyager.") + fmt.Println( + "BroadcastDeployAccountTxn successfully submitted! Wait a few minutes to see it in Voyager.", + ) fmt.Printf("Transaction hash: %v \n", resp.Hash) fmt.Printf("Contract address: %v \n", setup.PadZerosInFelt(resp.ContractAddress)) } diff --git a/examples/deployContractUDC/main.go b/examples/deployContractUDC/main.go index 32cbae2b9..dce464b33 100644 --- a/examples/deployContractUDC/main.go +++ b/examples/deployContractUDC/main.go @@ -17,7 +17,9 @@ import ( // NOTE : Please add in your keys only for testing purposes, in case of a leak you would potentially lose your funds. var ( // This is the class hash of a modern (Sierra) OpenZeppelin ERC20 contract. - erc20ContractHash, _ = utils.HexToFelt("0x073d71c37e20c569186445d2c497d2195b4c0be9a255d72dbad86662fcc63ae6") + erc20ContractHash, _ = utils.HexToFelt( + "0x073d71c37e20c569186445d2c497d2195b4c0be9a255d72dbad86662fcc63ae6", + ) ) // Example successful transaction created from this example on Sepolia @@ -26,14 +28,14 @@ func main() { fmt.Println("Starting deployContractUDC example") // Load variables from '.env' file - rpcProviderUrl := setup.GetRpcProviderUrl() + rpcProviderURL := setup.GetRPCProviderURL() accountAddress := setup.GetAccountAddress() accountCairoVersion := setup.GetAccountCairoVersion() privateKey := setup.GetPrivateKey() publicKey := setup.GetPublicKey() // Initialise connection to RPC provider - client, err := rpc.NewProvider(rpcProviderUrl) + client, err := rpc.NewProvider(rpcProviderURL) if err != nil { panic(fmt.Sprintf("Error dialling the RPC provider: %s", err)) } @@ -55,7 +57,13 @@ func main() { fmt.Println("Established connection with the client") // Initialise the account - accnt, err := account.NewAccount(client, accountAddressInFelt, publicKey, ks, accountCairoVersion) + accnt, err := account.NewAccount( + client, + accountAddressInFelt, + publicKey, + ks, + accountCairoVersion, + ) if err != nil { panic(err) } @@ -84,7 +92,13 @@ func main() { constructorCalldata = append(constructorCalldata, recipient, owner) // Deploy the contract with UDC - resp, salt, err := accnt.DeployContractWithUDC(context.Background(), erc20ContractHash, constructorCalldata, nil, nil) + resp, salt, err := accnt.DeployContractWithUDC( + context.Background(), + erc20ContractHash, + constructorCalldata, + nil, + nil, + ) if err != nil { panic(err) } @@ -102,7 +116,13 @@ func main() { fmt.Printf("Transaction status: %s\n", txReceipt.FinalityStatus) // Compute the contract address - contractAddress := utils.PrecomputeAddressForUDC(erc20ContractHash, salt, constructorCalldata, utils.UDCCairoV0, accnt.Address) + contractAddress := utils.PrecomputeAddressForUDC( + erc20ContractHash, + salt, + constructorCalldata, + utils.UDCCairoV0, + accnt.Address, + ) fmt.Printf("Contract deployed address: %s\n", contractAddress) } diff --git a/examples/internal/setup.go b/examples/internal/setup.go index 9e696fae2..9f3a21025 100644 --- a/examples/internal/setup.go +++ b/examples/internal/setup.go @@ -21,12 +21,12 @@ func init() { } // Validates whether the RPC_PROVIDER_URL variable has been set in the '.env' file and returns it; panics otherwise. -func GetRpcProviderUrl() string { +func GetRPCProviderURL() string { return getEnv("RPC_PROVIDER_URL") } // Validates whether the WS_PROVIDER_URL variable has been set in the '.env' file and returns it; panics otherwise. -func GetWsProviderUrl() string { +func GetWsProviderURL() string { return getEnv("WS_PROVIDER_URL") } diff --git a/examples/invoke/main.go b/examples/invoke/main.go index 3ed74934b..e888d7b24 100644 --- a/examples/invoke/main.go +++ b/examples/invoke/main.go @@ -22,14 +22,14 @@ var ( // the contract address, the contract method and the amount to be sent. func main() { // Load variables from '.env' file - rpcProviderUrl := setup.GetRpcProviderUrl() + rpcProviderURL := setup.GetRPCProviderURL() accountAddress := setup.GetAccountAddress() accountCairoVersion := setup.GetAccountCairoVersion() privateKey := setup.GetPrivateKey() publicKey := setup.GetPublicKey() // Initialise connection to RPC provider - client, err := rpc.NewProvider(rpcProviderUrl) + client, err := rpc.NewProvider(rpcProviderURL) if err != nil { panic(fmt.Sprintf("Error dialling the RPC provider: %s", err)) } @@ -49,7 +49,13 @@ func main() { panic(err) } // Initialise the account - accnt, err := account.NewAccount(client, accountAddressInFelt, publicKey, ks, accountCairoVersion) + accnt, err := account.NewAccount( + client, + accountAddressInFelt, + publicKey, + ks, + accountCairoVersion, + ) if err != nil { panic(err) } diff --git a/examples/invoke/simpleInvoke.go b/examples/invoke/simpleInvoke.go index 4a901f074..0626dea21 100644 --- a/examples/invoke/simpleInvoke.go +++ b/examples/invoke/simpleInvoke.go @@ -12,7 +12,12 @@ import ( ) // simpleInvoke is a function that shows how to easily send an invoke transaction. -func simpleInvoke(accnt *account.Account, contractAddress *felt.Felt, contractMethod string, amount *felt.Felt) { +func simpleInvoke( + accnt *account.Account, + contractAddress *felt.Felt, + contractMethod string, + amount *felt.Felt, +) { u256Amount, err := utils.HexToU256Felt(amount.String()) if err != nil { panic(err) diff --git a/examples/invoke/verboseInvoke.go b/examples/invoke/verboseInvoke.go index 42a39a1e0..2ae31ce53 100644 --- a/examples/invoke/verboseInvoke.go +++ b/examples/invoke/verboseInvoke.go @@ -13,7 +13,12 @@ import ( // verboseInvoke is a function that shows how to send an invoke transaction step by step, using only // a few helper functions. -func verboseInvoke(accnt *account.Account, contractAddress *felt.Felt, contractMethod string, amount *felt.Felt) { +func verboseInvoke( + accnt *account.Account, + contractAddress *felt.Felt, + contractMethod string, + amount *felt.Felt, +) { // Getting the nonce from the account nonce, err := accnt.Nonce(context.Background()) if err != nil { @@ -26,9 +31,11 @@ func verboseInvoke(accnt *account.Account, contractAddress *felt.Felt, contractM } // Building the functionCall struct, where : FnCall := rpc.FunctionCall{ - ContractAddress: contractAddress, // contractAddress is the contract that we want to call - EntryPointSelector: utils.GetSelectorFromNameFelt(contractMethod), // this is the function that we want to call - Calldata: u256Amount, // the calldata necessary to call the function. Here + ContractAddress: contractAddress, // contractAddress is the contract that we want to call + EntryPointSelector: utils.GetSelectorFromNameFelt( + contractMethod, + ), // this is the function that we want to call + Calldata: u256Amount, // the calldata necessary to call the function. Here // we are passing the "amount" value (a u256 cairo variable) for the "mint" function } diff --git a/examples/readEvents/main.go b/examples/readEvents/main.go index ca09d14d3..91d6c5db9 100644 --- a/examples/readEvents/main.go +++ b/examples/readEvents/main.go @@ -25,11 +25,11 @@ import ( // different ways of narrowing down event queries for efficient data retrieval. func main() { // Load variables from '.env' file - rpcProviderUrl := setup.GetRpcProviderUrl() - wsProviderUrl := setup.GetWsProviderUrl() + rpcProviderURL := setup.GetRPCProviderURL() + wsProviderURL := setup.GetWsProviderURL() // Initialise connection to RPC provider - provider, err := rpc.NewProvider(rpcProviderUrl) + provider, err := rpc.NewProvider(rpcProviderURL) if err != nil { panic(fmt.Sprintf("Error dialling the RPC provider: %v", err)) } @@ -45,7 +45,10 @@ func main() { // 3. call with Keys filter callWithKeysFilter(provider) // optional: filter with websocket - filterWithWebsocket(provider, wsProviderUrl) // if the wsProviderUrl is empty, the websocket example will be skipped + filterWithWebsocket( + provider, + wsProviderURL, + ) // if the wsProviderUrl is empty, the websocket example will be skipped // after all, here is a call with all filters combined fmt.Println("\n ----- 4. all filters -----") @@ -56,7 +59,9 @@ func main() { if err != nil { panic(fmt.Sprintf("failed to create felt from the contract address, error %v", err)) } - key3, err := utils.HexToFelt("0x1bfc84464f990c09cc0e5d64d18f54c3469fd5c467398bf31293051bade1c39") + key3, err := utils.HexToFelt( + "0x1bfc84464f990c09cc0e5d64d18f54c3469fd5c467398bf31293051bade1c39", + ) if err != nil { panic(fmt.Sprintf("failed to create felt from the provided key, error %v", err)) } @@ -96,7 +101,10 @@ func main() { fmt.Printf("number of returned events: %d\n", len(eventChunk.Events)) fmt.Printf("block number of the first event: %d\n", eventChunk.Events[0].BlockNumber) - fmt.Printf("block number of the last event: %d\n", eventChunk.Events[len(eventChunk.Events)-1].BlockNumber) + fmt.Printf( + "block number of the last event: %d\n", + eventChunk.Events[len(eventChunk.Events)-1].BlockNumber, + ) randomEvent := eventChunk.Events[rand.Intn(len(eventChunk.Events))] // get a random event from the chunk fmt.Printf("random event block number: %d\n", randomEvent.BlockNumber) fmt.Printf("random event tx hash: %s\n", randomEvent.TransactionHash.String()) @@ -125,8 +133,14 @@ func callWithChunkSizeAndContinuationToken(provider *rpc.Provider) { panic(fmt.Sprintf("error retrieving events: %v", err)) } fmt.Printf("number of returned events in the first chunk: %d\n", len(eventChunk.Events)) - fmt.Printf("block number of the first event in the first chunk: %d\n", eventChunk.Events[0].BlockNumber) - fmt.Printf("block number of the last event in the first chunk: %d\n", eventChunk.Events[len(eventChunk.Events)-1].BlockNumber) + fmt.Printf( + "block number of the first event in the first chunk: %d\n", + eventChunk.Events[0].BlockNumber, + ) + fmt.Printf( + "block number of the last event in the first chunk: %d\n", + eventChunk.Events[len(eventChunk.Events)-1].BlockNumber, + ) // Now we will get the second chunk secondEventChunk, err := provider.Events(context.Background(), rpc.EventsInput{ @@ -139,7 +153,10 @@ func callWithChunkSizeAndContinuationToken(provider *rpc.Provider) { panic(fmt.Sprintf("error retrieving events: %v", err)) } fmt.Printf("number of returned events in the second chunk: %d\n", len(secondEventChunk.Events)) - fmt.Printf("block number of the first event in the second chunk: %d\n", secondEventChunk.Events[0].BlockNumber) + fmt.Printf( + "block number of the first event in the second chunk: %d\n", + secondEventChunk.Events[0].BlockNumber, + ) fmt.Printf( "block number of the last event in the second chunk: %d\n", secondEventChunk.Events[len(secondEventChunk.Events)-1].BlockNumber, @@ -149,7 +166,9 @@ func callWithChunkSizeAndContinuationToken(provider *rpc.Provider) { func callWithBlockAndAddressFilters(provider *rpc.Provider) { fmt.Println() fmt.Println(" ----- 2. call with Block and Address filters -----") - contractAddress, err := utils.HexToFelt("0x049D36570D4e46f48e99674bd3fcc84644DdD6b96F7C741B1562B82f9e004dC7") // StarkGate: ETH Token + contractAddress, err := utils.HexToFelt( + "0x049D36570D4e46f48e99674bd3fcc84644DdD6b96F7C741B1562B82f9e004dC7", + ) // StarkGate: ETH Token if err != nil { panic(fmt.Sprintf("failed to create felt from the contract address, error %v", err)) } @@ -177,8 +196,14 @@ func callWithBlockAndAddressFilters(provider *rpc.Provider) { } fmt.Printf("number of returned events: %d\n", len(eventChunk.Events)) fmt.Printf("block number of the first event: %d\n", eventChunk.Events[0].BlockNumber) - fmt.Printf("block number of the last event: %d\n", eventChunk.Events[len(eventChunk.Events)-1].BlockNumber) - fmt.Printf("contract address of the first event: %s\n", eventChunk.Events[0].FromAddress.String()) + fmt.Printf( + "block number of the last event: %d\n", + eventChunk.Events[len(eventChunk.Events)-1].BlockNumber, + ) + fmt.Printf( + "contract address of the first event: %s\n", + eventChunk.Events[0].FromAddress.String(), + ) } func callWithKeysFilter(provider *rpc.Provider) { @@ -227,7 +252,10 @@ func callWithKeysFilter(provider *rpc.Provider) { fmt.Printf("number of returned events: %d\n", len(eventChunk.Events)) fmt.Printf("block number of the first event: %d\n", eventChunk.Events[0].BlockNumber) - fmt.Printf("block number of the last event: %d\n", eventChunk.Events[len(eventChunk.Events)-1].BlockNumber) + fmt.Printf( + "block number of the last event: %d\n", + eventChunk.Events[len(eventChunk.Events)-1].BlockNumber, + ) fmt.Printf("first key of the first event: %s\n", eventChunk.Events[0].Keys[0].String()) fmt.Println() @@ -260,13 +288,23 @@ func callWithKeysFilter(provider *rpc.Provider) { fmt.Printf("'Transfer' hash selector: %s\n", utils.GetSelectorFromNameFelt("Transfer").String()) fmt.Printf("'Approval' hash selector: %s\n", utils.GetSelectorFromNameFelt("Approval").String()) - fmt.Printf("'GameStarted' hash selector: %s\n", utils.GetSelectorFromNameFelt("GameStarted").String()) + fmt.Printf( + "'GameStarted' hash selector: %s\n", + utils.GetSelectorFromNameFelt("GameStarted").String(), + ) fmt.Printf("number of returned events: %d\n", len(eventChunk.Events)) fmt.Printf("block number of the first event: %d\n", eventChunk.Events[0].BlockNumber) - fmt.Printf("block number of the last event: %d\n", eventChunk.Events[len(eventChunk.Events)-1].BlockNumber) + fmt.Printf( + "block number of the last event: %d\n", + eventChunk.Events[len(eventChunk.Events)-1].BlockNumber, + ) transferEvent := findEventInChunk(eventChunk, "Transfer") - fmt.Printf("'Transfer' event found in block %d, tx hash: %s\n", transferEvent.BlockNumber, transferEvent.TransactionHash.String()) + fmt.Printf( + "'Transfer' event found in block %d, tx hash: %s\n", + transferEvent.BlockNumber, + transferEvent.TransactionHash.String(), + ) gameStartedEvent := findEventInChunk(eventChunk, "GameStarted") fmt.Printf( "'GameStarted' event found in block %d, tx hash: %s\n", @@ -274,11 +312,15 @@ func callWithKeysFilter(provider *rpc.Provider) { gameStartedEvent.TransactionHash.String(), ) approvalEvent := findEventInChunk(eventChunk, "Approval") - fmt.Printf("'Approval' event found in block %d, tx hash: %s\n", approvalEvent.BlockNumber, approvalEvent.TransactionHash.String()) + fmt.Printf( + "'Approval' event found in block %d, tx hash: %s\n", + approvalEvent.BlockNumber, + approvalEvent.TransactionHash.String(), + ) } -func filterWithWebsocket(provider *rpc.Provider, websocketUrl string) { - if websocketUrl == "" { +func filterWithWebsocket(provider *rpc.Provider, websocketURL string) { + if websocketURL == "" { fmt.Println("\nNo websocket URL provided. Skipping websocket filter...") return @@ -287,11 +329,13 @@ func filterWithWebsocket(provider *rpc.Provider, websocketUrl string) { fmt.Println() fmt.Println(" ----- 4. filter with websocket -----") - wsProvider, err := rpc.NewWebsocketProvider(websocketUrl) + wsProvider, err := rpc.NewWebsocketProvider(websocketURL) if err != nil { panic(fmt.Sprintf("error dialling the RPC provider: %v", err)) } - contractAddress, err := utils.HexToFelt("0x04718f5a0Fc34cC1AF16A1cdee98fFB20C31f5cD61D6Ab07201858f4287c938D") // StarkGate: ETH Token + contractAddress, err := utils.HexToFelt( + "0x04718f5a0Fc34cC1AF16A1cdee98fFB20C31f5cD61D6Ab07201858f4287c938D", + ) // StarkGate: ETH Token if err != nil { panic(fmt.Sprintf("failed to create felt from the contract address, error %v", err)) } @@ -306,20 +350,24 @@ func filterWithWebsocket(provider *rpc.Provider, websocketUrl string) { eventsChan := make(chan *rpc.EmittedEventWithFinalityStatus) // Subscribe to events - sub, err := wsProvider.SubscribeEvents(context.Background(), eventsChan, &rpc.EventSubscriptionInput{ - // Only events from this contract address - FromAddress: contractAddress, - // Subscribe to events from the latest block minus 10 (it'll return - // events from the last 10 blocks and progressively update as new blocks are added) - SubBlockID: new(rpc.SubscriptionBlockID).WithBlockNumber(blockNumber - 10), - Keys: [][]*felt.Felt{ - // the 'keys'filter behaves the same way as the RPC provider `starknet_getEvents` explained above. - // So this will return all events that have the 'Transfer' selector as the first key. - { - utils.GetSelectorFromNameFelt("Transfer"), + sub, err := wsProvider.SubscribeEvents( + context.Background(), + eventsChan, + &rpc.EventSubscriptionInput{ + // Only events from this contract address + FromAddress: contractAddress, + // Subscribe to events from the latest block minus 10 (it'll return + // events from the last 10 blocks and progressively update as new blocks are added) + SubBlockID: new(rpc.SubscriptionBlockID).WithBlockNumber(blockNumber - 10), + Keys: [][]*felt.Felt{ + // the 'keys'filter behaves the same way as the RPC provider `starknet_getEvents` explained above. + // So this will return all events that have the 'Transfer' selector as the first key. + { + utils.GetSelectorFromNameFelt("Transfer"), + }, }, }, - }) + ) if err != nil { panic(fmt.Sprintf("error subscribing to events: %v", err)) } @@ -331,7 +379,11 @@ func filterWithWebsocket(provider *rpc.Provider, websocketUrl string) { select { case event := <-eventsChan: // This case will be triggered when a new event is received. - fmt.Printf("New event received: Block %d, Event tx hash: %s\n", event.BlockNumber, event.TransactionHash.String()) + fmt.Printf( + "New event received: Block %d, Event tx hash: %s\n", + event.BlockNumber, + event.TransactionHash.String(), + ) case err := <-sub.Err(): // This case will be triggered when an error occurs. panic(err) diff --git a/examples/simpleCall/main.go b/examples/simpleCall/main.go index 373c53ab2..145b4851f 100644 --- a/examples/simpleCall/main.go +++ b/examples/simpleCall/main.go @@ -26,11 +26,11 @@ func main() { fmt.Println("Starting simpleCall example") // Load variables from '.env' file - rpcProviderUrl := setup.GetRpcProviderUrl() + rpcProviderURL := setup.GetRPCProviderURL() accountAddress := setup.GetAccountAddress() // Initialise connection to RPC provider - client, err := rpc.NewProvider(rpcProviderUrl) + client, err := rpc.NewProvider(rpcProviderURL) if err != nil { panic(fmt.Sprintf("Error dialling the RPC provider: %s", err)) } @@ -55,7 +55,11 @@ func main() { ContractAddress: contractAddress, EntryPointSelector: utils.GetSelectorFromNameFelt(contractMethod), } - decimalsResp, rpcErr := client.Call(context.Background(), getDecimalsTx, rpc.WithBlockTag("latest")) + decimalsResp, rpcErr := client.Call( + context.Background(), + getDecimalsTx, + rpc.WithBlockTag("latest"), + ) if rpcErr != nil { panic(rpcErr) } diff --git a/examples/simpleDeclare/main.go b/examples/simpleDeclare/main.go index 400031dde..ed30c7171 100644 --- a/examples/simpleDeclare/main.go +++ b/examples/simpleDeclare/main.go @@ -22,14 +22,14 @@ const ( // This example demonstrates how to declare a contract on Starknet. func main() { // Load variables from '.env' file - rpcProviderUrl := setup.GetRpcProviderUrl() + rpcProviderURL := setup.GetRPCProviderURL() accountAddress := setup.GetAccountAddress() accountCairoVersion := setup.GetAccountCairoVersion() privateKey := setup.GetPrivateKey() publicKey := setup.GetPublicKey() // Initialise connection to RPC provider - client, err := rpc.NewProvider(rpcProviderUrl) + client, err := rpc.NewProvider(rpcProviderURL) if err != nil { panic(fmt.Sprintf("Error dialling the RPC provider: %s", err)) } @@ -49,7 +49,13 @@ func main() { panic(err) } // Initialise the account - accnt, err := account.NewAccount(client, accountAddressInFelt, publicKey, ks, accountCairoVersion) + accnt, err := account.NewAccount( + client, + accountAddressInFelt, + publicKey, + ks, + accountCairoVersion, + ) if err != nil { panic(err) } @@ -63,7 +69,10 @@ func main() { } // Unmarshalling the sierra contract class from a JSON file. - contractClass, err := utils.UnmarshalJSONFileToType[contracts.ContractClass](sierraContractFilePath, "") + contractClass, err := utils.UnmarshalJSONFileToType[contracts.ContractClass]( + sierraContractFilePath, + "", + ) if err != nil { panic(err) } @@ -85,9 +94,15 @@ func main() { fmt.Println("You need to: ") fmt.Println("- create a different Cairo contract,") fmt.Println("- compile it,") - fmt.Println("- paste the new casm and sierra json files in this 'examples/simpleDeclare' folder,") - fmt.Println("- change the 'casmContractFilePath' and 'sierraContractFilePath' variables to the new files names,") - fmt.Println("and then, run the example again. You can use Scarb for it: https://docs.swmansion.com/scarb/") + fmt.Println( + "- paste the new casm and sierra json files in this 'examples/simpleDeclare' folder,", + ) + fmt.Println( + "- change the 'casmContractFilePath' and 'sierraContractFilePath' variables to the new files names,", + ) + fmt.Println( + "and then, run the example again. You can use Scarb for it: https://docs.swmansion.com/scarb/", + ) return } diff --git a/examples/typedData/main.go b/examples/typedData/main.go index 006b07813..0fc3d6007 100644 --- a/examples/typedData/main.go +++ b/examples/typedData/main.go @@ -8,7 +8,7 @@ import ( "github.com/NethermindEth/starknet.go/account" setup "github.com/NethermindEth/starknet.go/examples/internal" "github.com/NethermindEth/starknet.go/rpc" - "github.com/NethermindEth/starknet.go/typedData" + "github.com/NethermindEth/starknet.go/typedata" "github.com/NethermindEth/starknet.go/utils" ) @@ -20,7 +20,7 @@ func main() { fmt.Println("Account address:", accnt.Address) // This is how you can initialise a typed data from a JSON file - ttd, err := utils.UnmarshalJSONFileToType[typedData.TypedData]("./baseExample.json", "") + ttd, err := utils.UnmarshalJSONFileToType[typedata.TypedData]("./baseExample.json", "") if err != nil { panic(fmt.Errorf("fail to unmarshal TypedData: %w", err)) } @@ -50,14 +50,14 @@ func main() { func localSetup() *account.Account { // Load variables from '.env' file - rpcProviderUrl := setup.GetRpcProviderUrl() + rpcProviderURL := setup.GetRPCProviderURL() accountAddress := setup.GetAccountAddress() accountCairoVersion := setup.GetAccountCairoVersion() privateKey := setup.GetPrivateKey() publicKey := setup.GetPublicKey() // Initialise connection to RPC provider - client, err := rpc.NewProvider(rpcProviderUrl) + client, err := rpc.NewProvider(rpcProviderURL) if err != nil { panic(fmt.Sprintf("Error dialling the RPC provider: %s", err)) } @@ -77,7 +77,13 @@ func localSetup() *account.Account { panic(err) } // Initialise the account - accnt, err := account.NewAccount(client, accountAddressInFelt, publicKey, ks, accountCairoVersion) + accnt, err := account.NewAccount( + client, + accountAddressInFelt, + publicKey, + ks, + accountCairoVersion, + ) if err != nil { panic(err) } diff --git a/examples/websocket/main.go b/examples/websocket/main.go index a89cefba0..bf876a714 100644 --- a/examples/websocket/main.go +++ b/examples/websocket/main.go @@ -13,10 +13,10 @@ func main() { fmt.Println("Starting websocket example") // Load variables from '.env' file - wsProviderUrl := setup.GetWsProviderUrl() + wsProviderURL := setup.GetWsProviderURL() // Initialise connection to WS provider - wsClient, err := rpc.NewWebsocketProvider(wsProviderUrl) + wsClient, err := rpc.NewWebsocketProvider(wsProviderURL) if err != nil { panic(fmt.Sprintf("Error dialling the WS provider: %s", err)) } @@ -33,7 +33,11 @@ func main() { // We then call the desired websocket method, passing in the channel and the parameters if needed. // For example, to subscribe to new block headers, we call the SubscribeNewHeads method, passing in the channel and the blockID. // As the description says it's optional, we pass an empty BlockID as value. That way, the latest block will be used by default. - sub, err := wsClient.SubscribeNewHeads(context.Background(), newHeadsChan, rpc.SubscriptionBlockID{}) + sub, err := wsClient.SubscribeNewHeads( + context.Background(), + newHeadsChan, + rpc.SubscriptionBlockID{}, + ) if err != nil { panic(err) } diff --git a/hash/hash.go b/hash/hash.go index 56f0404cd..6a36f7b08 100644 --- a/hash/hash.go +++ b/hash/hash.go @@ -13,9 +13,9 @@ import ( ) var ( - PREFIX_TRANSACTION = new(felt.Felt).SetBytes([]byte("invoke")) - PREFIX_DECLARE = new(felt.Felt).SetBytes([]byte("declare")) - PREFIX_DEPLOY_ACCOUNT = new(felt.Felt).SetBytes([]byte("deploy_account")) + prefixInvoke = new(felt.Felt).SetBytes([]byte("invoke")) + prefixDeclare = new(felt.Felt).SetBytes([]byte("declare")) + prefixDeployAccount = new(felt.Felt).SetBytes([]byte("deploy_account")) ) var ( @@ -23,8 +23,8 @@ var ( ErrFeltToBigInt = errors.New("felt to BigInt error") ) -// CalculateDeprecatedTransactionHashCommon calculates the transaction hash common to be used -// in the StarkNet network - a unique identifier of the transaction. +// CalculateDeprecatedTransactionHashCommon calculates the transaction hash +// common to be used in the StarkNet network - a unique identifier of the transaction. // [specification]: https://github.com/starkware-libs/cairo-lang/blob/8276ac35830148a397e1143389f23253c8b80e93/src/starkware/starknet/core/os/transaction_hash/deprecated_transaction_hash.py#L29 // // Parameters: @@ -34,13 +34,13 @@ var ( // - entryPointSelector: The selector of the entry point // - calldata: The data of the transaction // - maxFee: The maximum fee for the transaction -// - chainId: The ID of the blockchain +// - chainID: The ID of the blockchain // - additionalData: Additional data to be included in the hash // // Returns: // - *felt.Felt: the calculated transaction hash // -//nolint:lll +//nolint:lll // The link would be unclickable if we break the line. func CalculateDeprecatedTransactionHashCommon( txHashPrefix *felt.Felt, version *felt.Felt, @@ -48,7 +48,7 @@ func CalculateDeprecatedTransactionHashCommon( entryPointSelector *felt.Felt, calldata *felt.Felt, maxFee *felt.Felt, - chainId *felt.Felt, + chainID *felt.Felt, additionalData []*felt.Felt, ) *felt.Felt { dataToHash := []*felt.Felt{ @@ -58,7 +58,7 @@ func CalculateDeprecatedTransactionHashCommon( entryPointSelector, calldata, maxFee, - chainId, + chainID, } dataToHash = append(dataToHash, additionalData...) @@ -67,13 +67,17 @@ func CalculateDeprecatedTransactionHashCommon( // ClassHash calculates the hash of a contract class. // -// It takes a contract class as input and calculates the hash by combining various elements of the class. -// The hash is calculated using the PoseidonArray function from the Curve package. -// The elements used in the hash calculation include the contract class version, constructor entry point, +// It takes a contract class as input and calculates the hash by combining +// various elements of the class. The hash is calculated using the +// PoseidonArray function from the Curve package. The elements used in the +// hash calculation include the contract class version, constructor entry point, // external entry point, L1 handler entry point, ABI, and Sierra program. -// The ABI is converted to bytes and then hashed using the StarknetKeccak function from the Curve package. -// Finally, the ContractClassVersionHash, ExternalHash, L1HandleHash, ConstructorHash, ABIHash, and -// SierraProgamHash are combined using the PoseidonArray function from the Curve package. +// The ABI is converted to bytes and then hashed using the StarknetKeccak +// function from the Curve package. +// Finally, the ContractClassVersionHash, ExternalHash, L1HandleHash, +// ConstructorHash, ABIHash, and +// SierraProgamHash are combined using the PoseidonArray function from the +// Curve package. // // Parameters: // - contract: A contract class object of type contracts.ContractClass. @@ -93,7 +97,15 @@ func ClassHash(contract *contracts.ContractClass) *felt.Felt { ABIHash := curve.StarknetKeccak([]byte(contract.ABI)) // https://docs.starknet.io/architecture-and-concepts/smart-contracts/class-hash/#computing_the_cairo_1_class_hash - return curve.PoseidonArray(ContractClassVersionHash, ExternalHash, L1HandleHash, ConstructorHash, ABIHash, SierraProgamHash) + //nolint:lll // The link would be unclickable if we break the line. + return curve.PoseidonArray( + ContractClassVersionHash, + ExternalHash, + L1HandleHash, + ConstructorHash, + ABIHash, + SierraProgamHash, + ) } // hashEntryPointByType calculates the hash of an entry point by type. @@ -102,11 +114,16 @@ func ClassHash(contract *contracts.ContractClass) *felt.Felt { // - entryPoint: A slice of contracts.SierraEntryPoint objects // // Returns: -// - *felt.Felt: a pointer to a felt.Felt object that represents the calculated hash. +// - *felt.Felt: a pointer to a felt.Felt object that represents the calculated +// hash. func hashEntryPointByType(entryPoint []contracts.SierraEntryPoint) *felt.Felt { flattened := make([]*felt.Felt, 0, len(entryPoint)) for _, elt := range entryPoint { - flattened = append(flattened, elt.Selector, new(felt.Felt).SetUint64(uint64(elt.FunctionIdx))) + flattened = append( + flattened, + elt.Selector, + new(felt.Felt).SetUint64(uint64(elt.FunctionIdx)), + ) } return curve.PoseidonArray(flattened...) @@ -119,28 +136,32 @@ type bytecodeSegment struct { Size uint64 } -// getByteCodeSegmentHasher calculates hasher function for byte code array from casm file -// this code is adaptation of: +// getByteCodeSegmentHasher calculates hasher function for byte code array from +// casm file. This code is adaptation of: // https://github.com/starkware-libs/cairo-lang/blob/efa9648f57568aad8f8a13fbf027d2de7c63c2c0/src/starkware/starknet/core/os/contract_class/compiled_class_hash.py // // Parameters: // - bytecode: Array of compiled bytecode values from casm file -// - bytecodeSegmentLengths: Nested datastructure of bytecode_segment_lengths values from casm file -// - visitedPcs: array pointer for tracking which bytecode bits were already processed, needed for recursive processing -// - bytecodeOffset: pointer at current offset in bytecode array, needed for recursive processing organisation +// - bytecodeSegmentLengths: Nested datastructure of bytecode_segment_lengths +// values from casm file +// - visitedPcs: array pointer for tracking which bytecode bits were already +// processed, needed for recursive processing +// - bytecodeOffset: pointer at current offset in bytecode array, needed for +// recursive processing organisation // // Returns: -// - hasherFunc: closure that calculates hash for given bytecode array, or nil in case of error +// - hasherFunc: closure that calculates hash for given bytecode array, or nil +// in case of error // - uint64: size of the current processed bytecode array, or nil in case of error // - error: error if any happened or nil if everything fine // -//nolint:lll +//nolint:lll // The link would be unclickable if we break the line. func getByteCodeSegmentHasher( bytecode []*felt.Felt, bytecodeSegmentLengths contracts.NestedUints, visitedPcs *[]uint64, bytecodeOffset uint64, -) (hasherFunc, uint64, error) { +) (hasherF hasherFunc, size uint64, err error) { if !bytecodeSegmentLengths.IsArray { segmentValue := *bytecodeSegmentLengths.Value segmentEnd := bytecodeOffset + segmentValue @@ -194,9 +215,9 @@ func getByteCodeSegmentHasher( visitedPcAfter = &visitedPcsData[len(visitedPcsData)-1] } - is_used := visitedPcAfter != visitedPcBefore + isUsed := visitedPcAfter != visitedPcBefore - if is_used && *visitedPcBefore != bytecodeOffset { + if isUsed && *visitedPcBefore != bytecodeOffset { return nil, 0, errors.New( "invalid segment structure: PC {visited_pc_before} was visited, " + "but the beginning of the segment ({bytecode_offset}) was not", @@ -230,7 +251,8 @@ func getByteCodeSegmentHasher( // // Parameters: // - bytecode: Array of compiled bytecode values from casm file -// - bytecodeSegmentLengths: Nested datastructure of bytecode_segment_lengths values from casm file +// - bytecodeSegmentLengths: Nested datastructure of bytecode_segment_lengths +// values from casm file // // Returns: // - *felt.Felt: Hash value @@ -242,7 +264,7 @@ func hashCasmClassByteCode( visited := make([]uint64, len(bytecode)) for i := range bytecode { - visited[i] = uint64(i) + visited[i] = uint64(i) //nolint:gosec // Never underflows } slices.Reverse(visited) @@ -274,7 +296,10 @@ func CompiledClassHash(casmClass *contracts.CasmClass) (*felt.Felt, error) { var err error if casmClass.BytecodeSegmentLengths != nil { - ByteCodeHasH, err = hashCasmClassByteCode(casmClass.ByteCode, *casmClass.BytecodeSegmentLengths) + ByteCodeHasH, err = hashCasmClassByteCode( + casmClass.ByteCode, + *casmClass.BytecodeSegmentLengths, + ) if err != nil { return nil, err } @@ -282,8 +307,15 @@ func CompiledClassHash(casmClass *contracts.CasmClass) (*felt.Felt, error) { ByteCodeHasH = curve.PoseidonArray(casmClass.ByteCode...) } + //nolint:lll // The link would be unclickable if we break the line. // https://github.com/software-mansion/starknet.py/blob/39af414389984efbc6edc48b0fe1f914ea5b9a77/starknet_py/hash/casm_class_hash.py#L18 - return curve.PoseidonArray(ContractClassVersionHash, ExternalHash, L1HandleHash, ConstructorHash, ByteCodeHasH), nil + return curve.PoseidonArray( + ContractClassVersionHash, + ExternalHash, + L1HandleHash, + ConstructorHash, + ByteCodeHasH, + ), nil } // hashCasmClassEntryPointByType calculates the hash of a CasmClassEntryPoint array. @@ -301,7 +333,12 @@ func hashCasmClassEntryPointByType(entryPoint []contracts.CasmEntryPoint) *felt. builtInFlat = append(builtInFlat, new(felt.Felt).SetBytes([]byte(builtIn))) } builtInHash := curve.PoseidonArray(builtInFlat...) - flattened = append(flattened, elt.Selector, new(felt.Felt).SetUint64(uint64(elt.Offset)), builtInHash) + flattened = append( + flattened, + elt.Selector, + new(felt.Felt).SetUint64(uint64(elt.Offset)), + builtInHash, + ) } return curve.PoseidonArray(flattened...) @@ -311,14 +348,16 @@ func hashCasmClassEntryPointByType(entryPoint []contracts.CasmEntryPoint) *felt. // // Parameters: // - txn: The invoke V0 transaction to calculate the hash for -// - chainId: The chain ID as a *felt.Felt +// - chainID: The chain ID as a *felt.Felt // // Returns: // - *felt.Felt: the calculated transaction hash // - error: an error if any -func TransactionHashInvokeV0(txn *rpc.InvokeTxnV0, chainId *felt.Felt) (*felt.Felt, error) { +func TransactionHashInvokeV0(txn *rpc.InvokeTxnV0, chainID *felt.Felt) (*felt.Felt, error) { + //nolint:lll // The link would be unclickable if we break the line. // https://docs.starknet.io/architecture-and-concepts/network-architecture/transactions/#v0_deprecated_hash_calculation - if txn.Version == "" || len(txn.Calldata) == 0 || txn.MaxFee == nil || txn.EntryPointSelector == nil { + if txn.Version == "" || len(txn.Calldata) == 0 || txn.MaxFee == nil || + txn.EntryPointSelector == nil { return nil, ErrNotAllParametersSet } @@ -329,13 +368,13 @@ func TransactionHashInvokeV0(txn *rpc.InvokeTxnV0, chainId *felt.Felt) (*felt.Fe } return CalculateDeprecatedTransactionHashCommon( - PREFIX_TRANSACTION, + prefixInvoke, txnVersionFelt, txn.ContractAddress, txn.EntryPointSelector, calldataHash, txn.MaxFee, - chainId, + chainID, []*felt.Felt{}, ), nil } @@ -344,14 +383,16 @@ func TransactionHashInvokeV0(txn *rpc.InvokeTxnV0, chainId *felt.Felt) (*felt.Fe // // Parameters: // - txn: The invoke V1 transaction to calculate the hash for -// - chainId: The chain ID as a *felt.Felt +// - chainID: The chain ID as a *felt.Felt // // Returns: // - *felt.Felt: the calculated transaction hash // - error: an error if any -func TransactionHashInvokeV1(txn *rpc.InvokeTxnV1, chainId *felt.Felt) (*felt.Felt, error) { +func TransactionHashInvokeV1(txn *rpc.InvokeTxnV1, chainID *felt.Felt) (*felt.Felt, error) { + //nolint:lll // The link would be unclickable if we break the line. // https://docs.starknet.io/architecture-and-concepts/network-architecture/transactions/#v1_deprecated_hash_calculation - if txn.Version == "" || len(txn.Calldata) == 0 || txn.Nonce == nil || txn.MaxFee == nil || txn.SenderAddress == nil { + if txn.Version == "" || len(txn.Calldata) == 0 || txn.Nonce == nil || txn.MaxFee == nil || + txn.SenderAddress == nil { return nil, ErrNotAllParametersSet } @@ -362,13 +403,13 @@ func TransactionHashInvokeV1(txn *rpc.InvokeTxnV1, chainId *felt.Felt) (*felt.Fe } return CalculateDeprecatedTransactionHashCommon( - PREFIX_TRANSACTION, + prefixInvoke, txnVersionFelt, txn.SenderAddress, &felt.Zero, calldataHash, txn.MaxFee, - chainId, + chainID, []*felt.Felt{txn.Nonce}, ), nil } @@ -377,15 +418,18 @@ func TransactionHashInvokeV1(txn *rpc.InvokeTxnV1, chainId *felt.Felt) (*felt.Fe // // Parameters: // - txn: The invoke V3 transaction to calculate the hash for -// - chainId: The chain ID as a *felt.Felt +// - chainID: The chain ID as a *felt.Felt // // Returns: // - *felt.Felt: the calculated transaction hash // - error: an error if any -func TransactionHashInvokeV3(txn *rpc.InvokeTxnV3, chainId *felt.Felt) (*felt.Felt, error) { +func TransactionHashInvokeV3(txn *rpc.InvokeTxnV3, chainID *felt.Felt) (*felt.Felt, error) { + //nolint:lll // The links would be unclickable if we break the line. // https://github.com/starknet-io/SNIPs/blob/main/SNIPS/snip-8.md#protocol-changes // https://docs.starknet.io/architecture-and-concepts/network-architecture/transactions/#v3_hash_calculation - if txn.Version == "" || txn.ResourceBounds == nil || len(txn.Calldata) == 0 || txn.Nonce == nil || txn.SenderAddress == nil || + if txn.Version == "" || txn.ResourceBounds == nil || len(txn.Calldata) == 0 || + txn.Nonce == nil || + txn.SenderAddress == nil || txn.PayMasterData == nil || txn.AccountDeploymentData == nil { return nil, ErrNotAllParametersSet @@ -409,12 +453,12 @@ func TransactionHashInvokeV3(txn *rpc.InvokeTxnV3, chainId *felt.Felt) (*felt.Fe } return crypto.PoseidonArray( - PREFIX_TRANSACTION, + prefixInvoke, txnVersionFelt, txn.SenderAddress, tipAndResourceHash, crypto.PoseidonArray(txn.PayMasterData...), - chainId, + chainID, txn.Nonce, new(felt.Felt).SetUint64(DAUint64), crypto.PoseidonArray(txn.AccountDeploymentData...), @@ -426,14 +470,16 @@ func TransactionHashInvokeV3(txn *rpc.InvokeTxnV3, chainId *felt.Felt) (*felt.Fe // // Parameters: // - txn: The declare V1 transaction to calculate the hash for -// - chainId: The chain ID as a *felt.Felt +// - chainID: The chain ID as a *felt.Felt // // Returns: // - *felt.Felt: the calculated transaction hash // - error: an error if any -func TransactionHashDeclareV1(txn *rpc.DeclareTxnV1, chainId *felt.Felt) (*felt.Felt, error) { +func TransactionHashDeclareV1(txn *rpc.DeclareTxnV1, chainID *felt.Felt) (*felt.Felt, error) { + //nolint:lll // The link would be unclickable if we break the line. // https://docs.starknet.io/architecture-and-concepts/network-architecture/transactions/#v1_deprecated_hash_calculation_2 - if txn.SenderAddress == nil || txn.Version == "" || txn.ClassHash == nil || txn.MaxFee == nil || txn.Nonce == nil { + if txn.SenderAddress == nil || txn.Version == "" || txn.ClassHash == nil || + txn.MaxFee == nil || txn.Nonce == nil { return nil, ErrNotAllParametersSet } @@ -445,29 +491,37 @@ func TransactionHashDeclareV1(txn *rpc.DeclareTxnV1, chainId *felt.Felt) (*felt. } return CalculateDeprecatedTransactionHashCommon( - PREFIX_DECLARE, + prefixDeclare, txnVersionFelt, txn.SenderAddress, &felt.Zero, calldataHash, txn.MaxFee, - chainId, + chainID, []*felt.Felt{txn.Nonce}, ), nil } -// TransactionHashDeclareV2 calculates the transaction hash for a declare V2 transaction. +// TransactionHashDeclareV2 calculates the transaction hash for a declare V2 +// transaction. // // Parameters: // - txn: The declare V2 transaction to calculate the hash for -// - chainId: The chain ID as a *felt.Felt +// - chainID: The chain ID as a *felt.Felt // // Returns: // - *felt.Felt: the calculated transaction hash // - error: an error if any -func TransactionHashDeclareV2(txn *rpc.DeclareTxnV2, chainId *felt.Felt) (*felt.Felt, error) { +func TransactionHashDeclareV2( + txn *rpc.DeclareTxnV2, + chainID *felt.Felt, +) (*felt.Felt, error) { + //nolint:lll // The link would be unclickable if we break the line. // https://docs.starknet.io/architecture-and-concepts/network-architecture/transactions/#v2_deprecated_hash_calculation - if txn.CompiledClassHash == nil || txn.SenderAddress == nil || txn.Version == "" || txn.ClassHash == nil || txn.MaxFee == nil || + if txn.CompiledClassHash == nil || txn.SenderAddress == nil || + txn.Version == "" || + txn.ClassHash == nil || + txn.MaxFee == nil || txn.Nonce == nil { return nil, ErrNotAllParametersSet } @@ -480,13 +534,13 @@ func TransactionHashDeclareV2(txn *rpc.DeclareTxnV2, chainId *felt.Felt) (*felt. } return CalculateDeprecatedTransactionHashCommon( - PREFIX_DECLARE, + prefixDeclare, txnVersionFelt, txn.SenderAddress, &felt.Zero, calldataHash, txn.MaxFee, - chainId, + chainID, []*felt.Felt{txn.Nonce, txn.CompiledClassHash}, ), nil } @@ -495,15 +549,21 @@ func TransactionHashDeclareV2(txn *rpc.DeclareTxnV2, chainId *felt.Felt) (*felt. // // Parameters: // - txn: The declare V3 transaction to calculate the hash for -// - chainId: The chain ID as a *felt.Felt +// - chainID: The chain ID as a *felt.Felt // // Returns: // - *felt.Felt: the calculated transaction hash // - error: an error if any -func TransactionHashDeclareV3(txn *rpc.DeclareTxnV3, chainId *felt.Felt) (*felt.Felt, error) { +func TransactionHashDeclareV3( + txn *rpc.DeclareTxnV3, + chainID *felt.Felt, +) (*felt.Felt, error) { + //nolint:lll // The links would be unclickable if we break the line. // https://docs.starknet.io/architecture-and-concepts/network-architecture/transactions/#v3_hash_calculation_2 // https://github.com/starknet-io/SNIPs/blob/main/SNIPS/snip-8.md#protocol-changes - if txn.Version == "" || txn.ResourceBounds == nil || txn.Nonce == nil || txn.SenderAddress == nil || txn.PayMasterData == nil || + if txn.Version == "" || txn.ResourceBounds == nil || txn.Nonce == nil || + txn.SenderAddress == nil || + txn.PayMasterData == nil || txn.AccountDeploymentData == nil || txn.ClassHash == nil || txn.CompiledClassHash == nil { @@ -529,12 +589,12 @@ func TransactionHashDeclareV3(txn *rpc.DeclareTxnV3, chainId *felt.Felt) (*felt. } return crypto.PoseidonArray( - PREFIX_DECLARE, + prefixDeclare, txnVersionFelt, txn.SenderAddress, tipAndResourceHash, crypto.PoseidonArray(txn.PayMasterData...), - chainId, + chainID, txn.Nonce, new(felt.Felt).SetUint64(DAUint64), crypto.PoseidonArray(txn.AccountDeploymentData...), @@ -543,19 +603,26 @@ func TransactionHashDeclareV3(txn *rpc.DeclareTxnV3, chainId *felt.Felt) (*felt. ), nil } -// TransactionHashBroadcastDeclareV3 calculates the transaction hash for a broadcast declare V3 transaction. +// TransactionHashBroadcastDeclareV3 calculates the transaction hash for a +// broadcast declare V3 transaction. // // Parameters: // - txn: The broadcast declare V3 transaction to calculate the hash for -// - chainId: The chain ID as a *felt.Felt +// - chainID: The chain ID as a *felt.Felt // // Returns: // - *felt.Felt: the calculated transaction hash // - error: an error if any -func TransactionHashBroadcastDeclareV3(txn *rpc.BroadcastDeclareTxnV3, chainId *felt.Felt) (*felt.Felt, error) { +func TransactionHashBroadcastDeclareV3( + txn *rpc.BroadcastDeclareTxnV3, + chainID *felt.Felt, +) (*felt.Felt, error) { + //nolint:lll // The links would be unclickable if we break the line. // https://docs.starknet.io/architecture-and-concepts/network-architecture/transactions/#v3_hash_calculation_2 // https://github.com/starknet-io/SNIPs/blob/main/SNIPS/snip-8.md#protocol-changes - if txn.Version == "" || txn.ResourceBounds == nil || txn.Nonce == nil || txn.SenderAddress == nil || txn.PayMasterData == nil || + if txn.Version == "" || txn.ResourceBounds == nil || txn.Nonce == nil || + txn.SenderAddress == nil || + txn.PayMasterData == nil || txn.AccountDeploymentData == nil || txn.ContractClass == nil || txn.CompiledClassHash == nil { @@ -581,12 +648,12 @@ func TransactionHashBroadcastDeclareV3(txn *rpc.BroadcastDeclareTxnV3, chainId * } return crypto.PoseidonArray( - PREFIX_DECLARE, + prefixDeclare, txnVersionFelt, txn.SenderAddress, tipAndResourceHash, crypto.PoseidonArray(txn.PayMasterData...), - chainId, + chainID, txn.Nonce, new(felt.Felt).SetUint64(DAUint64), crypto.PoseidonArray(txn.AccountDeploymentData...), @@ -595,17 +662,22 @@ func TransactionHashBroadcastDeclareV3(txn *rpc.BroadcastDeclareTxnV3, chainId * ), nil } -// TransactionHashDeployAccountV1 calculates the transaction hash for a deploy account V1 transaction. +// TransactionHashDeployAccountV1 calculates the transaction hash for a deploy +// account V1 transaction. // // Parameters: // - txn: The deploy account V1 transaction to calculate the hash for // - contractAddress: The contract address as parameters as a *felt.Felt -// - chainId: The chain ID as a *felt.Felt +// - chainID: The chain ID as a *felt.Felt // // Returns: // - *felt.Felt: the calculated transaction hash // - error: an error if any -func TransactionHashDeployAccountV1(txn *rpc.DeployAccountTxnV1, contractAddress, chainId *felt.Felt) (*felt.Felt, error) { +func TransactionHashDeployAccountV1( + txn *rpc.DeployAccountTxnV1, + contractAddress, chainID *felt.Felt, +) (*felt.Felt, error) { + //nolint:lll // The link would be unclickable if we break the line. // https://docs.starknet.io/architecture-and-concepts/network-architecture/transactions/#v1_deprecated_hash_calculation_3 calldata := []*felt.Felt{txn.ClassHash, txn.ContractAddressSalt} calldata = append(calldata, txn.ConstructorCalldata...) @@ -617,30 +689,36 @@ func TransactionHashDeployAccountV1(txn *rpc.DeployAccountTxnV1, contractAddress } return CalculateDeprecatedTransactionHashCommon( - PREFIX_DEPLOY_ACCOUNT, + prefixDeployAccount, versionFelt, contractAddress, &felt.Zero, calldataHash, txn.MaxFee, - chainId, + chainID, []*felt.Felt{txn.Nonce}, ), nil } -// TransactionHashDeployAccountV3 calculates the transaction hash for a deploy account V3 transaction. +// TransactionHashDeployAccountV3 calculates the transaction hash for a deploy +// account V3 transaction. // // Parameters: // - txn: The deploy account V3 transaction to calculate the hash for // - contractAddress: The contract address as parameters as a *felt.Felt -// - chainId: The chain ID as a *felt.Felt +// - chainID: The chain ID as a *felt.Felt // // Returns: // - *felt.Felt: the calculated transaction hash // - error: an error if any -func TransactionHashDeployAccountV3(txn *rpc.DeployAccountTxnV3, contractAddress, chainId *felt.Felt) (*felt.Felt, error) { +func TransactionHashDeployAccountV3( + txn *rpc.DeployAccountTxnV3, + contractAddress, chainID *felt.Felt, +) (*felt.Felt, error) { + //nolint:lll // The link would be unclickable if we break the line. // https://docs.starknet.io/architecture-and-concepts/network-architecture/transactions/#v3_hash_calculation_3 - if txn.Version == "" || txn.ResourceBounds == nil || txn.Nonce == nil || txn.PayMasterData == nil { + if txn.Version == "" || txn.ResourceBounds == nil || txn.Nonce == nil || + txn.PayMasterData == nil { return nil, ErrNotAllParametersSet } @@ -662,12 +740,12 @@ func TransactionHashDeployAccountV3(txn *rpc.DeployAccountTxnV3, contractAddress } return crypto.PoseidonArray( - PREFIX_DEPLOY_ACCOUNT, + prefixDeployAccount, txnVersionFelt, contractAddress, tipAndResourceHash, crypto.PoseidonArray(txn.PayMasterData...), - chainId, + chainID, txn.Nonce, new(felt.Felt).SetUint64(DAUint64), crypto.PoseidonArray(txn.ConstructorCalldata...), @@ -676,7 +754,10 @@ func TransactionHashDeployAccountV3(txn *rpc.DeployAccountTxnV3, contractAddress ), nil } -func TipAndResourcesHash(tip uint64, resourceBounds *rpc.ResourceBoundsMapping) (*felt.Felt, error) { +func TipAndResourcesHash( + tip uint64, + resourceBounds *rpc.ResourceBoundsMapping, +) (*felt.Felt, error) { if resourceBounds == nil { return nil, errors.New("resource bounds are nil") } @@ -696,7 +777,12 @@ func TipAndResourcesHash(tip uint64, resourceBounds *rpc.ResourceBoundsMapping) l2Bounds := new(felt.Felt).SetBytes(l2Bytes) l1DataGasBounds := new(felt.Felt).SetBytes(l1DataGasBytes) - return crypto.PoseidonArray(new(felt.Felt).SetUint64(tip), l1Bounds, l2Bounds, l1DataGasBounds), nil + return crypto.PoseidonArray( + new(felt.Felt).SetUint64(tip), + l1Bounds, + l2Bounds, + l1DataGasBounds, + ), nil } func DataAvailabilityModeConc(feeDAMode, nonceDAMode rpc.DataAvailabilityMode) (uint64, error) { diff --git a/internal/tests/jsonrpc_spy.go b/internal/tests/jsonrpc_spy.go index 4ea2fc4e5..3b91305b9 100644 --- a/internal/tests/jsonrpc_spy.go +++ b/internal/tests/jsonrpc_spy.go @@ -20,22 +20,32 @@ type Spy struct { // It's implemented by the `client.Client` type. type callCloser interface { CallContext(ctx context.Context, result interface{}, method string, args interface{}) error - CallContextWithSliceArgs(ctx context.Context, result interface{}, method string, args ...interface{}) error + CallContextWithSliceArgs( + ctx context.Context, + result interface{}, + method string, + args ...interface{}, + ) error Close() } // The Spyer interface implemented by the Spy type. type Spyer interface { CallContext(ctx context.Context, result interface{}, method string, args interface{}) error - CallContextWithSliceArgs(ctx context.Context, result interface{}, method string, args ...interface{}) error + CallContextWithSliceArgs( + ctx context.Context, + result interface{}, + method string, + args ...interface{}, + ) error Close() LastResponse() json.RawMessage } // Assert that the Spy type implements the callCloser and Spyer interfaces. var ( - _ callCloser = &Spy{} //nolint:exhaustruct - _ Spyer = &Spy{} //nolint:exhaustruct + _ callCloser = (*Spy)(nil) + _ Spyer = (*Spy)(nil) ) // NewJSONRPCSpy creates a new spy object. @@ -82,7 +92,12 @@ func NewJSONRPCSpy(client callCloser, debug ...bool) Spyer { // // Returns: // - error: an error if any occurred during the function call -func (s *Spy) CallContext(ctx context.Context, result interface{}, method string, arg interface{}) error { +func (s *Spy) CallContext( + ctx context.Context, + result interface{}, + method string, + arg interface{}, +) error { if s.mock { return s.callCloser.CallContext(ctx, result, method, arg) } @@ -121,7 +136,12 @@ func (s *Spy) CallContext(ctx context.Context, result interface{}, method string // // Returns: // - error: an error if any occurred during the function call -func (s *Spy) CallContextWithSliceArgs(ctx context.Context, result interface{}, method string, args ...interface{}) error { +func (s *Spy) CallContextWithSliceArgs( + ctx context.Context, + result interface{}, + method string, + args ...interface{}, +) error { if s.mock { return s.callCloser.CallContextWithSliceArgs(ctx, result, method, args...) } @@ -153,7 +173,8 @@ func (s *Spy) CallContextWithSliceArgs(ctx context.Context, result interface{}, } // LastResponse returns the last response captured by the spy. -// In other words, it returns the raw JSON response received from the server when calling a `callCloser` method. +// In other words, it returns the raw JSON response received from the server when +// calling a `callCloser` method. func (s *Spy) LastResponse() json.RawMessage { return s.buff } diff --git a/internal/tests/tests.go b/internal/tests/tests.go index e87bbfbbf..8686a1d5b 100644 --- a/internal/tests/tests.go +++ b/internal/tests/tests.go @@ -12,11 +12,12 @@ import ( ) // The environment for the test defined by the `-env` flag. If not set, default: mock -var TEST_ENV TestEnv +var TEST_ENV TestEnv //nolint:staticcheck //Only used in tests // An enum representing the environments for the test. type TestEnv string +//nolint:staticcheck // Only used in tests const ( MockEnv TestEnv = "mock" IntegrationEnv TestEnv = "integration" @@ -37,7 +38,8 @@ func loadEnvFlag() { // Loads the environment for the tests. It must be called before `m.Run` in the TestMain function // of each package. -// It looks for a `.env.` file in the `internal/tests` directory, where `` is the value of the `-env` flag. +// It looks for a `.env.` file in the `internal/tests` directory, where `` is +// the value of the `-env` flag. // If the file is not found, a warning is logged. func LoadEnv() { loadEnvFlag() @@ -46,7 +48,11 @@ func LoadEnv() { case MockEnv, IntegrationEnv, TestnetEnv, MainnetEnv, DevnetEnv, Devnet_TestnetEnv: break default: - log.Fatalf("invalid test environment '%s', supports: mock, integration, testnet, mainnet, devnet, devnet-testnet", TEST_ENV) + log.Fatalf( + `invalid test environment '%s', supports: mock, integration, testnet, + mainnet, devnet, devnet-testnet`, + TEST_ENV, + ) } // get the source file path @@ -71,8 +77,8 @@ func LoadEnv() { // If no environment is provided, the test fails. // If the environment is not in the list of environments, the test is skipped. // -// Packages like `account` and `rpc` are run on multiple environments, so -// in order to easily skip tests that are not supported on a specific environment, we use this helper. +// Packages like `account` and `rpc` are run on multiple environments, so in order to +// easily skip tests that are not supported on a specific environment, we use this helper. // If a test is not supported on a specific environment, it should be skipped; otherwise, it could // pass (since the environment is not being tested) and give a false positive. func RunTestOn(t *testing.T, envs ...TestEnv) { diff --git a/internal/utils/data.go b/internal/utils/data.go index 0260bf1f7..4e120f315 100644 --- a/internal/utils/data.go +++ b/internal/utils/data.go @@ -29,7 +29,8 @@ func UnwrapJSON(data map[string]any, tag string) (map[string]any, error) { return data, nil } -// GetAndUnmarshalJSONFromMap retrieves and unmarshals a JSON value from a map into the specified type T. +// GetAndUnmarshalJSONFromMap retrieves and unmarshals a JSON value from a map +// into the specified type T. // // Parameters: // - aMap: A map containing JSON raw messages @@ -38,7 +39,10 @@ func UnwrapJSON(data map[string]any, tag string) (map[string]any, error) { // Returns: // - T: The unmarshaled value of type T // - error: An error if the key is not found or unmarshaling fails -func GetAndUnmarshalJSONFromMap[T any](aMap map[string]json.RawMessage, key string) (result T, err error) { +func GetAndUnmarshalJSONFromMap[T any]( + aMap map[string]json.RawMessage, + key string, +) (result T, err error) { value, ok := aMap[key] if !ok { return result, fmt.Errorf("invalid json: missing field %s", key) @@ -52,7 +56,8 @@ func GetAndUnmarshalJSONFromMap[T any](aMap map[string]json.RawMessage, key stri return result, nil } -// UnmarshalJSONFileToType reads a JSON file at the given path and unmarshals it into the specified type T. +// UnmarshalJSONFileToType reads a JSON file at the given path and unmarshals it +// into the specified type T. // If any error occurs during file reading or unmarshalling, it returns an error. // // Parameters: diff --git a/internal/utils/felt.go b/internal/utils/felt.go index fc4b9ad27..7bc0cfbf5 100644 --- a/internal/utils/felt.go +++ b/internal/utils/felt.go @@ -36,11 +36,12 @@ func HexToFelt(hexVal string) (*felt.Felt, error) { // HexArrToFelt converts an array of hexadecimal strings to an array of felt objects. // -// The function iterates over each element in the hexArr array and calls the HexToFelt function to -// convert each hexadecimal value to a felt object. If any error occurs during the conversion, the -// function will return nil and the corresponding error. Otherwise, it appends the converted felt -// object to the feltArr array. Finally, the function returns the feltArr array containing all the -// converted felt objects. +// The function iterates over each element in the hexArr array and calls the HexToFelt +// function to convert each hexadecimal value to a felt object. +// If any error occurs during the conversion, the function will return nil and the +// corresponding error. +// Otherwise, it appends the converted felt object to the feltArr array. +// Finally, the function returns the feltArr array containing all the converted felt objects. // // Parameters: // - hexArr: an array of strings representing hexadecimal values @@ -120,26 +121,25 @@ func FeltArrToStringArr(f []*felt.Felt) []string { // StringToByteArrFelt converts string to array of Felt objects. // The returned array of felts will be of the format // -// [number of felts with 31 characters in length, 31 byte felts..., pending word with max size of 30 bytes, pending words bytes size] -// +// [number of felts with 31 characters in length, 31 byte felts..., pending word with +// max size of 30 bytes, pending words bytes size] // For further explanation, refer the [article] // // Parameters: -// // - s: string/bytearray to convert // // Returns: -// // - []*felt.Felt: the array of felt.Felt objects -// // - error: an error, if any // // [article]: https://docs.starknet.io/architecture-and-concepts/smart-contracts/serialization-of-cairo-types/#serialization_of_byte_arrays +// +//nolint:lll // The link would be unclickable if we break the line. func StringToByteArrFelt(s string) ([]*felt.Felt, error) { // TODO: make this helper return no error - const SHORT_LENGTH = 31 - exp := fmt.Sprintf(".{1,%d}", SHORT_LENGTH) + const shortLength = 31 + exp := fmt.Sprintf(".{1,%d}", shortLength) r := regexp.MustCompile(exp) arr := r.FindAllString(s, -1) @@ -151,7 +151,7 @@ func StringToByteArrFelt(s string) ([]*felt.Felt, error) { var count, size uint64 for _, val := range arr { - if len(val) == SHORT_LENGTH { + if len(val) == shortLength { count += 1 } else { size = uint64(len(val)) @@ -176,23 +176,22 @@ func StringToByteArrFelt(s string) ([]*felt.Felt, error) { // ByteArrFeltToString converts array of Felts to string. // The input array of felts will be of the format // -// [number of felts with 31 characters in length, 31 byte felts..., pending word with max size of 30 bytes, pending words bytes size] -// +// [number of felts with 31 characters in length, 31 byte felts..., pending word with +// max size of 30 bytes, pending words bytes size] // For further explanation, refer the [article] // // Parameters: -// // - []*felt.Felt: the array of felt.Felt objects // // Returns: -// // - s: string/bytearray -// // - error: an error, if any // // [article]: https://docs.starknet.io/architecture-and-concepts/smart-contracts/serialization-of-cairo-types/#serialization_of_byte_arrays +// +//nolint:lll // The link would be unclickable if we break the line. func ByteArrFeltToString(arr []*felt.Felt) (string, error) { - const SHORT_LENGTH = 31 + const shortLength = 31 if len(arr) < 3 { return "", errors.New("invalid felt array, require atleast 3 elements in array") @@ -202,12 +201,16 @@ func ByteArrFeltToString(arr []*felt.Felt) (string, error) { pendingWordLength := arr[len(arr)-1].Uint64() // pending word length is in the range [0, SHORT_LENGTH-1] - if pendingWordLength > SHORT_LENGTH-1 { + if pendingWordLength > shortLength-1 { return "", errors.New("invalid felt array, invalid pending word length") } if uint64(len(arr)) != 3+count { - return "", fmt.Errorf("invalid felt array, invalid length got %d expected %d", len(arr), 3+count) + return "", fmt.Errorf( + "invalid felt array, invalid length got %d expected %d", + len(arr), + 3+count, + ) } var res []string @@ -218,7 +221,7 @@ func ByteArrFeltToString(arr []*felt.Felt) (string, error) { } for index := range count { - res[index] = bytesFeltToString(arr[1+index], SHORT_LENGTH) + res[index] = bytesFeltToString(arr[1+index], shortLength) } if pendingWordLength != 0 { @@ -262,7 +265,7 @@ func BigIntArrToFeltArr(bigArr []*big.Int) []*felt.Felt { // - []*felt.Felt: a slice containing two felt.Felt values [low, high] // - error: if conversion fails // -//nolint:mnd +//nolint:mnd // There are comments explaining each magic number. func HexToU256Felt(hexStr string) ([]*felt.Felt, error) { // Ensure the hex string has the 0x prefix if !strings.HasPrefix(hexStr, "0x") && !strings.HasPrefix(hexStr, "0X") { @@ -271,7 +274,7 @@ func HexToU256Felt(hexStr string) ([]*felt.Felt, error) { // Parse the hex string to a big.Int value := new(big.Int) - value, success := value.SetString(hexStr[2:], 16) + value, success := value.SetString(hexStr[2:], 16) // hex base if !success { return nil, fmt.Errorf("failed to parse hex string: %s", hexStr) } @@ -296,7 +299,8 @@ func HexToU256Felt(hexStr string) ([]*felt.Felt, error) { return []*felt.Felt{lowFelt, highFelt}, nil } -// U256FeltToHex converts a Cairo u256 representation (two felt.Felt values) back to a hexadecimal string. +// U256FeltToHex converts a Cairo u256 representation (two felt.Felt values) +// back to a hexadecimal string. // The Cairo u256 is represented as two felt.Felt values: // - The first felt.Felt contains the 128 least significant bits (low part) // - The second felt.Felt contains the 128 most significant bits (high part) diff --git a/internal/utils/felt_test.go b/internal/utils/felt_test.go index 03d40e5c2..15b3c2e9c 100644 --- a/internal/utils/felt_test.go +++ b/internal/utils/felt_test.go @@ -20,12 +20,22 @@ func TestStringToByteArrFelt(t *testing.T) { out: []string{"0x0", "0x68656c6c6f", "0x5"}, }, { - in: "Long string, more than 31 characters.", - out: []string{"0x1", "0x4c6f6e6720737472696e672c206d6f7265207468616e203331206368617261", "0x63746572732e", "0x6"}, + in: "Long string, more than 31 characters.", + out: []string{ + "0x1", + "0x4c6f6e6720737472696e672c206d6f7265207468616e203331206368617261", + "0x63746572732e", + "0x6", + }, }, { - in: "Blockchain secure digital asset", - out: []string{"0x1", "0x426c6f636b636861696e20736563757265206469676974616c206173736574", "0x0", "0x0"}, + in: "Blockchain secure digital asset", + out: []string{ + "0x1", + "0x426c6f636b636861696e20736563757265206469676974616c206173736574", + "0x0", + "0x0", + }, }, { in: "Decentralised applications offer transparency and user control", @@ -42,12 +52,22 @@ func TestStringToByteArrFelt(t *testing.T) { out: []string{"0x0", "0x3132333435", "0x5"}, }, { - in: "1234567890123456789012345678901", - out: []string{"0x1", "0x31323334353637383930313233343536373839303132333435363738393031", "0x0", "0x0"}, + in: "1234567890123456789012345678901", + out: []string{ + "0x1", + "0x31323334353637383930313233343536373839303132333435363738393031", + "0x0", + "0x0", + }, }, { - in: "12345678901234567890123456789012", - out: []string{"0x1", "0x31323334353637383930313233343536373839303132333435363738393031", "0x32", "0x1"}, + in: "12345678901234567890123456789012", + out: []string{ + "0x1", + "0x31323334353637383930313233343536373839303132333435363738393031", + "0x32", + "0x1", + }, }, } @@ -72,11 +92,21 @@ func TestByteArrFeltToString(t *testing.T) { out: "hello", }, { - in: []string{"0x1", "0x4c6f6e6720737472696e672c206d6f7265207468616e203331206368617261", "0x63746572732e", "0x6"}, + in: []string{ + "0x1", + "0x4c6f6e6720737472696e672c206d6f7265207468616e203331206368617261", + "0x63746572732e", + "0x6", + }, out: "Long string, more than 31 characters.", }, { - in: []string{"0x1", "0x426c6f636b636861696e20736563757265206469676974616c206173736574", "0x0", "0x0"}, + in: []string{ + "0x1", + "0x426c6f636b636861696e20736563757265206469676974616c206173736574", + "0x0", + "0x0", + }, out: "Blockchain secure digital asset", }, { @@ -94,11 +124,21 @@ func TestByteArrFeltToString(t *testing.T) { out: "12345", }, { - in: []string{"0x1", "0x31323334353637383930313233343536373839303132333435363738393031", "0x0", "0x0"}, + in: []string{ + "0x1", + "0x31323334353637383930313233343536373839303132333435363738393031", + "0x0", + "0x0", + }, out: "1234567890123456789012345678901", }, { - in: []string{"0x1", "0x31323334353637383930313233343536373839303132333435363738393031", "0x32", "0x1"}, + in: []string{ + "0x1", + "0x31323334353637383930313233343536373839303132333435363738393031", + "0x32", + "0x1", + }, out: "12345678901234567890123456789012", }, { @@ -276,8 +316,18 @@ func TestU256FeltToHex(t *testing.T) { // Round-trip test: Convert back to u256 felt representation roundTrip, err := HexToU256Felt(result) require.NoError(t, err, "failed in round-trip conversion") - assert.Equal(t, lowFelt.String(), roundTrip[0].String(), "round-trip low bits do not match") - assert.Equal(t, highFelt.String(), roundTrip[1].String(), "round-trip high bits do not match") + assert.Equal( + t, + lowFelt.String(), + roundTrip[0].String(), + "round-trip low bits do not match", + ) + assert.Equal( + t, + highFelt.String(), + roundTrip[1].String(), + "round-trip high bits do not match", + ) }) } } diff --git a/internal/utils/keccak.go b/internal/utils/keccak.go index c0ae7759d..511cf761e 100644 --- a/internal/utils/keccak.go +++ b/internal/utils/keccak.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "hash" - "log" "math/big" "strings" @@ -157,21 +156,25 @@ func BigToHex(in *big.Int) string { } // GetSelectorFromName generates a selector from a given function name. +// Ref: https://www.starknet.io/cairo-book/ch101-01-00-contract-storage.html#addresses-of-storage-variables // // Parameters: // - funcName: the name of the function // // Returns: // - *big.Int: the selector +// +//nolint:lll // The link would be unclickable if we break the line. func GetSelectorFromName(funcName string) *big.Int { kec := Keccak256([]byte(funcName)) - maskedKec := MaskBits(250, 8, kec) //nolint:mnd + maskedKec := MaskBits(250, 8, kec) //nolint:mnd // Values taken from the starknet documentation. return new(big.Int).SetBytes(maskedKec) } -// GetSelectorFromNameFelt returns a *felt.Felt based on the given function name. +// GetSelectorFromNameFelt does the same as GetSelectorFromName, but returns +// the result as a *felt.Felt. // // Parameters: // - funcName: the name of the function @@ -181,7 +184,7 @@ func GetSelectorFromName(funcName string) *big.Int { func GetSelectorFromNameFelt(funcName string) *felt.Felt { kec := Keccak256([]byte(funcName)) - maskedKec := MaskBits(250, 8, kec) //nolint:mnd + maskedKec := MaskBits(250, 8, kec) //nolint:mnd // Values taken from the starknet documentation. return new(felt.Felt).SetBytes(maskedKec) } @@ -195,14 +198,17 @@ func GetSelectorFromNameFelt(funcName string) *felt.Felt { // Returns: // - []byte: a 32-byte hash output func Keccak256(data ...[]byte) []byte { - b := make([]byte, 32) //nolint:mnd + b := make([]byte, 32) //nolint:mnd // 32 bytes = 256 bits, necessary for keccak256 d := NewKeccakState() for _, b := range data { - d.Write(b) + _, err := d.Write(b) + if err != nil { + panic(err) + } } if _, err := d.Read(b); err != nil { - log.Fatal(err) + panic(err) } return b @@ -249,7 +255,8 @@ func MaskBits(mask, wordSize int, slice []byte) (ret []byte) { return ret } -// ComputeFact computes the factorial of a given number. +// ComputeFact computes a cryptographic hash from a program hash and its outputs. +// It combines the program hash with a hash of all program outputs using Keccak256. // // Parameters: // - programHash: a pointer to a big.Int representing the program hash @@ -258,31 +265,40 @@ func MaskBits(mask, wordSize int, slice []byte) (ret []byte) { // Returns: // - *big.Int: a pointer to a big.Int representing the computed factorial // -//nolint:mnd +//nolint:mnd // 32 bytes = 256 bits, necessary for keccak256 func ComputeFact(programHash *big.Int, programOutputs []*big.Int) *big.Int { var progOutBuf []byte for _, programOutput := range programOutputs { - inBuf := FmtKecBytes(programOutput, 32) + inBuf := FmtKecBytes( + programOutput, + 32, + ) progOutBuf = append(progOutBuf, inBuf...) } - kecBuf := FmtKecBytes(programHash, 32) + kecBuf := FmtKecBytes( + programHash, + 32, + ) kecBuf = append(kecBuf, Keccak256(progOutBuf)...) return new(big.Int).SetBytes(Keccak256(kecBuf)) } -// SplitFactStr splits a given fact, with maximum 256 bits size, into two parts (felts): fact_low and fact_high. +// SplitFactStr splits a given fact, with maximum 256 bits size, into two +// parts (felts): fact_low and fact_high. // -// The function takes a fact string as input and converts it to a big number using the HexToBN function. -// It then converts the big number to bytes using the Bytes method. -// If the length of the bytes is less than 32, it pads the bytes with zeros using the bytes.Repeat method. +// The function takes a fact string as input and converts it to a big number +// using the HexToBN function. It then converts the big number to bytes using +// the Bytes method. If the length of the bytes is less than 32, it pads the +// bytes with zeros using the bytes.Repeat method. // The padded bytes are then appended to the original bytes. -// The function then extracts the low part of the bytes by taking the last 16 bytes and converts it -// to a big number using the BytesToBig function. -// It also extracts the high part of the bytes by taking the first 16 bytes and converts it to a big number -// using the BytesToBig function. -// Finally, it converts the low and high big numbers to hexadecimal strings using the BigToHex function and returns them. +// The function then extracts the low part of the bytes by taking the last 16 +// bytes and converts it to a big number using the BytesToBig function. +// It also extracts the high part of the bytes by taking the first 16 bytes and +// converts it to a big number using the BytesToBig function. +// Finally, it converts the low and high big numbers to hexadecimal strings using +// the BigToHex function and returns them. // // Parameters: // - fact: The fact string to be split @@ -292,36 +308,38 @@ func ComputeFact(programHash *big.Int, programOutputs []*big.Int) *big.Int { // - fact_high: The high part of the fact string in hexadecimal format // - err: An error if any // -//nolint:mnd -func SplitFactStr(fact string) (fact_low, fact_high string, err error) { +//nolint:mnd // There's a comment explaining each magic number. +func SplitFactStr(fact string) (factLow, factHigh string, err error) { numStr := strings.ReplaceAll(fact, "0x", "") - factBN, ok := new(big.Int).SetString(numStr, 16) + factBN, ok := new(big.Int).SetString(numStr, 16) // hex base if !ok { return "", "", errors.New("failed to convert fact string to big.Int") } - if factBN.BitLen() > 256 { + if factBN.BitLen() > 256 { // max 256 bits return "", "", errors.New("fact string is too large") } factBytes := factBN.Bytes() - lpadfactBytes := bytes.Repeat([]byte{0x00}, 32-len(factBytes)) + lpadfactBytes := bytes.Repeat([]byte{0x00}, 32-len(factBytes)) // left pad with zeros factBytes = append(lpadfactBytes, factBytes...) - low := BytesToBig(factBytes[16:]) - high := BytesToBig(factBytes[:16]) + high := BytesToBig(factBytes[:16]) // first 16 bytes + low := BytesToBig(factBytes[16:]) // last 16 bytes return BigToHex(low), BigToHex(high), nil } -// FmtKecBytes formats the given big.Int as a byte slice (Keccak hash) with a specified length. +// FmtKecBytes formats the given big.Int as a byte slice (Keccak hash) with +// a specified length. // // The function appends the bytes of the big.Int to a buffer and returns it. -// If the length of the buffer is less than the specified length, the function pads the buffer with zeros. +// If the length of the buffer is less than the specified length, the function +// pads the buffer with zeros. // // Parameters: // - in: the big.Int to be formatted // - rolen: the length of the buffer // // Returns: -// buf: the formatted buffer +// - buf: the formatted buffer func FmtKecBytes(in *big.Int, rolen int) (buf []byte) { buf = append(buf, in.Bytes()...) diff --git a/internal/utils/keccak_test.go b/internal/utils/keccak_test.go index 439855d21..bb86d79e0 100644 --- a/internal/utils/keccak_test.go +++ b/internal/utils/keccak_test.go @@ -56,14 +56,22 @@ func TestComputeFact(t *testing.T) { expected *big.Int }{ { - programHash: HexToBN("0x114952172aed91e59f870a314e75de0a437ff550e4618068cec2d832e48b0c7"), + programHash: HexToBN( + "0x114952172aed91e59f870a314e75de0a437ff550e4618068cec2d832e48b0c7", + ), programOutput: []*big.Int{big.NewInt(289)}, - expected: HexToBN("0xe6168c0a865aa80d724ad05627fa65fbcfe4b1d66a586e9f348f461b076072c4"), + expected: HexToBN( + "0xe6168c0a865aa80d724ad05627fa65fbcfe4b1d66a586e9f348f461b076072c4", + ), }, { - programHash: HexToBN("0x79920d895101ad1fbdea9adf141d8f362fdea9ee35f33dfcd07f38e4a589bab"), + programHash: HexToBN( + "0x79920d895101ad1fbdea9adf141d8f362fdea9ee35f33dfcd07f38e4a589bab", + ), programOutput: []*big.Int{ - StrToBig("2754806153357301156380357983574496185342034785016738734224771556919270737441"), + StrToBig( + "2754806153357301156380357983574496185342034785016738734224771556919270737441", + ), }, expected: HexToBN("0x1d174fa1443deea9aab54bbca8d9be308dd14a0323dd827556c173bd132098db"), }, diff --git a/internal/utils/slices.go b/internal/utils/slices.go index b226a803f..6cf9dd0f4 100644 --- a/internal/utils/slices.go +++ b/internal/utils/slices.go @@ -26,7 +26,8 @@ func Map[T1, T2 any](slice []T1, f func(T1) T2) []T2 { return result } -// Filter filters a slice of type T using the given predicate, returning a new slice with the elements that match the predicate +// Filter filters a slice of type T using the given predicate, returning a new slice with +// the elements that match the predicate func Filter[T any](slice []T, f func(T) bool) []T { if slice == nil { return nil diff --git a/internal/utils/slices_test.go b/internal/utils/slices_test.go index 6bcde8004..89f4c74d6 100644 --- a/internal/utils/slices_test.go +++ b/internal/utils/slices_test.go @@ -89,7 +89,7 @@ func TestMap(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { t.Parallel() - result := Map(tc.input, func(i int) string { return strconv.Itoa(i) }) //nolint:gocritic + result := Map(tc.input, strconv.Itoa) assert.ElementsMatch(t, result, tc.expected) }) } diff --git a/internal/utils/test.go b/internal/utils/test.go index be8f45dc7..f42901e78 100644 --- a/internal/utils/test.go +++ b/internal/utils/test.go @@ -8,7 +8,7 @@ import ( ) // Just a random felt variable to use when needed. The value is "0xdeadbeef" -var RANDOM_FELT = new(felt.Felt).SetUint64(3735928559) //nolint:mnd +var DeadBeef = new(felt.Felt).SetUint64(3735928559) //nolint:mnd // 0xdeadbeef // TestHexToFelt generates a felt.Felt from a hexadecimal string. // @@ -26,7 +26,8 @@ func TestHexToFelt(t testing.TB, hex string) *felt.Felt { return f } -// TestHexArrToFelt generates a slice of *felt.Felt from a slice of strings representing hexadecimal values. +// TestHexArrToFelt generates a slice of *felt.Felt from a slice of strings +// representing hexadecimal values. // // Parameters: // - t: A testing.TB interface used for test logging and error reporting @@ -42,7 +43,8 @@ func TestHexArrToFelt(t testing.TB, hexArr []string) []*felt.Felt { return feltArr } -// TestUnmarshalJSONFileToType reads a JSON file at the given path and unmarshals it into the specified type T. +// TestUnmarshalJSONFileToType reads a JSON file at the given path and unmarshals it +// into the specified type T. // If any error occurs during file reading or unmarshalling, it fails the test. // // Parameters: diff --git a/internal/utils/transactions_test.go b/internal/utils/transactions_test.go index 773d27034..5c0955801 100644 --- a/internal/utils/transactions_test.go +++ b/internal/utils/transactions_test.go @@ -30,8 +30,11 @@ func TestWeiToETH(t *testing.T) { expected: 0.001, }, { - name: "Large amount", - wei: new(big.Int).Mul(big.NewInt(1000), new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)), // 1000 ETH + name: "Large amount", + wei: new( + big.Int, + ).Mul(big.NewInt(1000), new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)), + // 1000 ETH expected: 1000.0, }, } @@ -72,16 +75,25 @@ func TestETHToWei(t *testing.T) { expected: big.NewInt(1000000000000000), // 0.001 ETH }, { - name: "Large amount", - eth: 1000.0, - expected: new(big.Int).Mul(big.NewInt(1000), new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)), // 1000 ETH + name: "Large amount", + eth: 1000.0, + expected: new( + big.Int, + ).Mul(big.NewInt(1000), new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)), + // 1000 ETH }, { name: "Fractional amount", eth: 1.5, expected: new(big.Int).Add( - new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil), // 1 ETH - new(big.Int).Div(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil), big.NewInt(2))), // 0.5 ETH + new( + big.Int, + ).Exp(big.NewInt(10), big.NewInt(18), nil), // 1 ETH + new( + big.Int, + ).Div(new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil), big.NewInt(2)), + ), + // 0.5 ETH }, } diff --git a/merkle/merkle.go b/merkle/merkle.go index 0068128a8..aa6c5942d 100644 --- a/merkle/merkle.go +++ b/merkle/merkle.go @@ -15,8 +15,9 @@ type FixedSizeMerkleTree struct { // NewFixedSizeMerkleTree creates a new fixed-size Merkle tree. // -// It takes a variable number of *big.Int leaves as input and returns a pointer to a FixedSizeMerkleTree and an error. -// The function builds the Merkle tree using the given leaves and sets the tree's root. +// It takes a variable number of *big.Int leaves as input and returns a +// pointer to a FixedSizeMerkleTree and an error. The function builds the +// Merkle tree using the given leaves and sets the tree's root. // // Parameters: // - leaves: a slice of *big.Int representing the leaves of the tree. @@ -24,10 +25,10 @@ type FixedSizeMerkleTree struct { // Returns: // - *FixedSizeMerkleTree: a pointer to a FixedSizeMerkleTree func NewFixedSizeMerkleTree(leaves ...*big.Int) *FixedSizeMerkleTree { - //nolint:exhaustruct mt := &FixedSizeMerkleTree{ Leaves: leaves, Branches: [][]*big.Int{}, + Root: nil, } mt.Root = mt.build(leaves) @@ -98,8 +99,13 @@ func (mt *FixedSizeMerkleTree) Proof(leaf *big.Int) ([]*big.Int, error) { // // Returns: // - []*big.Int: the Merkle proof for the given leaf -// - error: if the key is not found in the branch or there is an error in the nextproof calculation. -func (mt *FixedSizeMerkleTree) recursiveProof(leaf *big.Int, branchIndex int, hashPath []*big.Int) ([]*big.Int, error) { +// - error: if the key is not found in the branch or there is an error in +// the next proof calculation. +func (mt *FixedSizeMerkleTree) recursiveProof( + leaf *big.Int, + branchIndex int, + hashPath []*big.Int, +) ([]*big.Int, error) { if branchIndex >= len(mt.Branches) { return hashPath, nil } @@ -113,7 +119,10 @@ func (mt *FixedSizeMerkleTree) recursiveProof(leaf *big.Int, branchIndex int, ha } } if index == -1 { - return nil, fmt.Errorf("key 0x%s not found in branch", leaf.Text(16)) //nolint:mnd //hex base + return nil, fmt.Errorf( + "key 0x%s not found in branch", + leaf.Text(16), //nolint:mnd // hex base + ) } nextProof := big.NewInt(0) if index%2 == 0 && index+1 < len(branch) { @@ -123,9 +132,9 @@ func (mt *FixedSizeMerkleTree) recursiveProof(leaf *big.Int, branchIndex int, ha nextProof = branch[index-1] } newLeaf := MerkleHash(leaf, nextProof) - newHashPath := append(hashPath, nextProof) //nolint:gocritic + hashPath = append(hashPath, nextProof) - return mt.recursiveProof(newLeaf, branchIndex+1, newHashPath) + return mt.recursiveProof(newLeaf, branchIndex+1, hashPath) } // ProofMerklePath checks if a given leaf node is part of a Merkle tree path. diff --git a/merkle/merkle_test.go b/merkle/merkle_test.go index 7f8fddc16..7de3ca7ac 100644 --- a/merkle/merkle_test.go +++ b/merkle/merkle_test.go @@ -31,8 +31,18 @@ func debugProof(t *testing.T, proofs []*big.Int) { // Returns: // // none +// +//nolint:staticcheck // Best readability func TestGeneral_FixedSizeMerkleTree_Check1(t *testing.T) { - leaves := []*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3), big.NewInt(4), big.NewInt(5), big.NewInt(6), big.NewInt(7)} + leaves := []*big.Int{ + big.NewInt(1), + big.NewInt(2), + big.NewInt(3), + big.NewInt(4), + big.NewInt(5), + big.NewInt(6), + big.NewInt(7), + } merkleTree := NewFixedSizeMerkleTree(leaves...) proof_7_0 := MerkleHash(big.NewInt(7), big.NewInt(0)) proof_1_2 := MerkleHash(big.NewInt(1), big.NewInt(2)) diff --git a/mocks/mock_rpc_provider.go b/mocks/mock_rpc_provider.go index ba2458f37..b62e670e3 100644 --- a/mocks/mock_rpc_provider.go +++ b/mocks/mock_rpc_provider.go @@ -20,32 +20,32 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockRpcProvider is a mock of RpcProvider interface. -type MockRpcProvider struct { +// MockRPCProvider is a mock of RPCProvider interface. +type MockRPCProvider struct { ctrl *gomock.Controller - recorder *MockRpcProviderMockRecorder + recorder *MockRPCProviderMockRecorder isgomock struct{} } -// MockRpcProviderMockRecorder is the mock recorder for MockRpcProvider. -type MockRpcProviderMockRecorder struct { - mock *MockRpcProvider +// MockRPCProviderMockRecorder is the mock recorder for MockRPCProvider. +type MockRPCProviderMockRecorder struct { + mock *MockRPCProvider } -// NewMockRpcProvider creates a new mock instance. -func NewMockRpcProvider(ctrl *gomock.Controller) *MockRpcProvider { - mock := &MockRpcProvider{ctrl: ctrl} - mock.recorder = &MockRpcProviderMockRecorder{mock} +// NewMockRPCProvider creates a new mock instance. +func NewMockRPCProvider(ctrl *gomock.Controller) *MockRPCProvider { + mock := &MockRPCProvider{ctrl: ctrl} + mock.recorder = &MockRPCProviderMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockRpcProvider) EXPECT() *MockRpcProviderMockRecorder { +func (m *MockRPCProvider) EXPECT() *MockRPCProviderMockRecorder { return m.recorder } // AddDeclareTransaction mocks base method. -func (m *MockRpcProvider) AddDeclareTransaction(ctx context.Context, declareTransaction *rpc.BroadcastDeclareTxnV3) (rpc.AddDeclareTransactionResponse, error) { +func (m *MockRPCProvider) AddDeclareTransaction(ctx context.Context, declareTransaction *rpc.BroadcastDeclareTxnV3) (rpc.AddDeclareTransactionResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddDeclareTransaction", ctx, declareTransaction) ret0, _ := ret[0].(rpc.AddDeclareTransactionResponse) @@ -54,13 +54,13 @@ func (m *MockRpcProvider) AddDeclareTransaction(ctx context.Context, declareTran } // AddDeclareTransaction indicates an expected call of AddDeclareTransaction. -func (mr *MockRpcProviderMockRecorder) AddDeclareTransaction(ctx, declareTransaction any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) AddDeclareTransaction(ctx, declareTransaction any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddDeclareTransaction", reflect.TypeOf((*MockRpcProvider)(nil).AddDeclareTransaction), ctx, declareTransaction) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddDeclareTransaction", reflect.TypeOf((*MockRPCProvider)(nil).AddDeclareTransaction), ctx, declareTransaction) } // AddDeployAccountTransaction mocks base method. -func (m *MockRpcProvider) AddDeployAccountTransaction(ctx context.Context, deployAccountTransaction *rpc.BroadcastDeployAccountTxnV3) (rpc.AddDeployAccountTransactionResponse, error) { +func (m *MockRPCProvider) AddDeployAccountTransaction(ctx context.Context, deployAccountTransaction *rpc.BroadcastDeployAccountTxnV3) (rpc.AddDeployAccountTransactionResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddDeployAccountTransaction", ctx, deployAccountTransaction) ret0, _ := ret[0].(rpc.AddDeployAccountTransactionResponse) @@ -69,13 +69,13 @@ func (m *MockRpcProvider) AddDeployAccountTransaction(ctx context.Context, deplo } // AddDeployAccountTransaction indicates an expected call of AddDeployAccountTransaction. -func (mr *MockRpcProviderMockRecorder) AddDeployAccountTransaction(ctx, deployAccountTransaction any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) AddDeployAccountTransaction(ctx, deployAccountTransaction any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddDeployAccountTransaction", reflect.TypeOf((*MockRpcProvider)(nil).AddDeployAccountTransaction), ctx, deployAccountTransaction) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddDeployAccountTransaction", reflect.TypeOf((*MockRPCProvider)(nil).AddDeployAccountTransaction), ctx, deployAccountTransaction) } // AddInvokeTransaction mocks base method. -func (m *MockRpcProvider) AddInvokeTransaction(ctx context.Context, invokeTxn *rpc.BroadcastInvokeTxnV3) (rpc.AddInvokeTransactionResponse, error) { +func (m *MockRPCProvider) AddInvokeTransaction(ctx context.Context, invokeTxn *rpc.BroadcastInvokeTxnV3) (rpc.AddInvokeTransactionResponse, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddInvokeTransaction", ctx, invokeTxn) ret0, _ := ret[0].(rpc.AddInvokeTransactionResponse) @@ -84,13 +84,13 @@ func (m *MockRpcProvider) AddInvokeTransaction(ctx context.Context, invokeTxn *r } // AddInvokeTransaction indicates an expected call of AddInvokeTransaction. -func (mr *MockRpcProviderMockRecorder) AddInvokeTransaction(ctx, invokeTxn any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) AddInvokeTransaction(ctx, invokeTxn any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddInvokeTransaction", reflect.TypeOf((*MockRpcProvider)(nil).AddInvokeTransaction), ctx, invokeTxn) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddInvokeTransaction", reflect.TypeOf((*MockRPCProvider)(nil).AddInvokeTransaction), ctx, invokeTxn) } // BlockHashAndNumber mocks base method. -func (m *MockRpcProvider) BlockHashAndNumber(ctx context.Context) (*rpc.BlockHashAndNumberOutput, error) { +func (m *MockRPCProvider) BlockHashAndNumber(ctx context.Context) (*rpc.BlockHashAndNumberOutput, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BlockHashAndNumber", ctx) ret0, _ := ret[0].(*rpc.BlockHashAndNumberOutput) @@ -99,13 +99,13 @@ func (m *MockRpcProvider) BlockHashAndNumber(ctx context.Context) (*rpc.BlockHas } // BlockHashAndNumber indicates an expected call of BlockHashAndNumber. -func (mr *MockRpcProviderMockRecorder) BlockHashAndNumber(ctx any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) BlockHashAndNumber(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockHashAndNumber", reflect.TypeOf((*MockRpcProvider)(nil).BlockHashAndNumber), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockHashAndNumber", reflect.TypeOf((*MockRPCProvider)(nil).BlockHashAndNumber), ctx) } // BlockNumber mocks base method. -func (m *MockRpcProvider) BlockNumber(ctx context.Context) (uint64, error) { +func (m *MockRPCProvider) BlockNumber(ctx context.Context) (uint64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BlockNumber", ctx) ret0, _ := ret[0].(uint64) @@ -114,13 +114,13 @@ func (m *MockRpcProvider) BlockNumber(ctx context.Context) (uint64, error) { } // BlockNumber indicates an expected call of BlockNumber. -func (mr *MockRpcProviderMockRecorder) BlockNumber(ctx any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) BlockNumber(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockNumber", reflect.TypeOf((*MockRpcProvider)(nil).BlockNumber), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockNumber", reflect.TypeOf((*MockRPCProvider)(nil).BlockNumber), ctx) } // BlockTransactionCount mocks base method. -func (m *MockRpcProvider) BlockTransactionCount(ctx context.Context, blockID rpc.BlockID) (uint64, error) { +func (m *MockRPCProvider) BlockTransactionCount(ctx context.Context, blockID rpc.BlockID) (uint64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BlockTransactionCount", ctx, blockID) ret0, _ := ret[0].(uint64) @@ -129,13 +129,13 @@ func (m *MockRpcProvider) BlockTransactionCount(ctx context.Context, blockID rpc } // BlockTransactionCount indicates an expected call of BlockTransactionCount. -func (mr *MockRpcProviderMockRecorder) BlockTransactionCount(ctx, blockID any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) BlockTransactionCount(ctx, blockID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockTransactionCount", reflect.TypeOf((*MockRpcProvider)(nil).BlockTransactionCount), ctx, blockID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockTransactionCount", reflect.TypeOf((*MockRPCProvider)(nil).BlockTransactionCount), ctx, blockID) } // BlockWithReceipts mocks base method. -func (m *MockRpcProvider) BlockWithReceipts(ctx context.Context, blockID rpc.BlockID) (any, error) { +func (m *MockRPCProvider) BlockWithReceipts(ctx context.Context, blockID rpc.BlockID) (any, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BlockWithReceipts", ctx, blockID) ret0, _ := ret[0].(any) @@ -144,13 +144,13 @@ func (m *MockRpcProvider) BlockWithReceipts(ctx context.Context, blockID rpc.Blo } // BlockWithReceipts indicates an expected call of BlockWithReceipts. -func (mr *MockRpcProviderMockRecorder) BlockWithReceipts(ctx, blockID any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) BlockWithReceipts(ctx, blockID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockWithReceipts", reflect.TypeOf((*MockRpcProvider)(nil).BlockWithReceipts), ctx, blockID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockWithReceipts", reflect.TypeOf((*MockRPCProvider)(nil).BlockWithReceipts), ctx, blockID) } // BlockWithTxHashes mocks base method. -func (m *MockRpcProvider) BlockWithTxHashes(ctx context.Context, blockID rpc.BlockID) (any, error) { +func (m *MockRPCProvider) BlockWithTxHashes(ctx context.Context, blockID rpc.BlockID) (any, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BlockWithTxHashes", ctx, blockID) ret0, _ := ret[0].(any) @@ -159,13 +159,13 @@ func (m *MockRpcProvider) BlockWithTxHashes(ctx context.Context, blockID rpc.Blo } // BlockWithTxHashes indicates an expected call of BlockWithTxHashes. -func (mr *MockRpcProviderMockRecorder) BlockWithTxHashes(ctx, blockID any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) BlockWithTxHashes(ctx, blockID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockWithTxHashes", reflect.TypeOf((*MockRpcProvider)(nil).BlockWithTxHashes), ctx, blockID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockWithTxHashes", reflect.TypeOf((*MockRPCProvider)(nil).BlockWithTxHashes), ctx, blockID) } // BlockWithTxs mocks base method. -func (m *MockRpcProvider) BlockWithTxs(ctx context.Context, blockID rpc.BlockID) (any, error) { +func (m *MockRPCProvider) BlockWithTxs(ctx context.Context, blockID rpc.BlockID) (any, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BlockWithTxs", ctx, blockID) ret0, _ := ret[0].(any) @@ -174,13 +174,13 @@ func (m *MockRpcProvider) BlockWithTxs(ctx context.Context, blockID rpc.BlockID) } // BlockWithTxs indicates an expected call of BlockWithTxs. -func (mr *MockRpcProviderMockRecorder) BlockWithTxs(ctx, blockID any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) BlockWithTxs(ctx, blockID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockWithTxs", reflect.TypeOf((*MockRpcProvider)(nil).BlockWithTxs), ctx, blockID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BlockWithTxs", reflect.TypeOf((*MockRPCProvider)(nil).BlockWithTxs), ctx, blockID) } // Call mocks base method. -func (m *MockRpcProvider) Call(ctx context.Context, call rpc.FunctionCall, block rpc.BlockID) ([]*felt.Felt, error) { +func (m *MockRPCProvider) Call(ctx context.Context, call rpc.FunctionCall, block rpc.BlockID) ([]*felt.Felt, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Call", ctx, call, block) ret0, _ := ret[0].([]*felt.Felt) @@ -189,13 +189,13 @@ func (m *MockRpcProvider) Call(ctx context.Context, call rpc.FunctionCall, block } // Call indicates an expected call of Call. -func (mr *MockRpcProviderMockRecorder) Call(ctx, call, block any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) Call(ctx, call, block any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Call", reflect.TypeOf((*MockRpcProvider)(nil).Call), ctx, call, block) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Call", reflect.TypeOf((*MockRPCProvider)(nil).Call), ctx, call, block) } // ChainID mocks base method. -func (m *MockRpcProvider) ChainID(ctx context.Context) (string, error) { +func (m *MockRPCProvider) ChainID(ctx context.Context) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ChainID", ctx) ret0, _ := ret[0].(string) @@ -204,13 +204,13 @@ func (m *MockRpcProvider) ChainID(ctx context.Context) (string, error) { } // ChainID indicates an expected call of ChainID. -func (mr *MockRpcProviderMockRecorder) ChainID(ctx any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) ChainID(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ChainID", reflect.TypeOf((*MockRpcProvider)(nil).ChainID), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ChainID", reflect.TypeOf((*MockRPCProvider)(nil).ChainID), ctx) } // Class mocks base method. -func (m *MockRpcProvider) Class(ctx context.Context, blockID rpc.BlockID, classHash *felt.Felt) (rpc.ClassOutput, error) { +func (m *MockRPCProvider) Class(ctx context.Context, blockID rpc.BlockID, classHash *felt.Felt) (rpc.ClassOutput, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Class", ctx, blockID, classHash) ret0, _ := ret[0].(rpc.ClassOutput) @@ -219,13 +219,13 @@ func (m *MockRpcProvider) Class(ctx context.Context, blockID rpc.BlockID, classH } // Class indicates an expected call of Class. -func (mr *MockRpcProviderMockRecorder) Class(ctx, blockID, classHash any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) Class(ctx, blockID, classHash any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Class", reflect.TypeOf((*MockRpcProvider)(nil).Class), ctx, blockID, classHash) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Class", reflect.TypeOf((*MockRPCProvider)(nil).Class), ctx, blockID, classHash) } // ClassAt mocks base method. -func (m *MockRpcProvider) ClassAt(ctx context.Context, blockID rpc.BlockID, contractAddress *felt.Felt) (rpc.ClassOutput, error) { +func (m *MockRPCProvider) ClassAt(ctx context.Context, blockID rpc.BlockID, contractAddress *felt.Felt) (rpc.ClassOutput, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ClassAt", ctx, blockID, contractAddress) ret0, _ := ret[0].(rpc.ClassOutput) @@ -234,13 +234,13 @@ func (m *MockRpcProvider) ClassAt(ctx context.Context, blockID rpc.BlockID, cont } // ClassAt indicates an expected call of ClassAt. -func (mr *MockRpcProviderMockRecorder) ClassAt(ctx, blockID, contractAddress any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) ClassAt(ctx, blockID, contractAddress any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClassAt", reflect.TypeOf((*MockRpcProvider)(nil).ClassAt), ctx, blockID, contractAddress) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClassAt", reflect.TypeOf((*MockRPCProvider)(nil).ClassAt), ctx, blockID, contractAddress) } // ClassHashAt mocks base method. -func (m *MockRpcProvider) ClassHashAt(ctx context.Context, blockID rpc.BlockID, contractAddress *felt.Felt) (*felt.Felt, error) { +func (m *MockRPCProvider) ClassHashAt(ctx context.Context, blockID rpc.BlockID, contractAddress *felt.Felt) (*felt.Felt, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ClassHashAt", ctx, blockID, contractAddress) ret0, _ := ret[0].(*felt.Felt) @@ -249,13 +249,13 @@ func (m *MockRpcProvider) ClassHashAt(ctx context.Context, blockID rpc.BlockID, } // ClassHashAt indicates an expected call of ClassHashAt. -func (mr *MockRpcProviderMockRecorder) ClassHashAt(ctx, blockID, contractAddress any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) ClassHashAt(ctx, blockID, contractAddress any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClassHashAt", reflect.TypeOf((*MockRpcProvider)(nil).ClassHashAt), ctx, blockID, contractAddress) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClassHashAt", reflect.TypeOf((*MockRPCProvider)(nil).ClassHashAt), ctx, blockID, contractAddress) } // CompiledCasm mocks base method. -func (m *MockRpcProvider) CompiledCasm(ctx context.Context, classHash *felt.Felt) (*contracts.CasmClass, error) { +func (m *MockRPCProvider) CompiledCasm(ctx context.Context, classHash *felt.Felt) (*contracts.CasmClass, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CompiledCasm", ctx, classHash) ret0, _ := ret[0].(*contracts.CasmClass) @@ -264,13 +264,13 @@ func (m *MockRpcProvider) CompiledCasm(ctx context.Context, classHash *felt.Felt } // CompiledCasm indicates an expected call of CompiledCasm. -func (mr *MockRpcProviderMockRecorder) CompiledCasm(ctx, classHash any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) CompiledCasm(ctx, classHash any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CompiledCasm", reflect.TypeOf((*MockRpcProvider)(nil).CompiledCasm), ctx, classHash) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CompiledCasm", reflect.TypeOf((*MockRPCProvider)(nil).CompiledCasm), ctx, classHash) } // EstimateFee mocks base method. -func (m *MockRpcProvider) EstimateFee(ctx context.Context, requests []rpc.BroadcastTxn, simulationFlags []rpc.SimulationFlag, blockID rpc.BlockID) ([]rpc.FeeEstimation, error) { +func (m *MockRPCProvider) EstimateFee(ctx context.Context, requests []rpc.BroadcastTxn, simulationFlags []rpc.SimulationFlag, blockID rpc.BlockID) ([]rpc.FeeEstimation, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "EstimateFee", ctx, requests, simulationFlags, blockID) ret0, _ := ret[0].([]rpc.FeeEstimation) @@ -279,13 +279,13 @@ func (m *MockRpcProvider) EstimateFee(ctx context.Context, requests []rpc.Broadc } // EstimateFee indicates an expected call of EstimateFee. -func (mr *MockRpcProviderMockRecorder) EstimateFee(ctx, requests, simulationFlags, blockID any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) EstimateFee(ctx, requests, simulationFlags, blockID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EstimateFee", reflect.TypeOf((*MockRpcProvider)(nil).EstimateFee), ctx, requests, simulationFlags, blockID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EstimateFee", reflect.TypeOf((*MockRPCProvider)(nil).EstimateFee), ctx, requests, simulationFlags, blockID) } // EstimateMessageFee mocks base method. -func (m *MockRpcProvider) EstimateMessageFee(ctx context.Context, msg rpc.MsgFromL1, blockID rpc.BlockID) (rpc.MessageFeeEstimation, error) { +func (m *MockRPCProvider) EstimateMessageFee(ctx context.Context, msg rpc.MsgFromL1, blockID rpc.BlockID) (rpc.MessageFeeEstimation, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "EstimateMessageFee", ctx, msg, blockID) ret0, _ := ret[0].(rpc.MessageFeeEstimation) @@ -294,13 +294,13 @@ func (m *MockRpcProvider) EstimateMessageFee(ctx context.Context, msg rpc.MsgFro } // EstimateMessageFee indicates an expected call of EstimateMessageFee. -func (mr *MockRpcProviderMockRecorder) EstimateMessageFee(ctx, msg, blockID any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) EstimateMessageFee(ctx, msg, blockID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EstimateMessageFee", reflect.TypeOf((*MockRpcProvider)(nil).EstimateMessageFee), ctx, msg, blockID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EstimateMessageFee", reflect.TypeOf((*MockRPCProvider)(nil).EstimateMessageFee), ctx, msg, blockID) } // Events mocks base method. -func (m *MockRpcProvider) Events(ctx context.Context, input rpc.EventsInput) (*rpc.EventChunk, error) { +func (m *MockRPCProvider) Events(ctx context.Context, input rpc.EventsInput) (*rpc.EventChunk, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Events", ctx, input) ret0, _ := ret[0].(*rpc.EventChunk) @@ -309,58 +309,28 @@ func (m *MockRpcProvider) Events(ctx context.Context, input rpc.EventsInput) (*r } // Events indicates an expected call of Events. -func (mr *MockRpcProviderMockRecorder) Events(ctx, input any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) Events(ctx, input any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Events", reflect.TypeOf((*MockRpcProvider)(nil).Events), ctx, input) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Events", reflect.TypeOf((*MockRPCProvider)(nil).Events), ctx, input) } -// GetMessagesStatus mocks base method. -func (m *MockRpcProvider) GetMessagesStatus(ctx context.Context, transactionHash rpc.NumAsHex) ([]rpc.MessageStatus, error) { +// MessagesStatus mocks base method. +func (m *MockRPCProvider) MessagesStatus(ctx context.Context, transactionHash rpc.NumAsHex) ([]rpc.MessageStatus, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMessagesStatus", ctx, transactionHash) + ret := m.ctrl.Call(m, "MessagesStatus", ctx, transactionHash) ret0, _ := ret[0].([]rpc.MessageStatus) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetMessagesStatus indicates an expected call of GetMessagesStatus. -func (mr *MockRpcProviderMockRecorder) GetMessagesStatus(ctx, transactionHash any) *gomock.Call { +// MessagesStatus indicates an expected call of MessagesStatus. +func (mr *MockRPCProviderMockRecorder) MessagesStatus(ctx, transactionHash any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMessagesStatus", reflect.TypeOf((*MockRpcProvider)(nil).GetMessagesStatus), ctx, transactionHash) -} - -// GetStorageProof mocks base method. -func (m *MockRpcProvider) GetStorageProof(ctx context.Context, storageProofInput rpc.StorageProofInput) (*rpc.StorageProofResult, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStorageProof", ctx, storageProofInput) - ret0, _ := ret[0].(*rpc.StorageProofResult) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetStorageProof indicates an expected call of GetStorageProof. -func (mr *MockRpcProviderMockRecorder) GetStorageProof(ctx, storageProofInput any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStorageProof", reflect.TypeOf((*MockRpcProvider)(nil).GetStorageProof), ctx, storageProofInput) -} - -// GetTransactionStatus mocks base method. -func (m *MockRpcProvider) GetTransactionStatus(ctx context.Context, transactionHash *felt.Felt) (*rpc.TxnStatusResult, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTransactionStatus", ctx, transactionHash) - ret0, _ := ret[0].(*rpc.TxnStatusResult) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetTransactionStatus indicates an expected call of GetTransactionStatus. -func (mr *MockRpcProviderMockRecorder) GetTransactionStatus(ctx, transactionHash any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTransactionStatus", reflect.TypeOf((*MockRpcProvider)(nil).GetTransactionStatus), ctx, transactionHash) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MessagesStatus", reflect.TypeOf((*MockRPCProvider)(nil).MessagesStatus), ctx, transactionHash) } // Nonce mocks base method. -func (m *MockRpcProvider) Nonce(ctx context.Context, blockID rpc.BlockID, contractAddress *felt.Felt) (*felt.Felt, error) { +func (m *MockRPCProvider) Nonce(ctx context.Context, blockID rpc.BlockID, contractAddress *felt.Felt) (*felt.Felt, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Nonce", ctx, blockID, contractAddress) ret0, _ := ret[0].(*felt.Felt) @@ -369,13 +339,13 @@ func (m *MockRpcProvider) Nonce(ctx context.Context, blockID rpc.BlockID, contra } // Nonce indicates an expected call of Nonce. -func (mr *MockRpcProviderMockRecorder) Nonce(ctx, blockID, contractAddress any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) Nonce(ctx, blockID, contractAddress any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nonce", reflect.TypeOf((*MockRpcProvider)(nil).Nonce), ctx, blockID, contractAddress) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Nonce", reflect.TypeOf((*MockRPCProvider)(nil).Nonce), ctx, blockID, contractAddress) } // SimulateTransactions mocks base method. -func (m *MockRpcProvider) SimulateTransactions(ctx context.Context, blockID rpc.BlockID, txns []rpc.BroadcastTxn, simulationFlags []rpc.SimulationFlag) ([]rpc.SimulatedTransaction, error) { +func (m *MockRPCProvider) SimulateTransactions(ctx context.Context, blockID rpc.BlockID, txns []rpc.BroadcastTxn, simulationFlags []rpc.SimulationFlag) ([]rpc.SimulatedTransaction, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SimulateTransactions", ctx, blockID, txns, simulationFlags) ret0, _ := ret[0].([]rpc.SimulatedTransaction) @@ -384,13 +354,13 @@ func (m *MockRpcProvider) SimulateTransactions(ctx context.Context, blockID rpc. } // SimulateTransactions indicates an expected call of SimulateTransactions. -func (mr *MockRpcProviderMockRecorder) SimulateTransactions(ctx, blockID, txns, simulationFlags any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) SimulateTransactions(ctx, blockID, txns, simulationFlags any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SimulateTransactions", reflect.TypeOf((*MockRpcProvider)(nil).SimulateTransactions), ctx, blockID, txns, simulationFlags) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SimulateTransactions", reflect.TypeOf((*MockRPCProvider)(nil).SimulateTransactions), ctx, blockID, txns, simulationFlags) } // SpecVersion mocks base method. -func (m *MockRpcProvider) SpecVersion(ctx context.Context) (string, error) { +func (m *MockRPCProvider) SpecVersion(ctx context.Context) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SpecVersion", ctx) ret0, _ := ret[0].(string) @@ -399,13 +369,13 @@ func (m *MockRpcProvider) SpecVersion(ctx context.Context) (string, error) { } // SpecVersion indicates an expected call of SpecVersion. -func (mr *MockRpcProviderMockRecorder) SpecVersion(ctx any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) SpecVersion(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SpecVersion", reflect.TypeOf((*MockRpcProvider)(nil).SpecVersion), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SpecVersion", reflect.TypeOf((*MockRPCProvider)(nil).SpecVersion), ctx) } // StateUpdate mocks base method. -func (m *MockRpcProvider) StateUpdate(ctx context.Context, blockID rpc.BlockID) (*rpc.StateUpdateOutput, error) { +func (m *MockRPCProvider) StateUpdate(ctx context.Context, blockID rpc.BlockID) (*rpc.StateUpdateOutput, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "StateUpdate", ctx, blockID) ret0, _ := ret[0].(*rpc.StateUpdateOutput) @@ -414,13 +384,13 @@ func (m *MockRpcProvider) StateUpdate(ctx context.Context, blockID rpc.BlockID) } // StateUpdate indicates an expected call of StateUpdate. -func (mr *MockRpcProviderMockRecorder) StateUpdate(ctx, blockID any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) StateUpdate(ctx, blockID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StateUpdate", reflect.TypeOf((*MockRpcProvider)(nil).StateUpdate), ctx, blockID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StateUpdate", reflect.TypeOf((*MockRPCProvider)(nil).StateUpdate), ctx, blockID) } // StorageAt mocks base method. -func (m *MockRpcProvider) StorageAt(ctx context.Context, contractAddress *felt.Felt, key string, blockID rpc.BlockID) (string, error) { +func (m *MockRPCProvider) StorageAt(ctx context.Context, contractAddress *felt.Felt, key string, blockID rpc.BlockID) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "StorageAt", ctx, contractAddress, key, blockID) ret0, _ := ret[0].(string) @@ -429,13 +399,28 @@ func (m *MockRpcProvider) StorageAt(ctx context.Context, contractAddress *felt.F } // StorageAt indicates an expected call of StorageAt. -func (mr *MockRpcProviderMockRecorder) StorageAt(ctx, contractAddress, key, blockID any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) StorageAt(ctx, contractAddress, key, blockID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StorageAt", reflect.TypeOf((*MockRpcProvider)(nil).StorageAt), ctx, contractAddress, key, blockID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StorageAt", reflect.TypeOf((*MockRPCProvider)(nil).StorageAt), ctx, contractAddress, key, blockID) +} + +// StorageProof mocks base method. +func (m *MockRPCProvider) StorageProof(ctx context.Context, storageProofInput rpc.StorageProofInput) (*rpc.StorageProofResult, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "StorageProof", ctx, storageProofInput) + ret0, _ := ret[0].(*rpc.StorageProofResult) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// StorageProof indicates an expected call of StorageProof. +func (mr *MockRPCProviderMockRecorder) StorageProof(ctx, storageProofInput any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StorageProof", reflect.TypeOf((*MockRPCProvider)(nil).StorageProof), ctx, storageProofInput) } // Syncing mocks base method. -func (m *MockRpcProvider) Syncing(ctx context.Context) (rpc.SyncStatus, error) { +func (m *MockRPCProvider) Syncing(ctx context.Context) (rpc.SyncStatus, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Syncing", ctx) ret0, _ := ret[0].(rpc.SyncStatus) @@ -444,13 +429,13 @@ func (m *MockRpcProvider) Syncing(ctx context.Context) (rpc.SyncStatus, error) { } // Syncing indicates an expected call of Syncing. -func (mr *MockRpcProviderMockRecorder) Syncing(ctx any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) Syncing(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Syncing", reflect.TypeOf((*MockRpcProvider)(nil).Syncing), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Syncing", reflect.TypeOf((*MockRPCProvider)(nil).Syncing), ctx) } // TraceBlockTransactions mocks base method. -func (m *MockRpcProvider) TraceBlockTransactions(ctx context.Context, blockID rpc.BlockID) ([]rpc.Trace, error) { +func (m *MockRPCProvider) TraceBlockTransactions(ctx context.Context, blockID rpc.BlockID) ([]rpc.Trace, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TraceBlockTransactions", ctx, blockID) ret0, _ := ret[0].([]rpc.Trace) @@ -459,13 +444,13 @@ func (m *MockRpcProvider) TraceBlockTransactions(ctx context.Context, blockID rp } // TraceBlockTransactions indicates an expected call of TraceBlockTransactions. -func (mr *MockRpcProviderMockRecorder) TraceBlockTransactions(ctx, blockID any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) TraceBlockTransactions(ctx, blockID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TraceBlockTransactions", reflect.TypeOf((*MockRpcProvider)(nil).TraceBlockTransactions), ctx, blockID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TraceBlockTransactions", reflect.TypeOf((*MockRPCProvider)(nil).TraceBlockTransactions), ctx, blockID) } // TraceTransaction mocks base method. -func (m *MockRpcProvider) TraceTransaction(ctx context.Context, transactionHash *felt.Felt) (rpc.TxnTrace, error) { +func (m *MockRPCProvider) TraceTransaction(ctx context.Context, transactionHash *felt.Felt) (rpc.TxnTrace, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TraceTransaction", ctx, transactionHash) ret0, _ := ret[0].(rpc.TxnTrace) @@ -474,28 +459,28 @@ func (m *MockRpcProvider) TraceTransaction(ctx context.Context, transactionHash } // TraceTransaction indicates an expected call of TraceTransaction. -func (mr *MockRpcProviderMockRecorder) TraceTransaction(ctx, transactionHash any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) TraceTransaction(ctx, transactionHash any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TraceTransaction", reflect.TypeOf((*MockRpcProvider)(nil).TraceTransaction), ctx, transactionHash) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TraceTransaction", reflect.TypeOf((*MockRPCProvider)(nil).TraceTransaction), ctx, transactionHash) } -// TransactionByBlockIdAndIndex mocks base method. -func (m *MockRpcProvider) TransactionByBlockIdAndIndex(ctx context.Context, blockID rpc.BlockID, index uint64) (*rpc.BlockTransaction, error) { +// TransactionByBlockIDAndIndex mocks base method. +func (m *MockRPCProvider) TransactionByBlockIDAndIndex(ctx context.Context, blockID rpc.BlockID, index uint64) (*rpc.BlockTransaction, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TransactionByBlockIdAndIndex", ctx, blockID, index) + ret := m.ctrl.Call(m, "TransactionByBlockIDAndIndex", ctx, blockID, index) ret0, _ := ret[0].(*rpc.BlockTransaction) ret1, _ := ret[1].(error) return ret0, ret1 } -// TransactionByBlockIdAndIndex indicates an expected call of TransactionByBlockIdAndIndex. -func (mr *MockRpcProviderMockRecorder) TransactionByBlockIdAndIndex(ctx, blockID, index any) *gomock.Call { +// TransactionByBlockIDAndIndex indicates an expected call of TransactionByBlockIDAndIndex. +func (mr *MockRPCProviderMockRecorder) TransactionByBlockIDAndIndex(ctx, blockID, index any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TransactionByBlockIdAndIndex", reflect.TypeOf((*MockRpcProvider)(nil).TransactionByBlockIdAndIndex), ctx, blockID, index) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TransactionByBlockIDAndIndex", reflect.TypeOf((*MockRPCProvider)(nil).TransactionByBlockIDAndIndex), ctx, blockID, index) } // TransactionByHash mocks base method. -func (m *MockRpcProvider) TransactionByHash(ctx context.Context, hash *felt.Felt) (*rpc.BlockTransaction, error) { +func (m *MockRPCProvider) TransactionByHash(ctx context.Context, hash *felt.Felt) (*rpc.BlockTransaction, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TransactionByHash", ctx, hash) ret0, _ := ret[0].(*rpc.BlockTransaction) @@ -504,13 +489,13 @@ func (m *MockRpcProvider) TransactionByHash(ctx context.Context, hash *felt.Felt } // TransactionByHash indicates an expected call of TransactionByHash. -func (mr *MockRpcProviderMockRecorder) TransactionByHash(ctx, hash any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) TransactionByHash(ctx, hash any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TransactionByHash", reflect.TypeOf((*MockRpcProvider)(nil).TransactionByHash), ctx, hash) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TransactionByHash", reflect.TypeOf((*MockRPCProvider)(nil).TransactionByHash), ctx, hash) } // TransactionReceipt mocks base method. -func (m *MockRpcProvider) TransactionReceipt(ctx context.Context, transactionHash *felt.Felt) (*rpc.TransactionReceiptWithBlockInfo, error) { +func (m *MockRPCProvider) TransactionReceipt(ctx context.Context, transactionHash *felt.Felt) (*rpc.TransactionReceiptWithBlockInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TransactionReceipt", ctx, transactionHash) ret0, _ := ret[0].(*rpc.TransactionReceiptWithBlockInfo) @@ -519,9 +504,24 @@ func (m *MockRpcProvider) TransactionReceipt(ctx context.Context, transactionHas } // TransactionReceipt indicates an expected call of TransactionReceipt. -func (mr *MockRpcProviderMockRecorder) TransactionReceipt(ctx, transactionHash any) *gomock.Call { +func (mr *MockRPCProviderMockRecorder) TransactionReceipt(ctx, transactionHash any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TransactionReceipt", reflect.TypeOf((*MockRPCProvider)(nil).TransactionReceipt), ctx, transactionHash) +} + +// TransactionStatus mocks base method. +func (m *MockRPCProvider) TransactionStatus(ctx context.Context, transactionHash *felt.Felt) (*rpc.TxnStatusResult, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "TransactionStatus", ctx, transactionHash) + ret0, _ := ret[0].(*rpc.TxnStatusResult) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// TransactionStatus indicates an expected call of TransactionStatus. +func (mr *MockRPCProviderMockRecorder) TransactionStatus(ctx, transactionHash any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TransactionReceipt", reflect.TypeOf((*MockRpcProvider)(nil).TransactionReceipt), ctx, transactionHash) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TransactionStatus", reflect.TypeOf((*MockRPCProvider)(nil).TransactionStatus), ctx, transactionHash) } // MockWebsocketProvider is a mock of WebsocketProvider interface. diff --git a/rpc/block.go b/rpc/block.go index aa0bc203a..379f3e67b 100644 --- a/rpc/block.go +++ b/rpc/block.go @@ -38,7 +38,9 @@ func (provider *Provider) BlockNumber(ctx context.Context) (uint64, error) { // Returns: // - *BlockHashAndNumberOutput: The hash and number of the current block // - error: An error if any -func (provider *Provider) BlockHashAndNumber(ctx context.Context) (*BlockHashAndNumberOutput, error) { +func (provider *Provider) BlockHashAndNumber( + ctx context.Context, +) (*BlockHashAndNumberOutput, error) { var block BlockHashAndNumberOutput if err := do(ctx, provider.c, "starknet_blockHashAndNumber", &block); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrNoBlocks) @@ -55,10 +57,10 @@ func (provider *Provider) BlockHashAndNumber(ctx context.Context) (*BlockHashAnd // Returns: // - BlockID: A BlockID struct with the specified block number func WithBlockNumber(n uint64) BlockID { - //nolint:exhaustruct - return BlockID{ - Number: &n, - } + var blockID BlockID + blockID.Number = &n + + return blockID } // WithBlockHash returns a BlockID with the given hash. @@ -69,10 +71,10 @@ func WithBlockNumber(n uint64) BlockID { // Returns: // - BlockID: A BlockID struct with the specified hash func WithBlockHash(h *felt.Felt) BlockID { - //nolint:exhaustruct - return BlockID{ - Hash: h, - } + var blockID BlockID + blockID.Hash = h + + return blockID } // WithBlockTag creates a new BlockID with the specified tag. @@ -83,10 +85,10 @@ func WithBlockHash(h *felt.Felt) BlockID { // Returns: // - BlockID: A BlockID struct with the specified tag func WithBlockTag(tag BlockTag) BlockID { - //nolint:exhaustruct - return BlockID{ - Tag: tag, - } + var blockID BlockID + blockID.Tag = tag + + return blockID } // BlockWithTxHashes retrieves the block with transaction hashes for the given block ID. @@ -99,8 +101,11 @@ func WithBlockTag(tag BlockTag) BlockID { // - interface{}: The retrieved block // - error: An error, if any // -//nolint:dupl -func (provider *Provider) BlockWithTxHashes(ctx context.Context, blockID BlockID) (interface{}, error) { +//nolint:dupl // Similar to BlockWithTxs, but it's a different method. +func (provider *Provider) BlockWithTxHashes( + ctx context.Context, + blockID BlockID, +) (interface{}, error) { var result BlockTxHashes if err := do(ctx, provider.c, "starknet_getBlockWithTxHashes", &result, blockID); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrBlockNotFound) @@ -108,8 +113,8 @@ func (provider *Provider) BlockWithTxHashes(ctx context.Context, blockID BlockID // if header.Hash == nil it's a pre_confirmed block if result.Hash == nil { - return &Pre_confirmedBlockTxHashes{ - Pre_confirmedBlockHeader{ + return &PreConfirmedBlockTxHashes{ + PreConfirmedBlockHeader{ Number: result.Number, Timestamp: result.Timestamp, SequencerAddress: result.SequencerAddress, @@ -136,7 +141,10 @@ func (provider *Provider) BlockWithTxHashes(ctx context.Context, blockID BlockID // Returns: // - *StateUpdateOutput: The retrieved state update // - error: An error, if any -func (provider *Provider) StateUpdate(ctx context.Context, blockID BlockID) (*StateUpdateOutput, error) { +func (provider *Provider) StateUpdate( + ctx context.Context, + blockID BlockID, +) (*StateUpdateOutput, error) { var state StateUpdateOutput if err := do(ctx, provider.c, "starknet_getStateUpdate", &state, blockID); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrBlockNotFound) @@ -154,7 +162,10 @@ func (provider *Provider) StateUpdate(ctx context.Context, blockID BlockID) (*St // Returns: // - uint64: The number of transactions in the block // - error: An error, if any -func (provider *Provider) BlockTransactionCount(ctx context.Context, blockID BlockID) (uint64, error) { +func (provider *Provider) BlockTransactionCount( + ctx context.Context, + blockID BlockID, +) (uint64, error) { var result uint64 if err := do(ctx, provider.c, "starknet_getBlockTransactionCount", &result, blockID); err != nil { return 0, rpcerr.UnwrapToRPCErr(err, ErrBlockNotFound) @@ -173,7 +184,7 @@ func (provider *Provider) BlockTransactionCount(ctx context.Context, blockID Blo // - interface{}: The retrieved block // - error: An error, if any // -//nolint:dupl +//nolint:dupl // Similar to BlockWithTxHashes, but it's a different method. func (provider *Provider) BlockWithTxs(ctx context.Context, blockID BlockID) (interface{}, error) { var result Block if err := do(ctx, provider.c, "starknet_getBlockWithTxs", &result, blockID); err != nil { @@ -181,8 +192,8 @@ func (provider *Provider) BlockWithTxs(ctx context.Context, blockID BlockID) (in } // if header.Hash == nil it's a pre_confirmed block if result.Hash == nil { - return &Pre_confirmedBlock{ - Pre_confirmedBlockHeader{ + return &PreConfirmedBlock{ + PreConfirmedBlockHeader{ Number: result.Number, Timestamp: result.Timestamp, SequencerAddress: result.SequencerAddress, @@ -200,7 +211,10 @@ func (provider *Provider) BlockWithTxs(ctx context.Context, blockID BlockID) (in } // Get block information with full transactions and receipts given the block id -func (provider *Provider) BlockWithReceipts(ctx context.Context, blockID BlockID) (interface{}, error) { +func (provider *Provider) BlockWithReceipts( + ctx context.Context, + blockID BlockID, +) (interface{}, error) { var result json.RawMessage if err := do(ctx, provider.c, "starknet_getBlockWithReceipts", &result, blockID); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrBlockNotFound) @@ -220,11 +234,11 @@ func (provider *Provider) BlockWithReceipts(ctx context.Context, blockID BlockID return &block, nil } else { - var pre_confirmedBlock Pre_confirmedBlockWithReceipts - if err := json.Unmarshal(result, &pre_confirmedBlock); err != nil { + var preConfirmedBlock PreConfirmedBlockWithReceipts + if err := json.Unmarshal(result, &preConfirmedBlock); err != nil { return nil, rpcerr.Err(rpcerr.InternalError, StringErrData(err.Error())) } - return &pre_confirmedBlock, nil + return &preConfirmedBlock, nil } } diff --git a/rpc/block_test.go b/rpc/block_test.go index 48e2f7dd1..dbcad022e 100644 --- a/rpc/block_test.go +++ b/rpc/block_test.go @@ -48,10 +48,18 @@ func TestBlockHashAndNumber(t *testing.T) { blockHashAndNumber, err := testConfig.Provider.BlockHashAndNumber(context.Background()) require.NoError(t, err, "BlockHashAndNumber should not return an error") - require.True(t, strings.HasPrefix(blockHashAndNumber.Hash.String(), "0x"), "current block hash should return a string starting with 0x") + require.True( + t, + strings.HasPrefix(blockHashAndNumber.Hash.String(), "0x"), + "current block hash should return a string starting with 0x", + ) if tests.TEST_ENV == tests.MockEnv { - require.Equal(t, &BlockHashAndNumberOutput{Number: 1234, Hash: internalUtils.RANDOM_FELT}, blockHashAndNumber) + require.Equal( + t, + &BlockHashAndNumberOutput{Number: 1234, Hash: internalUtils.DeadBeef}, + blockHashAndNumber, + ) } } @@ -89,10 +97,10 @@ func TestBlockWithTxHashes(t *testing.T) { testConfig := BeforeEach(t, false) type testSetType struct { - BlockID BlockID - ExpectedErr error - ExpectedBlockWithTxHashes *BlockTxHashes - ExpectedPre_confirmedBlockWithTxHashes *Pre_confirmedBlockTxHashes + BlockID BlockID + ExpectedErr error + ExpectedBlockWithTxHashes *BlockTxHashes + ExpectedPreConfirmedBlockWithTxHashes *PreConfirmedBlockTxHashes } blockSepolia64159 := *internalUtils.TestUnmarshalJSONFileToType[BlockTxHashes](t, "./testData/blockWithHashes/sepoliaBlockWithHashes64159.json", "result") @@ -104,31 +112,31 @@ func TestBlockWithTxHashes(t *testing.T) { }) blockMock := BlockTxHashes{ BlockHeader: BlockHeader{ - Hash: internalUtils.RANDOM_FELT, - ParentHash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, + ParentHash: internalUtils.DeadBeef, Timestamp: 124, - SequencerAddress: internalUtils.RANDOM_FELT, + SequencerAddress: internalUtils.DeadBeef, }, - Status: BlockStatus_AcceptedOnL1, + Status: BlockStatusAcceptedOnL1, Transactions: txHashesMock, } testSet := map[tests.TestEnv][]testSetType{ tests.MockEnv: { { - BlockID: BlockID{Tag: BlockTagPre_confirmed}, + BlockID: BlockID{Tag: BlockTagPreConfirmed}, ExpectedErr: nil, - ExpectedPre_confirmedBlockWithTxHashes: &Pre_confirmedBlockTxHashes{ - Pre_confirmedBlockHeader{ + ExpectedPreConfirmedBlockWithTxHashes: &PreConfirmedBlockTxHashes{ + PreConfirmedBlockHeader{ Number: 1234, Timestamp: 123, - SequencerAddress: internalUtils.RANDOM_FELT, + SequencerAddress: internalUtils.DeadBeef, }, txHashesMock, }, }, { - BlockID: BlockID{Hash: internalUtils.RANDOM_FELT}, + BlockID: BlockID{Hash: internalUtils.DeadBeef}, ExpectedBlockWithTxHashes: &blockMock, }, { @@ -142,7 +150,7 @@ func TestBlockWithTxHashes(t *testing.T) { ExpectedErr: nil, }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), ExpectedErr: nil, }, { @@ -166,7 +174,7 @@ func TestBlockWithTxHashes(t *testing.T) { ExpectedErr: nil, }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), ExpectedErr: nil, }, { @@ -205,14 +213,14 @@ func TestBlockWithTxHashes(t *testing.T) { if test.ExpectedBlockWithTxHashes != nil { assert.Exactly(t, test.ExpectedBlockWithTxHashes, block) } - case *Pre_confirmedBlockTxHashes: - pBlock, ok := result.(*Pre_confirmedBlockTxHashes) + case *PreConfirmedBlockTxHashes: + pBlock, ok := result.(*PreConfirmedBlockTxHashes) require.Truef(t, ok, "should return *Pre_confirmedBlockTxHashes, instead: %T\n", result) - if test.ExpectedPre_confirmedBlockWithTxHashes == nil { - validatePre_confirmedBlockHeader(t, &pBlock.Pre_confirmedBlockHeader) + if test.ExpectedPreConfirmedBlockWithTxHashes == nil { + validatePreConfirmedBlockHeader(t, &pBlock.PreConfirmedBlockHeader) } else { - assert.Exactly(t, test.ExpectedPre_confirmedBlockWithTxHashes, pBlock) + assert.Exactly(t, test.ExpectedPreConfirmedBlockWithTxHashes, pBlock) } default: t.Fatalf("unexpected block type, found: %T\n", resultType) @@ -240,20 +248,20 @@ func TestBlockWithTxs(t *testing.T) { testConfig := BeforeEach(t, false) type testSetType struct { - BlockID BlockID - ExpectedBlock *Block - ExpectedPre_confirmedBlock *Pre_confirmedBlock - InvokeV0Index int // TODO: implement mainnet testcases as Sepolia doesn't contains V0 transactions - InvokeV1Index int - InvokeV3Index int - DeclareV0Index int // TODO: implement mainnet testcases as Sepolia doesn't contains V0 transactions - DeclareV1Index int - DeclareV2Index int - DeclareV3Index int // TODO: implement testcase - DeployAccountV1Index int - DeployAccountV3Index int // TODO: implement testcase - L1HandlerV0Index int - DeployV0Index int // TODO: implement testcase + BlockID BlockID + ExpectedBlock *Block + ExpectedPreConfirmedBlock *PreConfirmedBlock + InvokeV0Index int // TODO: implement mainnet testcases as Sepolia doesn't contains V0 transactions + InvokeV1Index int + InvokeV3Index int + DeclareV0Index int // TODO: implement mainnet testcases as Sepolia doesn't contains V0 transactions + DeclareV1Index int + DeclareV2Index int + DeclareV3Index int // TODO: implement testcase + DeployAccountV1Index int + DeployAccountV3Index int // TODO: implement testcase + L1HandlerV0Index int + DeployV0Index int // TODO: implement testcase } fullBlockSepolia65083 := *internalUtils.TestUnmarshalJSONFileToType[Block](t, "./testData/block/sepoliaBlockTxs65083.json", "result") @@ -266,26 +274,26 @@ func TestBlockWithTxs(t *testing.T) { BlockID: WithBlockTag(BlockTagLatest), }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), }, { BlockID: WithBlockTag(BlockTagL1Accepted), - ExpectedPre_confirmedBlock: &Pre_confirmedBlock{ - Pre_confirmedBlockHeader{ + ExpectedPreConfirmedBlock: &PreConfirmedBlock{ + PreConfirmedBlockHeader{ Number: 1234, Timestamp: 1234, - SequencerAddress: internalUtils.RANDOM_FELT, + SequencerAddress: internalUtils.DeadBeef, L1GasPrice: ResourcePrice{ - PriceInFRI: internalUtils.RANDOM_FELT, - PriceInWei: internalUtils.RANDOM_FELT, + PriceInFRI: internalUtils.DeadBeef, + PriceInWei: internalUtils.DeadBeef, }, L2GasPrice: ResourcePrice{ - PriceInFRI: internalUtils.RANDOM_FELT, - PriceInWei: internalUtils.RANDOM_FELT, + PriceInFRI: internalUtils.DeadBeef, + PriceInWei: internalUtils.DeadBeef, }, L1DataGasPrice: ResourcePrice{ - PriceInFRI: internalUtils.RANDOM_FELT, - PriceInWei: internalUtils.RANDOM_FELT, + PriceInFRI: internalUtils.DeadBeef, + PriceInWei: internalUtils.DeadBeef, }, L1DAMode: L1DAModeBlob, StarknetVersion: "0.14.0", @@ -309,7 +317,7 @@ func TestBlockWithTxs(t *testing.T) { BlockID: WithBlockTag(BlockTagLatest), }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), }, { BlockID: WithBlockTag(BlockTagL1Accepted), @@ -334,7 +342,7 @@ func TestBlockWithTxs(t *testing.T) { BlockID: WithBlockTag(BlockTagLatest), }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), }, { BlockID: WithBlockTag(BlockTagL1Accepted), @@ -351,15 +359,18 @@ func TestBlockWithTxs(t *testing.T) { for _, test := range testSet { blockID, _ := test.BlockID.MarshalJSON() t.Run(fmt.Sprintf("BlockID: %v", string(blockID)), func(t *testing.T) { - blockWithTxsInterface, err := testConfig.Provider.BlockWithTxs(context.Background(), test.BlockID) + blockWithTxsInterface, err := testConfig.Provider.BlockWithTxs( + context.Background(), + test.BlockID, + ) require.NoError(t, err, "Unable to fetch the given block.") switch block := blockWithTxsInterface.(type) { - case *Pre_confirmedBlock: - if test.ExpectedPre_confirmedBlock == nil { - validatePre_confirmedBlockHeader(t, &block.Pre_confirmedBlockHeader) + case *PreConfirmedBlock: + if test.ExpectedPreConfirmedBlock == nil { + validatePreConfirmedBlockHeader(t, &block.PreConfirmedBlockHeader) } else { - assert.Exactly(t, test.ExpectedPre_confirmedBlock, block) + assert.Exactly(t, test.ExpectedPreConfirmedBlock, block) } case *Block: if test.ExpectedBlock == nil { @@ -454,7 +465,7 @@ func TestBlockTransactionCount(t *testing.T) { ExpectedCount: 10, }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), ExpectedCount: 10, }, { @@ -472,7 +483,7 @@ func TestBlockTransactionCount(t *testing.T) { ExpectedCount: 58, }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), ExpectedCount: -1, }, { @@ -504,22 +515,28 @@ func TestBlockTransactionCount(t *testing.T) { }, }[tests.TEST_ENV] for _, test := range testSet { - t.Run(fmt.Sprintf("Count: %v, BlockID: %v", test.ExpectedCount, test.BlockID), func(t *testing.T) { - count, err := testConfig.Provider.BlockTransactionCount(context.Background(), test.BlockID) - if test.ExpectedError != nil { - require.EqualError(t, test.ExpectedError, err.Error()) + t.Run( + fmt.Sprintf("Count: %v, BlockID: %v", test.ExpectedCount, test.BlockID), + func(t *testing.T) { + count, err := testConfig.Provider.BlockTransactionCount( + context.Background(), + test.BlockID, + ) + if test.ExpectedError != nil { + require.EqualError(t, test.ExpectedError, err.Error()) - return - } - require.NoError(t, err) + return + } + require.NoError(t, err) - if test.ExpectedCount == -1 { - // since 0 is the default value of an int64 var, let's set the expected count to -1 when we want to skip the count check - return - } + if test.ExpectedCount == -1 { + // since 0 is the default value of an int64 var, let's set the expected count to -1 when we want to skip the count check + return + } - assert.Equal(t, uint64(test.ExpectedCount), count) - }) + assert.Equal(t, uint64(test.ExpectedCount), count) + }, + ) } } @@ -550,7 +567,10 @@ func TestCaptureUnsupportedBlockTxn(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { for i := test.StartBlock; i < test.EndBlock; i++ { - blockWithTxsInterface, err := testConfig.Provider.BlockWithTxs(context.Background(), WithBlockNumber(i)) + blockWithTxsInterface, err := testConfig.Provider.BlockWithTxs( + context.Background(), + WithBlockNumber(i), + ) require.NoError(t, err) blockWithTxs, ok := blockWithTxsInterface.(*Block) require.True(t, ok, "expecting *rpc.Block, instead %T", blockWithTxsInterface) @@ -566,7 +586,9 @@ func TestCaptureUnsupportedBlockTxn(t *testing.T) { _, okdec3 := v.Transaction.(DeclareTxnV3) _, okdep := v.Transaction.(DeployTxn) _, okdepac := v.Transaction.(DeployAccountTxnV1) - if !okv0 && !okv1 && !okv3 && !okl1 && !okdec0 && !okdec1 && !okdec2 && !okdec3 && !okdep && !okdepac { + if !okv0 && !okv1 && !okv3 && !okl1 && !okdec0 && !okdec1 && !okdec2 && !okdec3 && + !okdep && + !okdepac { t.Fatalf("New Type Detected %T at Block(%d)/Txn(%d)", v, i, k) } } @@ -597,7 +619,7 @@ func TestStateUpdate(t *testing.T) { BlockID: WithBlockTag(BlockTagLatest), }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), }, { BlockID: WithBlockTag(BlockTagL1Accepted), @@ -616,7 +638,7 @@ func TestStateUpdate(t *testing.T) { BlockID: WithBlockTag(BlockTagLatest), }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), }, { BlockID: WithBlockTag(BlockTagL1Accepted), @@ -708,13 +730,21 @@ func assertStateUpdateJSONEquality(t *testing.T, subfield string, expectedResult // other state diff fields assert.ElementsMatch(t, expectedResultMap["nonces"], resultMap["nonces"]) - assert.ElementsMatch(t, expectedResultMap["deployed_contracts"], resultMap["deployed_contracts"]) - assert.ElementsMatch(t, expectedResultMap["deprecated_declared_classes"], resultMap["deprecated_declared_classes"]) + assert.ElementsMatch( + t, + expectedResultMap["deployed_contracts"], + resultMap["deployed_contracts"], + ) + assert.ElementsMatch( + t, + expectedResultMap["deprecated_declared_classes"], + resultMap["deprecated_declared_classes"], + ) assert.ElementsMatch(t, expectedResultMap["declared_classes"], resultMap["declared_classes"]) assert.ElementsMatch(t, expectedResultMap["replaced_classes"], resultMap["replaced_classes"]) } -func validatePre_confirmedBlockHeader(t *testing.T, pBlock *Pre_confirmedBlockHeader) { +func validatePreConfirmedBlockHeader(t *testing.T, pBlock *PreConfirmedBlockHeader) { assert.NotZero(t, pBlock.Number) assert.NotZero(t, pBlock.Timestamp) assert.NotZero(t, pBlock.SequencerAddress) diff --git a/rpc/call.go b/rpc/call.go index e190062a0..3f0b13752 100644 --- a/rpc/call.go +++ b/rpc/call.go @@ -17,14 +17,24 @@ import ( // Returns // - []*felt.Felt: the result of the function call // - error: an error if any occurred during the execution -func (provider *Provider) Call(ctx context.Context, request FunctionCall, blockID BlockID) ([]*felt.Felt, error) { +func (provider *Provider) Call( + ctx context.Context, + request FunctionCall, + blockID BlockID, +) ([]*felt.Felt, error) { if request.Calldata == nil { request.Calldata = []*felt.Felt{} } var result []*felt.Felt if err := do(ctx, provider.c, "starknet_call", &result, request, blockID); err != nil { - return nil, rpcerr.UnwrapToRPCErr(err, ErrContractNotFound, ErrEntrypointNotFound, ErrContractError, ErrBlockNotFound) + return nil, rpcerr.UnwrapToRPCErr( + err, + ErrContractNotFound, + ErrEntrypointNotFound, + ErrContractError, + ErrBlockNotFound, + ) } return result, nil diff --git a/rpc/call_test.go b/rpc/call_test.go index 38384ea97..7a8319400 100644 --- a/rpc/call_test.go +++ b/rpc/call_test.go @@ -27,7 +27,14 @@ import ( // // none func TestCall(t *testing.T) { - tests.RunTestOn(t, tests.MockEnv, tests.TestnetEnv, tests.MainnetEnv, tests.DevnetEnv, tests.IntegrationEnv) + tests.RunTestOn( + t, + tests.MockEnv, + tests.TestnetEnv, + tests.MainnetEnv, + tests.DevnetEnv, + tests.IntegrationEnv, + ) testConfig := BeforeEach(t, false) @@ -56,12 +63,12 @@ func TestCall(t *testing.T) { { name: "Ok", FunctionCall: FunctionCall{ - ContractAddress: internalUtils.RANDOM_FELT, + ContractAddress: internalUtils.DeadBeef, EntryPointSelector: internalUtils.GetSelectorFromNameFelt("decimals"), Calldata: []*felt.Felt{}, }, BlockID: WithBlockTag(BlockTagLatest), - ExpectedPatternResult: internalUtils.RANDOM_FELT, + ExpectedPatternResult: internalUtils.DeadBeef, }, }, tests.TestnetEnv: { @@ -82,7 +89,7 @@ func TestCall(t *testing.T) { EntryPointSelector: internalUtils.GetSelectorFromNameFelt("name"), Calldata: []*felt.Felt{}, }, - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), ExpectedPatternResult: internalUtils.TestHexToFelt(t, "0x506f736974696f6e"), }, { @@ -128,7 +135,7 @@ func TestCall(t *testing.T) { { name: "ContractNotFound", FunctionCall: FunctionCall{ - ContractAddress: internalUtils.RANDOM_FELT, + ContractAddress: internalUtils.DeadBeef, EntryPointSelector: internalUtils.GetSelectorFromNameFelt("name"), Calldata: []*felt.Felt{}, }, @@ -164,7 +171,11 @@ func TestCall(t *testing.T) { for _, test := range testSet { t.Run("Test: "+test.name, func(t *testing.T) { - output, err := testConfig.Provider.Call(context.Background(), test.FunctionCall, test.BlockID) + output, err := testConfig.Provider.Call( + context.Background(), + test.FunctionCall, + test.BlockID, + ) if test.ExpectedError != nil { rpcErr, ok := err.(*RPCError) require.True(t, ok) diff --git a/rpc/chain_test.go b/rpc/chain_test.go index abbe1a8d7..99cb6137a 100644 --- a/rpc/chain_test.go +++ b/rpc/chain_test.go @@ -13,7 +13,14 @@ import ( // TestChainID is a function that tests the ChainID function in the Go test file. func TestChainID(t *testing.T) { - tests.RunTestOn(t, tests.MockEnv, tests.TestnetEnv, tests.MainnetEnv, tests.DevnetEnv, tests.IntegrationEnv) + tests.RunTestOn( + t, + tests.MockEnv, + tests.TestnetEnv, + tests.MainnetEnv, + tests.DevnetEnv, + tests.IntegrationEnv, + ) testConfig := BeforeEach(t, false) @@ -61,11 +68,11 @@ func TestSyncing(t *testing.T) { if tests.TEST_ENV == tests.MockEnv { value := SyncStatus{ IsSyncing: true, - StartingBlockHash: internalUtils.RANDOM_FELT, + StartingBlockHash: internalUtils.DeadBeef, StartingBlockNum: 1234, - CurrentBlockHash: internalUtils.RANDOM_FELT, + CurrentBlockHash: internalUtils.DeadBeef, CurrentBlockNum: 1234, - HighestBlockHash: internalUtils.RANDOM_FELT, + HighestBlockHash: internalUtils.DeadBeef, HighestBlockNum: 1234, } assert.Exactly(t, value, sync) diff --git a/rpc/client.go b/rpc/client.go index 41a7b278b..73c751603 100644 --- a/rpc/client.go +++ b/rpc/client.go @@ -8,12 +8,19 @@ import ( ) type callCloser interface { - // CallContext calls the RPC method with the specified parameters and returns an error. + // CallContext calls the RPC method with the specified parameters and + // returns an error. CallContext(ctx context.Context, result interface{}, method string, args interface{}) error // CallContextWithSliceArgs call 'CallContext' with a slice of arguments. - // For RPC-Calls with optional arguments, use 'CallContext' instead and pass a struct containing - // the arguments, because Juno doesn't support optional arguments being passed in an array, only within an object. - CallContextWithSliceArgs(ctx context.Context, result interface{}, method string, args ...interface{}) error + // For RPC-Calls with optional arguments, use 'CallContext' instead and + // pass a struct containing the arguments, because Juno doesn't support + // optional arguments being passed in an array, only within an object. + CallContextWithSliceArgs( + ctx context.Context, + result interface{}, + method string, + args ...interface{}, + ) error Close() } @@ -31,8 +38,9 @@ type wsConn interface { args interface{}, ) (*client.ClientSubscription, error) // SubscribeWithSliceArgs call 'Subscribe' with a slice of arguments. - // For RPC-Subscriptions with optional arguments, use 'Subscribe' instead and pass a struct containing - // the arguments, because Juno doesn't support optional arguments being passed in an array, only within an object. + // For RPC-Subscriptions with optional arguments, use 'Subscribe' instead and pass + // a struct containing the arguments, because Juno doesn't support optional arguments + // being passed in an array, only within an object. SubscribeWithSliceArgs( ctx context.Context, namespace string, @@ -42,7 +50,8 @@ type wsConn interface { ) (*client.ClientSubscription, error) } -// do is a function that performs a remote procedure call (RPC) using the provided callCloser. +// do is a function that performs a remote procedure call (RPC) using the +// provided callCloser. // It passes the parameters as an array in the JSON-RPC call. // // Parameters: @@ -54,7 +63,13 @@ type wsConn interface { // // Returns: // - error: an error if any occurred during the function call -func do(ctx context.Context, call callCloser, method string, data interface{}, args ...interface{}) error { +func do( + ctx context.Context, + call callCloser, + method string, + data interface{}, + args ...interface{}, +) error { var raw json.RawMessage err := call.CallContextWithSliceArgs(ctx, &raw, method, args...) if err != nil { @@ -70,9 +85,10 @@ func do(ctx context.Context, call callCloser, method string, data interface{}, a return nil } -// doAsObject is a function that performs a remote procedure call (RPC) using the provided callCloser. -// It passes the parameter as an object in the JSON-RPC call, used for RPC-Calls with optional arguments -// since Juno doesn't support optional arguments being passed in an array, only within an object. +// doAsObject is a function that performs a remote procedure call (RPC) using +// the provided callCloser. It passes the parameter as an object in the JSON-RPC +// call, used for RPC-Calls with optional arguments since Juno doesn't support +// optional arguments being passed in an array, only within an object. // // Parameters: // - ctx: represents the current execution context diff --git a/rpc/contract.go b/rpc/contract.go index e258bfc1d..b45938c83 100644 --- a/rpc/contract.go +++ b/rpc/contract.go @@ -21,7 +21,11 @@ import ( // Returns: // - ClassOutput: The output of the class. // - error: An error if any occurred during the execution. -func (provider *Provider) Class(ctx context.Context, blockID BlockID, classHash *felt.Felt) (ClassOutput, error) { +func (provider *Provider) Class( + ctx context.Context, + blockID BlockID, + classHash *felt.Felt, +) (ClassOutput, error) { var rawClass map[string]any if err := do(ctx, provider.c, "starknet_getClass", &rawClass, blockID, classHash); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrClassHashNotFound, ErrBlockNotFound) @@ -40,9 +44,15 @@ func (provider *Provider) Class(ctx context.Context, blockID BlockID, classHash // Returns: // - ClassOutput: The output of the class // - error: An error if any occurred during the execution -func (provider *Provider) ClassAt(ctx context.Context, blockID BlockID, contractAddress *felt.Felt) (ClassOutput, error) { +func (provider *Provider) ClassAt( + ctx context.Context, + blockID BlockID, + contractAddress *felt.Felt, +) (ClassOutput, error) { var rawClass map[string]any - if err := do(ctx, provider.c, "starknet_getClassAt", &rawClass, blockID, contractAddress); err != nil { + if err := do( + ctx, provider.c, "starknet_getClassAt", &rawClass, blockID, contractAddress, + ); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrContractNotFound, ErrBlockNotFound) } @@ -91,9 +101,15 @@ func typecastClassOutput(rawClass map[string]any) (ClassOutput, error) { // Returns: // - *felt.Felt: The class hash // - error: An error if any occurred during the execution -func (provider *Provider) ClassHashAt(ctx context.Context, blockID BlockID, contractAddress *felt.Felt) (*felt.Felt, error) { +func (provider *Provider) ClassHashAt( + ctx context.Context, + blockID BlockID, + contractAddress *felt.Felt, +) (*felt.Felt, error) { var result *felt.Felt - if err := do(ctx, provider.c, "starknet_getClassHashAt", &result, blockID, contractAddress); err != nil { + if err := do( + ctx, provider.c, "starknet_getClassHashAt", &result, blockID, contractAddress, + ); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrContractNotFound, ErrBlockNotFound) } @@ -111,10 +127,17 @@ func (provider *Provider) ClassHashAt(ctx context.Context, blockID BlockID, cont // Returns: // - string: The value of the storage // - error: An error if any occurred during the execution -func (provider *Provider) StorageAt(ctx context.Context, contractAddress *felt.Felt, key string, blockID BlockID) (string, error) { +func (provider *Provider) StorageAt( + ctx context.Context, + contractAddress *felt.Felt, + key string, + blockID BlockID, +) (string, error) { var value string hashKey := fmt.Sprintf("0x%x", internalUtils.GetSelectorFromName(key)) - if err := do(ctx, provider.c, "starknet_getStorageAt", &value, contractAddress, hashKey, blockID); err != nil { + if err := do( + ctx, provider.c, "starknet_getStorageAt", &value, contractAddress, hashKey, blockID, + ); err != nil { return "", rpcerr.UnwrapToRPCErr(err, ErrContractNotFound, ErrBlockNotFound) } @@ -131,28 +154,37 @@ func (provider *Provider) StorageAt(ctx context.Context, contractAddress *felt.F // Returns: // - *felt.Felt: the contract's nonce at the requested state // - error: an error if any -func (provider *Provider) Nonce(ctx context.Context, blockID BlockID, contractAddress *felt.Felt) (*felt.Felt, error) { +func (provider *Provider) Nonce( + ctx context.Context, + blockID BlockID, + contractAddress *felt.Felt, +) (*felt.Felt, error) { var nonce *felt.Felt - if err := do(ctx, provider.c, "starknet_getNonce", &nonce, blockID, contractAddress); err != nil { + if err := do( + ctx, provider.c, "starknet_getNonce", &nonce, blockID, contractAddress, + ); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrContractNotFound, ErrBlockNotFound) } return nonce, nil } -// Estimates the resources required by a given sequence of transactions when applied on a given state. -// If one of the transactions reverts or fails due to any reason (e.g. validation failure or an internal error), -// a TRANSACTION_EXECUTION_ERROR is returned. The estimate is given in fri. +// Estimates the resources required by a given sequence of transactions when applied +// on a given state. If one of the transactions reverts or fails due to any reason +// (e.g. validation failure or an internal error), a TRANSACTION_EXECUTION_ERROR is returned. +// The estimate is given in fri. // // Parameters: // - ctx: The context of the function call -// - requests: A sequence of transactions to estimate, running each transaction on the state resulting from applying all the previous ones +// - requests: A sequence of transactions to estimate, running each transaction on the +// state resulting from applying all the previous ones // - simulationFlags: Describes what parts of the transaction should be executed -// - blockID: The hash of the requested block, or number (height) of the requested block, or a block tag, for -// the block referencing the state or call the transaction on. +// - blockID: The hash of the requested block, or number (height) of the requested block, +// or a block tag, for the block referencing the state or call the transaction on. // // Returns: -// - []FeeEstimation: A sequence of fee estimation where the i'th estimate corresponds to the i'th transaction +// - []FeeEstimation: A sequence of fee estimation where the i'th estimate corresponds +// to the i'th transaction // - error: An error if any occurred during the execution func (provider *Provider) EstimateFee( ctx context.Context, @@ -161,7 +193,9 @@ func (provider *Provider) EstimateFee( blockID BlockID, ) ([]FeeEstimation, error) { var raw []FeeEstimation - if err := do(ctx, provider.c, "starknet_estimateFee", &raw, requests, simulationFlags, blockID); err != nil { + if err := do( + ctx, provider.c, "starknet_estimateFee", &raw, requests, simulationFlags, blockID, + ); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrTxnExec, ErrBlockNotFound) } @@ -178,9 +212,15 @@ func (provider *Provider) EstimateFee( // Returns: // - MessageFeeEstimation: the fee estimated for the message // - error: an error if any occurred during the execution -func (provider *Provider) EstimateMessageFee(ctx context.Context, msg MsgFromL1, blockID BlockID) (MessageFeeEstimation, error) { +func (provider *Provider) EstimateMessageFee( + ctx context.Context, + msg MsgFromL1, + blockID BlockID, +) (MessageFeeEstimation, error) { var raw MessageFeeEstimation - if err := do(ctx, provider.c, "starknet_estimateMessageFee", &raw, msg, blockID); err != nil { + if err := do( + ctx, provider.c, "starknet_estimateMessageFee", &raw, msg, blockID, + ); err != nil { return raw, rpcerr.UnwrapToRPCErr(err, ErrContractError, ErrBlockNotFound) } @@ -188,26 +228,33 @@ func (provider *Provider) EstimateMessageFee(ctx context.Context, msg MsgFromL1, } // Get merkle paths in one of the state tries: global state, classes, individual contract. -// A single request can query for any mix of the three types of storage proofs (classes, contracts, and storage) +// A single request can query for any mix of the three types of storage proofs (classes, +// contracts, and storage) // // Parameters: // - ctx: The context of the function call // - storageProofInput: an input containing optional and required fields for the request // // Returns: -// - *StorageProofResult: The requested storage proofs. Note that if a requested leaf has the default value, -// the path to it may end in an edge node whose path is not a prefix of the requested leaf, thus effectively proving non-membership +// - *StorageProofResult: The requested storage proofs. Note that if a requested leaf +// has the default value, the path to it may end in an edge node whose path is not a +// prefix of the requested leaf, thus effectively proving non-membership // - error: an error if any occurred during the execution // -//nolint:gocritic -func (provider *Provider) GetStorageProof(ctx context.Context, storageProofInput StorageProofInput) (*StorageProofResult, error) { - err := checkForPre_confirmed(storageProofInput.BlockID) +//nolint:gocritic //TODO: pass the input as a pointer +func (provider *Provider) StorageProof( + ctx context.Context, + storageProofInput StorageProofInput, +) (*StorageProofResult, error) { + err := checkForPreConfirmed(storageProofInput.BlockID) if err != nil { return nil, err } var raw StorageProofResult - if err := doAsObject(ctx, provider.c, "starknet_getStorageProof", &raw, storageProofInput); err != nil { + if err := doAsObject( + ctx, provider.c, "starknet_getStorageProof", &raw, storageProofInput, + ); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrBlockNotFound, ErrStorageProofNotSupported) } diff --git a/rpc/contract_test.go b/rpc/contract_test.go index 521560c92..362d2ef44 100644 --- a/rpc/contract_test.go +++ b/rpc/contract_test.go @@ -45,8 +45,8 @@ func TestClassAt(t *testing.T) { testSet := map[tests.TestEnv][]testSetType{ tests.MockEnv: { { - ContractAddress: internalUtils.RANDOM_FELT, - ExpectedOperation: internalUtils.RANDOM_FELT.String(), + ContractAddress: internalUtils.DeadBeef, + ExpectedOperation: internalUtils.DeadBeef.String(), Block: WithBlockNumber(58344), }, }, @@ -66,7 +66,7 @@ func TestClassAt(t *testing.T) { { ContractAddress: internalUtils.TestHexToFelt(t, "0x04dAadB9d30c887E1ab2cf7D78DFE444A77AAB5a49C3353d6d9977e7eD669902"), ExpectedOperation: internalUtils.GetSelectorFromNameFelt("name_get").String(), - Block: WithBlockTag(BlockTagPre_confirmed), + Block: WithBlockTag(BlockTagPreConfirmed), }, { ContractAddress: internalUtils.TestHexToFelt(t, "0x04dAadB9d30c887E1ab2cf7D78DFE444A77AAB5a49C3353d6d9977e7eD669902"), @@ -96,39 +96,46 @@ func TestClassAt(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { - t.Run(fmt.Sprintf("BlockID: %v, ContractAddress: %v", test.Block, test.ContractAddress), func(t *testing.T) { - resp, err := testConfig.Provider.ClassAt(context.Background(), test.Block, test.ContractAddress) - require.NoError(t, err) + t.Run( + fmt.Sprintf("BlockID: %v, ContractAddress: %v", test.Block, test.ContractAddress), + func(t *testing.T) { + resp, err := testConfig.Provider.ClassAt( + context.Background(), + test.Block, + test.ContractAddress, + ) + require.NoError(t, err) - switch class := resp.(type) { - case *contracts.DeprecatedContractClass: - require.NotEmpty(t, class.Program, "code should exist") + switch class := resp.(type) { + case *contracts.DeprecatedContractClass: + require.NotEmpty(t, class.Program, "code should exist") - assert.Condition(t, func() bool { - for _, deprecatedCairoEntryPoint := range class.DeprecatedEntryPointsByType.External { - if test.ExpectedOperation == deprecatedCairoEntryPoint.Selector.String() { - return true + assert.Condition(t, func() bool { + for _, deprecatedCairoEntryPoint := range class.DeprecatedEntryPointsByType.External { + if test.ExpectedOperation == deprecatedCairoEntryPoint.Selector.String() { + return true + } } - } - return false - }, "operation not found in the class") - case *contracts.ContractClass: - require.NotEmpty(t, class.SierraProgram, "code should exist") + return false + }, "operation not found in the class") + case *contracts.ContractClass: + require.NotEmpty(t, class.SierraProgram, "code should exist") - assert.Condition(t, func() bool { - for _, entryPointsByType := range class.EntryPointsByType.External { - if test.ExpectedOperation == entryPointsByType.Selector.String() { - return true + assert.Condition(t, func() bool { + for _, entryPointsByType := range class.EntryPointsByType.External { + if test.ExpectedOperation == entryPointsByType.Selector.String() { + return true + } } - } - return false - }, "operation not found in the class") - default: - t.Fatalf("Received unknown response type: %v", reflect.TypeOf(resp)) - } - }) + return false + }, "operation not found in the class") + default: + t.Fatalf("Received unknown response type: %v", reflect.TypeOf(resp)) + } + }, + ) } } @@ -148,7 +155,14 @@ func TestClassAt(t *testing.T) { // // none func TestClassHashAt(t *testing.T) { - tests.RunTestOn(t, tests.MockEnv, tests.DevnetEnv, tests.TestnetEnv, tests.MainnetEnv, tests.IntegrationEnv) + tests.RunTestOn( + t, + tests.MockEnv, + tests.DevnetEnv, + tests.TestnetEnv, + tests.MainnetEnv, + tests.IntegrationEnv, + ) testConfig := BeforeEach(t, false) @@ -161,8 +175,8 @@ func TestClassHashAt(t *testing.T) { tests.MockEnv: { { Block: WithBlockTag(BlockTagLatest), - ContractHash: internalUtils.RANDOM_FELT, - ExpectedClassHash: internalUtils.RANDOM_FELT, + ContractHash: internalUtils.DeadBeef, + ExpectedClassHash: internalUtils.DeadBeef, }, }, tests.DevnetEnv: { @@ -191,7 +205,7 @@ func TestClassHashAt(t *testing.T) { ExpectedClassHash: internalUtils.TestHexToFelt(t, "0x01f372292df22d28f2d4c5798734421afe9596e6a566b8bc9b7b50e26521b855"), }, { - Block: WithBlockTag(BlockTagPre_confirmed), + Block: WithBlockTag(BlockTagPreConfirmed), ContractHash: internalUtils.TestHexToFelt(t, "0x04dAadB9d30c887E1ab2cf7D78DFE444A77AAB5a49C3353d6d9977e7eD669902"), ExpectedClassHash: internalUtils.TestHexToFelt(t, "0x01f372292df22d28f2d4c5798734421afe9596e6a566b8bc9b7b50e26521b855"), }, @@ -218,12 +232,19 @@ func TestClassHashAt(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { - t.Run(fmt.Sprintf("BlockID: %v, ContractHash: %v", test.Block, test.ContractHash), func(t *testing.T) { - classhash, err := testConfig.Provider.ClassHashAt(context.Background(), test.Block, test.ContractHash) - require.NoError(t, err) - require.NotEmpty(t, classhash, "should return a class") - require.Equal(t, test.ExpectedClassHash, classhash) - }) + t.Run( + fmt.Sprintf("BlockID: %v, ContractHash: %v", test.Block, test.ContractHash), + func(t *testing.T) { + classhash, err := testConfig.Provider.ClassHashAt( + context.Background(), + test.Block, + test.ContractHash, + ) + require.NoError(t, err) + require.NotEmpty(t, classhash, "should return a class") + require.Equal(t, test.ExpectedClassHash, classhash) + }, + ) } } @@ -268,8 +289,8 @@ func TestClass(t *testing.T) { testSet := map[tests.TestEnv][]testSetType{ tests.MockEnv: { { - BlockID: WithBlockTag(BlockTagPre_confirmed), - ClassHash: internalUtils.RANDOM_FELT, + BlockID: WithBlockTag(BlockTagPreConfirmed), + ClassHash: internalUtils.DeadBeef, ExpectedProgram: "H4sIAAAAAAAA", }, }, @@ -294,7 +315,7 @@ func TestClass(t *testing.T) { ExpectedEntryPointConstructor: contracts.SierraEntryPoint{FunctionIdx: 2, Selector: internalUtils.TestHexToFelt(t, "0x28ffe4ff0f226a9107253e17a904099aa4f63a02a5621de0576e5aa71bc5194")}, }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), ClassHash: internalUtils.TestHexToFelt(t, "0x01f372292df22d28f2d4c5798734421afe9596e6a566b8bc9b7b50e26521b855"), ExpectedProgram: internalUtils.TestHexToFelt(t, "0xe70d09071117174f17170d4fe60d09071117").String(), ExpectedEntryPointConstructor: contracts.SierraEntryPoint{FunctionIdx: 2, Selector: internalUtils.TestHexToFelt(t, "0x28ffe4ff0f226a9107253e17a904099aa4f63a02a5621de0576e5aa71bc5194")}, @@ -327,20 +348,27 @@ func TestClass(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { - t.Run(fmt.Sprintf("BlockID: %v, ClassHash: %v", test.BlockID, test.ClassHash), func(t *testing.T) { - resp, err := testConfig.Provider.Class(context.Background(), test.BlockID, test.ClassHash) - require.NoError(t, err) + t.Run( + fmt.Sprintf("BlockID: %v, ClassHash: %v", test.BlockID, test.ClassHash), + func(t *testing.T) { + resp, err := testConfig.Provider.Class( + context.Background(), + test.BlockID, + test.ClassHash, + ) + require.NoError(t, err) - switch class := resp.(type) { - case *contracts.DeprecatedContractClass: - assert.Contains(t, class.Program, test.ExpectedProgram) - case *contracts.ContractClass: - assert.Equal(t, class.SierraProgram[len(class.SierraProgram)-1].String(), test.ExpectedProgram) - assert.Equal(t, class.EntryPointsByType.Constructor[0], test.ExpectedEntryPointConstructor) - default: - t.Fatalf("Received unknown response type: %v", reflect.TypeOf(resp)) - } - }) + switch class := resp.(type) { + case *contracts.DeprecatedContractClass: + assert.Contains(t, class.Program, test.ExpectedProgram) + case *contracts.ContractClass: + assert.Equal(t, class.SierraProgram[len(class.SierraProgram)-1].String(), test.ExpectedProgram) + assert.Equal(t, class.EntryPointsByType.Constructor[0], test.ExpectedEntryPointConstructor) + default: + t.Fatalf("Received unknown response type: %v", reflect.TypeOf(resp)) + } + }, + ) } } @@ -360,7 +388,14 @@ func TestClass(t *testing.T) { // // none func TestStorageAt(t *testing.T) { - tests.RunTestOn(t, tests.MockEnv, tests.DevnetEnv, tests.TestnetEnv, tests.MainnetEnv, tests.IntegrationEnv) + tests.RunTestOn( + t, + tests.MockEnv, + tests.DevnetEnv, + tests.TestnetEnv, + tests.MainnetEnv, + tests.IntegrationEnv, + ) testConfig := BeforeEach(t, false) @@ -373,22 +408,22 @@ func TestStorageAt(t *testing.T) { testSet := map[tests.TestEnv][]testSetType{ tests.MockEnv: { { - ContractHash: internalUtils.RANDOM_FELT, + ContractHash: internalUtils.DeadBeef, StorageKey: "_signer", - Block: WithBlockTag(BlockTagPre_confirmed), - ExpectedValue: internalUtils.RANDOM_FELT.String(), + Block: WithBlockTag(BlockTagPreConfirmed), + ExpectedValue: internalUtils.DeadBeef.String(), }, { - ContractHash: internalUtils.RANDOM_FELT, + ContractHash: internalUtils.DeadBeef, StorageKey: "_signer", Block: WithBlockTag(BlockTagLatest), - ExpectedValue: internalUtils.RANDOM_FELT.String(), + ExpectedValue: internalUtils.DeadBeef.String(), }, { - ContractHash: internalUtils.RANDOM_FELT, + ContractHash: internalUtils.DeadBeef, StorageKey: "_signer", Block: WithBlockTag(BlockTagL1Accepted), - ExpectedValue: internalUtils.RANDOM_FELT.String(), + ExpectedValue: internalUtils.DeadBeef.String(), }, }, tests.DevnetEnv: { @@ -409,7 +444,7 @@ func TestStorageAt(t *testing.T) { { ContractHash: internalUtils.TestHexToFelt(t, "0x0200AB5CE3D7aDE524335Dc57CaF4F821A0578BBb2eFc2166cb079a3D29cAF9A"), StorageKey: "_signer", - Block: WithBlockTag(BlockTagPre_confirmed), + Block: WithBlockTag(BlockTagPreConfirmed), ExpectedValue: "0x38bd4cad8706e3a5d167ef7af12e28268c6122df3e0e909839a103039871b9e", }, { @@ -444,7 +479,12 @@ func TestStorageAt(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { - value, err := testConfig.Provider.StorageAt(context.Background(), test.ContractHash, test.StorageKey, test.Block) + value, err := testConfig.Provider.StorageAt( + context.Background(), + test.ContractHash, + test.StorageKey, + test.Block, + ) require.NoError(t, err) require.EqualValues(t, test.ExpectedValue, value) } @@ -464,7 +504,14 @@ func TestStorageAt(t *testing.T) { // // none func TestNonce(t *testing.T) { - tests.RunTestOn(t, tests.MockEnv, tests.DevnetEnv, tests.TestnetEnv, tests.MainnetEnv, tests.IntegrationEnv) + tests.RunTestOn( + t, + tests.MockEnv, + tests.DevnetEnv, + tests.TestnetEnv, + tests.MainnetEnv, + tests.IntegrationEnv, + ) testConfig := BeforeEach(t, false) @@ -501,7 +548,7 @@ func TestNonce(t *testing.T) { }, { ContractAddress: internalUtils.TestHexToFelt(t, "0x0200AB5CE3D7aDE524335Dc57CaF4F821A0578BBb2eFc2166cb079a3D29cAF9A"), - Block: WithBlockTag(BlockTagPre_confirmed), + Block: WithBlockTag(BlockTagPreConfirmed), ExpectedNonce: internalUtils.TestHexToFelt(t, "0x1"), }, { @@ -527,12 +574,19 @@ func TestNonce(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { - t.Run(fmt.Sprintf("blockID: %v, contractAddress: %s", test.Block, test.ContractAddress), func(t *testing.T) { - nonce, err := testConfig.Provider.Nonce(context.Background(), test.Block, test.ContractAddress) - require.NoError(t, err) - require.NotNil(t, nonce, "should return a nonce") - require.Equal(t, test.ExpectedNonce, nonce) - }) + t.Run( + fmt.Sprintf("blockID: %v, contractAddress: %s", test.Block, test.ContractAddress), + func(t *testing.T) { + nonce, err := testConfig.Provider.Nonce( + context.Background(), + test.Block, + test.ContractAddress, + ) + require.NoError(t, err) + require.NotNil(t, nonce, "should return a nonce") + require.Equal(t, test.ExpectedNonce, nonce) + }, + ) } } @@ -560,8 +614,14 @@ func TestEstimateMessageFee(t *testing.T) { // https://sepolia.voyager.online/message/0x273f4e20fc522098a60099e5872ab3deeb7fb8321a03dadbd866ac90b7268361 l1Handler := MsgFromL1{ FromAddress: "0x8453fc6cd1bcfe8d4dfc069c400b433054d47bdc", - ToAddress: internalUtils.TestHexToFelt(t, "0x04c5772d1914fe6ce891b64eb35bf3522aeae1315647314aac58b01137607f3f"), - Selector: internalUtils.TestHexToFelt(t, "0x1b64b1b3b690b43b9b514fb81377518f4039cd3e4f4914d8a6bdf01d679fb19"), + ToAddress: internalUtils.TestHexToFelt( + t, + "0x04c5772d1914fe6ce891b64eb35bf3522aeae1315647314aac58b01137607f3f", + ), + Selector: internalUtils.TestHexToFelt( + t, + "0x1b64b1b3b690b43b9b514fb81377518f4039cd3e4f4914d8a6bdf01d679fb19", + ), Payload: internalUtils.TestHexArrToFelt(t, []string{ "0x455448", "0x2f14d277fc49e0e2d2967d019aea8d6bd9cb3998", @@ -578,13 +638,13 @@ func TestEstimateMessageFee(t *testing.T) { BlockID: BlockID{Tag: "latest"}, ExpectedFeeEst: &MessageFeeEstimation{ FeeEstimationCommon: FeeEstimationCommon{ - L1GasConsumed: internalUtils.RANDOM_FELT, - L1GasPrice: internalUtils.RANDOM_FELT, - L2GasConsumed: internalUtils.RANDOM_FELT, - L2GasPrice: internalUtils.RANDOM_FELT, - L1DataGasConsumed: internalUtils.RANDOM_FELT, - L1DataGasPrice: internalUtils.RANDOM_FELT, - OverallFee: internalUtils.RANDOM_FELT, + L1GasConsumed: internalUtils.DeadBeef, + L1GasPrice: internalUtils.DeadBeef, + L2GasConsumed: internalUtils.DeadBeef, + L2GasPrice: internalUtils.DeadBeef, + L1DataGasConsumed: internalUtils.DeadBeef, + L1DataGasPrice: internalUtils.DeadBeef, + OverallFee: internalUtils.DeadBeef, }, Unit: WeiUnit, }, @@ -614,7 +674,7 @@ func TestEstimateMessageFee(t *testing.T) { }, { MsgFromL1: l1Handler, - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), ExpectedFeeEst: nil, }, { @@ -625,8 +685,8 @@ func TestEstimateMessageFee(t *testing.T) { { // invalid msg data MsgFromL1: MsgFromL1{ FromAddress: "0x8453fc6cd1bcfe8d4dfc069c400b433054d47bdc", - ToAddress: internalUtils.RANDOM_FELT, - Selector: internalUtils.RANDOM_FELT, + ToAddress: internalUtils.DeadBeef, + Selector: internalUtils.DeadBeef, Payload: []*felt.Felt{}, }, BlockID: WithBlockNumber(523066), @@ -641,25 +701,32 @@ func TestEstimateMessageFee(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { - t.Run(fmt.Sprintf("blockID: %v, fromAddress: %s", test.BlockID, test.FromAddress), func(t *testing.T) { - resp, err := testConfig.Provider.EstimateMessageFee(context.Background(), test.MsgFromL1, test.BlockID) - if test.ExpectedError != nil { - rpcErr, ok := err.(*RPCError) - require.True(t, ok) - assert.Equal(t, test.ExpectedError.Code, rpcErr.Code) - assert.Equal(t, test.ExpectedError.Message, rpcErr.Message) + t.Run( + fmt.Sprintf("blockID: %v, fromAddress: %s", test.BlockID, test.FromAddress), + func(t *testing.T) { + resp, err := testConfig.Provider.EstimateMessageFee( + context.Background(), + test.MsgFromL1, + test.BlockID, + ) + if test.ExpectedError != nil { + rpcErr, ok := err.(*RPCError) + require.True(t, ok) + assert.Equal(t, test.ExpectedError.Code, rpcErr.Code) + assert.Equal(t, test.ExpectedError.Message, rpcErr.Message) - return - } - require.NoError(t, err) + return + } + require.NoError(t, err) - if test.ExpectedFeeEst != nil { - assert.Exactly(t, *test.ExpectedFeeEst, resp) + if test.ExpectedFeeEst != nil { + assert.Exactly(t, *test.ExpectedFeeEst, resp) - return - } - assert.NotEmpty(t, resp) - }) + return + } + assert.NotEmpty(t, resp) + }, + ) } } @@ -698,13 +765,13 @@ func TestEstimateFee(t *testing.T) { expectedResp: []FeeEstimation{ { FeeEstimationCommon: FeeEstimationCommon{ - L1GasConsumed: internalUtils.RANDOM_FELT, - L1GasPrice: internalUtils.RANDOM_FELT, - L2GasConsumed: internalUtils.RANDOM_FELT, - L2GasPrice: internalUtils.RANDOM_FELT, - L1DataGasConsumed: internalUtils.RANDOM_FELT, - L1DataGasPrice: internalUtils.RANDOM_FELT, - OverallFee: internalUtils.RANDOM_FELT, + L1GasConsumed: internalUtils.DeadBeef, + L1GasPrice: internalUtils.DeadBeef, + L2GasConsumed: internalUtils.DeadBeef, + L2GasPrice: internalUtils.DeadBeef, + L1DataGasConsumed: internalUtils.DeadBeef, + L1DataGasPrice: internalUtils.DeadBeef, + OverallFee: internalUtils.DeadBeef, }, Unit: FriUnit, }, @@ -715,7 +782,7 @@ func TestEstimateFee(t *testing.T) { txs: []BroadcastTxn{ bradcastInvokeV3, }, - simFlags: []SimulationFlag{SKIP_VALIDATE}, + simFlags: []SimulationFlag{SkipValidate}, blockID: WithBlockTag("latest"), expectedError: nil, expectedResp: []FeeEstimation{ @@ -763,7 +830,7 @@ func TestEstimateFee(t *testing.T) { txs: []BroadcastTxn{ bradcastInvokeV3, }, - simFlags: []SimulationFlag{SKIP_VALIDATE}, + simFlags: []SimulationFlag{SkipValidate}, blockID: WithBlockNumber(574447), expectedError: nil, expectedResp: []FeeEstimation{ @@ -786,7 +853,7 @@ func TestEstimateFee(t *testing.T) { txs: []BroadcastTxn{ bradcastInvokeV3WithNewNonce, }, - simFlags: []SimulationFlag{SKIP_VALIDATE}, + simFlags: []SimulationFlag{SkipValidate}, blockID: WithBlockTag(BlockTagLatest), expectedError: nil, expectedResp: nil, @@ -796,8 +863,8 @@ func TestEstimateFee(t *testing.T) { txs: []BroadcastTxn{ bradcastInvokeV3WithNewNonce, }, - simFlags: []SimulationFlag{SKIP_VALIDATE}, - blockID: WithBlockTag(BlockTagPre_confirmed), + simFlags: []SimulationFlag{SkipValidate}, + blockID: WithBlockTag(BlockTagPreConfirmed), expectedError: nil, expectedResp: nil, }, @@ -806,7 +873,7 @@ func TestEstimateFee(t *testing.T) { txs: []BroadcastTxn{ bradcastInvokeV3WithNewNonce, }, - simFlags: []SimulationFlag{SKIP_VALIDATE}, + simFlags: []SimulationFlag{SkipValidate}, blockID: WithBlockTag(BlockTagL1Accepted), expectedError: nil, expectedResp: nil, @@ -829,9 +896,9 @@ func TestEstimateFee(t *testing.T) { MaxPricePerUnit: "0x18955dc56", }, }, - Type: TransactionType_Invoke, + Type: TransactionTypeInvoke, Version: TransactionV3, - SenderAddress: internalUtils.RANDOM_FELT, + SenderAddress: internalUtils.DeadBeef, Nonce: &felt.Zero, Calldata: []*felt.Felt{}, Signature: []*felt.Felt{}, @@ -862,7 +929,7 @@ func TestEstimateFee(t *testing.T) { txs: []BroadcastTxn{ integrationInvokeV3, }, - simFlags: []SimulationFlag{SKIP_VALIDATE}, + simFlags: []SimulationFlag{SkipValidate}, blockID: WithBlockNumber(1_300_000), expectedError: nil, expectedResp: []FeeEstimation{ @@ -898,9 +965,9 @@ func TestEstimateFee(t *testing.T) { MaxPricePerUnit: "0x18955dc56", }, }, - Type: TransactionType_Invoke, + Type: TransactionTypeInvoke, Version: TransactionV3, - SenderAddress: internalUtils.RANDOM_FELT, + SenderAddress: internalUtils.DeadBeef, Nonce: &felt.Zero, Calldata: []*felt.Felt{}, Signature: []*felt.Felt{}, @@ -929,7 +996,12 @@ func TestEstimateFee(t *testing.T) { for _, test := range testSet { t.Run(test.description, func(t *testing.T) { - resp, err := testConfig.Provider.EstimateFee(context.Background(), test.txs, test.simFlags, test.blockID) + resp, err := testConfig.Provider.EstimateFee( + context.Background(), + test.txs, + test.simFlags, + test.blockID, + ) if test.expectedError != nil { require.Error(t, err) rpcErr, ok := err.(*RPCError) @@ -1049,7 +1121,7 @@ func TestGetStorageProof(t *testing.T) { { Description: "error: using pre_confirmed tag in block_id", StorageProofInput: StorageProofInput{ - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), }, ExpectedError: ErrInvalidBlockID, }, @@ -1145,7 +1217,7 @@ func TestGetStorageProof(t *testing.T) { { Description: "error: using pre_confirmed tag in block_id", StorageProofInput: StorageProofInput{ - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), }, ExpectedError: ErrInvalidBlockID, }, @@ -1168,7 +1240,7 @@ func TestGetStorageProof(t *testing.T) { for _, test := range testSet { t.Run(test.Description, func(t *testing.T) { - result, err := provider.GetStorageProof(context.Background(), test.StorageProofInput) + result, err := provider.StorageProof(context.Background(), test.StorageProofInput) if test.ExpectedError != nil { require.Error(t, err) require.ErrorContains(t, err, test.ExpectedError.Error()) @@ -1218,7 +1290,11 @@ func assertStorageProofJSONEquality(t *testing.T, expectedResult, result []byte) require.True(t, ok) resultContractsProofContractLeavesData, ok := resultContractsProof["contract_leaves_data"].([]any) require.True(t, ok) - assert.ElementsMatch(t, expectedContractsProofContractLeavesData, resultContractsProofContractLeavesData) + assert.ElementsMatch( + t, + expectedContractsProofContractLeavesData, + resultContractsProofContractLeavesData, + ) // compare 'contracts_storage_proofs' expectedContractsStorageProofs, ok := expectedResultMap["contracts_storage_proofs"].([]any) diff --git a/rpc/errors.go b/rpc/errors.go index 818d311b3..e250c2413 100644 --- a/rpc/errors.go +++ b/rpc/errors.go @@ -16,15 +16,14 @@ type ( StringErrData = rpcerr.StringErrData ) -//nolint:exhaustruct var ( - _ rpcerr.RPCData = &CompilationErrData{} - _ rpcerr.RPCData = &ContractErrData{} - _ rpcerr.RPCData = &TransactionExecErrData{} - _ rpcerr.RPCData = &TraceStatusErrData{} + _ rpcerr.RPCData = (*CompilationErrData)(nil) + _ rpcerr.RPCData = (*ContractErrData)(nil) + _ rpcerr.RPCData = (*TransactionExecErrData)(nil) + _ rpcerr.RPCData = (*TraceStatusErrData)(nil) ) -//nolint:exhaustruct +//nolint:exhaustruct // Omitting the Data field for errors that don't have data. var ( ErrFailedToReceiveTxn = &RPCError{ Code: 1, @@ -115,7 +114,8 @@ var ( Message: "The transaction's resources don't cover validation or the minimal transaction fee", } ErrInsufficientAccountBalance = &RPCError{ - Code: 54, + Code: 54, + //nolint:lll // The line break would be outputted in the error message Message: "Account balance is smaller than the transaction's maximal fee (calculated as the sum of each resource's limit x max price)", } ErrValidationFailure = &RPCError{ diff --git a/rpc/errors_test.go b/rpc/errors_test.go index 804b3b1aa..b06eaff96 100644 --- a/rpc/errors_test.go +++ b/rpc/errors_test.go @@ -21,7 +21,10 @@ func TestRPCError(t *testing.T) { _, err := testConfig.Provider.ChainID(context.Background()) require.NoError(t, err) - _, err = testConfig.Provider.Events(context.Background(), EventsInput{ResultPageRequest: ResultPageRequest{ChunkSize: 0}}) + _, err = testConfig.Provider.Events( + context.Background(), + EventsInput{ResultPageRequest: ResultPageRequest{ChunkSize: 0}}, + ) require.Error(t, err) rpcErr := err.(*RPCError) assert.Equal(t, rpcErr.Code, rpcerr.InternalError) @@ -40,12 +43,16 @@ func TestRPCError(t *testing.T) { // invalid msg msgFromL1 := MsgFromL1{ FromAddress: "0x8453fc6cd1bcfe8d4dfc069c400b433054d47bdc", - ToAddress: internalUtils.RANDOM_FELT, - Selector: internalUtils.RANDOM_FELT, + ToAddress: internalUtils.DeadBeef, + Selector: internalUtils.DeadBeef, Payload: []*felt.Felt{}, } - _, err := testConfig.Provider.EstimateMessageFee(context.Background(), msgFromL1, WithBlockNumber(523066)) + _, err := testConfig.Provider.EstimateMessageFee( + context.Background(), + msgFromL1, + WithBlockNumber(523066), + ) require.Error(t, err) rpcErr := err.(*RPCError) diff --git a/rpc/events.go b/rpc/events.go index a21768624..cfe195f5b 100644 --- a/rpc/events.go +++ b/rpc/events.go @@ -16,11 +16,17 @@ import ( // - eventChunk: The retrieved events // - error: An error if any // -//nolint:gocritic +//nolint:gocritic //TODO: pass the input as a pointer func (provider *Provider) Events(ctx context.Context, input EventsInput) (*EventChunk, error) { var result EventChunk if err := do(ctx, provider.c, "starknet_getEvents", &result, input); err != nil { - return nil, rpcerr.UnwrapToRPCErr(err, ErrPageSizeTooBig, ErrInvalidContinuationToken, ErrBlockNotFound, ErrTooManyKeysInFilter) + return nil, rpcerr.UnwrapToRPCErr( + err, + ErrPageSizeTooBig, + ErrInvalidContinuationToken, + ErrBlockNotFound, + ErrTooManyKeysInFilter, + ) } return &result, nil diff --git a/rpc/executables.go b/rpc/executables.go index 821886696..d9b3cf0ee 100644 --- a/rpc/executables.go +++ b/rpc/executables.go @@ -17,7 +17,10 @@ import ( // Returns: // - CasmCompiledContractClass: The compiled contract class // - error: An error if any occurred during the execution -func (provider *Provider) CompiledCasm(ctx context.Context, classHash *felt.Felt) (*contracts.CasmClass, error) { +func (provider *Provider) CompiledCasm( + ctx context.Context, + classHash *felt.Felt, +) (*contracts.CasmClass, error) { var result contracts.CasmClass if err := do(ctx, provider.c, "starknet_getCompiledCasm", &result, classHash); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrClassHashNotFound, ErrCompilationError) diff --git a/rpc/executables_test.go b/rpc/executables_test.go index c35fb2a21..f7aaa8175 100644 --- a/rpc/executables_test.go +++ b/rpc/executables_test.go @@ -29,7 +29,7 @@ func TestCompiledCasm(t *testing.T) { tests.MockEnv: { { Description: "success - get compiled CASM", - ClassHash: internalUtils.RANDOM_FELT, + ClassHash: internalUtils.DeadBeef, ExpectedResultPath: "./testData/compiledCasm/sepolia.json", }, { @@ -71,7 +71,10 @@ func TestCompiledCasm(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { - expectedResult, err := internalUtils.UnmarshalJSONFileToType[contracts.CasmClass](test.ExpectedResultPath, "result") + expectedResult, err := internalUtils.UnmarshalJSONFileToType[contracts.CasmClass]( + test.ExpectedResultPath, + "result", + ) if test.ExpectedResultPath != "" { require.NoError(t, err) } diff --git a/rpc/mock_test.go b/rpc/mock_test.go index fe23c1cea..2e74fb85f 100644 --- a/rpc/mock_test.go +++ b/rpc/mock_test.go @@ -44,7 +44,12 @@ func (r *rpcMock) Close() { // // Returns: // - error: an error if any occurred during the function call -func (r *rpcMock) CallContextWithSliceArgs(ctx context.Context, result interface{}, method string, args ...interface{}) error { +func (r *rpcMock) CallContextWithSliceArgs( + ctx context.Context, + result interface{}, + method string, + args ...interface{}, +) error { return methodsSwitchList(result, method, args...) } @@ -57,7 +62,12 @@ func (r *rpcMock) CallContextWithSliceArgs(ctx context.Context, result interface // // Returns: // - error: an error if any occurred during the function call -func (r *rpcMock) CallContext(ctx context.Context, result interface{}, method string, args interface{}) error { +func (r *rpcMock) CallContext( + ctx context.Context, + result interface{}, + method string, + args interface{}, +) error { return methodsSwitchList(result, method, args) } @@ -181,7 +191,7 @@ func mock_starknet_blockHashAndNumber(result interface{}, args ...interface{}) e blockData := BlockHashAndNumberOutput{ Number: 1234, - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, } resp, err := json.Marshal(blockData) @@ -236,11 +246,11 @@ func mock_starknet_syncing(result interface{}, args ...interface{}) error { value := SyncStatus{ IsSyncing: true, - StartingBlockHash: internalUtils.RANDOM_FELT, + StartingBlockHash: internalUtils.DeadBeef, StartingBlockNum: 1234, - CurrentBlockHash: internalUtils.RANDOM_FELT, + CurrentBlockHash: internalUtils.DeadBeef, CurrentBlockNum: 1234, - HighestBlockHash: internalUtils.RANDOM_FELT, + HighestBlockHash: internalUtils.DeadBeef, HighestBlockNum: 1234, } @@ -381,11 +391,15 @@ func mock_starknet_getTransactionReceipt(result interface{}, args ...interface{} } arg0Felt := args[0].(*felt.Felt) - l1BlockHash, err := new(felt.Felt).SetString("0x74011377f326265f5a54e27a27968355e7033ad1de11b77b225374875aff519") + l1BlockHash, err := new( + felt.Felt, + ).SetString("0x74011377f326265f5a54e27a27968355e7033ad1de11b77b225374875aff519") if err != nil { return err } - testTxnHash, err := internalUtils.HexToFelt("0xf2f3d50192637e8d5e817363460c39d3a668fe12f117ecedb9749466d8352b") + testTxnHash, err := internalUtils.HexToFelt( + "0xf2f3d50192637e8d5e817363460c39d3a668fe12f117ecedb9749466d8352b", + ) if err != nil { return err } @@ -613,11 +627,15 @@ func mock_starknet_getEvents(result interface{}, args ...interface{}) error { return errors.New("-ChuckSize error message-") } - blockHash, err := internalUtils.HexToFelt("0x59dbe64bf2e2f89f5f2958cff11044dca0c64dea2e37ec6eaad9a5f838793cb") + blockHash, err := internalUtils.HexToFelt( + "0x59dbe64bf2e2f89f5f2958cff11044dca0c64dea2e37ec6eaad9a5f838793cb", + ) if err != nil { return err } - txHash, err := internalUtils.HexToFelt("0x568147c09d5e5db8dc703ce1da21eae47e9ad9c789bc2f2889c4413a38c579d") + txHash, err := internalUtils.HexToFelt( + "0x568147c09d5e5db8dc703ce1da21eae47e9ad9c789bc2f2889c4413a38c579d", + ) if err != nil { return err } @@ -711,7 +729,11 @@ func mock_starknet_addDeclareTransaction(result interface{}, args ...interface{} return nil } - return fmt.Errorf("%w: args[0] should be BroadcastDeclareTxnV3, got %T\n", errWrongArgs, args[0]) + return fmt.Errorf( + "%w: args[0] should be BroadcastDeclareTxnV3, got %T\n", + errWrongArgs, + args[0], + ) } // mock_starknet_estimateFee simulates the estimation of a fee in the StarkNet network. @@ -769,13 +791,13 @@ func mock_starknet_estimateFee(result interface{}, args ...interface{}) error { } else { output = FeeEstimation{ FeeEstimationCommon: FeeEstimationCommon{ - L1GasConsumed: internalUtils.RANDOM_FELT, - L1GasPrice: internalUtils.RANDOM_FELT, - L2GasConsumed: internalUtils.RANDOM_FELT, - L2GasPrice: internalUtils.RANDOM_FELT, - L1DataGasConsumed: internalUtils.RANDOM_FELT, - L1DataGasPrice: internalUtils.RANDOM_FELT, - OverallFee: internalUtils.RANDOM_FELT, + L1GasConsumed: internalUtils.DeadBeef, + L1GasPrice: internalUtils.DeadBeef, + L2GasConsumed: internalUtils.DeadBeef, + L2GasPrice: internalUtils.DeadBeef, + L1DataGasConsumed: internalUtils.DeadBeef, + L1DataGasPrice: internalUtils.DeadBeef, + OverallFee: internalUtils.DeadBeef, }, Unit: FriUnit, } @@ -825,13 +847,13 @@ func mock_starknet_estimateMessageFee(result interface{}, args ...interface{}) e output := MessageFeeEstimation{ FeeEstimationCommon: FeeEstimationCommon{ - L1DataGasConsumed: internalUtils.RANDOM_FELT, - L1DataGasPrice: internalUtils.RANDOM_FELT, - L1GasConsumed: internalUtils.RANDOM_FELT, - L1GasPrice: internalUtils.RANDOM_FELT, - L2GasConsumed: internalUtils.RANDOM_FELT, - L2GasPrice: internalUtils.RANDOM_FELT, - OverallFee: internalUtils.RANDOM_FELT, + L1DataGasConsumed: internalUtils.DeadBeef, + L1DataGasPrice: internalUtils.DeadBeef, + L1GasConsumed: internalUtils.DeadBeef, + L1GasPrice: internalUtils.DeadBeef, + L2GasConsumed: internalUtils.DeadBeef, + L2GasPrice: internalUtils.DeadBeef, + OverallFee: internalUtils.DeadBeef, }, Unit: WeiUnit, } @@ -1040,7 +1062,10 @@ func mock_starknet_getStateUpdate(result interface{}, args ...interface{}) error return errWrongArgs } - output, err := internalUtils.UnmarshalJSONFileToType[StateUpdateOutput]("testData/stateUpdate/sepolia_30000.json", "result") + output, err := internalUtils.UnmarshalJSONFileToType[StateUpdateOutput]( + "testData/stateUpdate/sepolia_30000.json", + "result", + ) if err != nil { return err } @@ -1126,24 +1151,24 @@ func mock_starknet_getBlockWithTxs(result interface{}, args ...interface{}) erro return errWrongArgs } - if blockId.Tag == BlockTagPre_confirmed { + if blockId.Tag == BlockTagPreConfirmed { pBlock, err := json.Marshal( - Pre_confirmedBlock{ - Pre_confirmedBlockHeader{ + PreConfirmedBlock{ + PreConfirmedBlockHeader{ Number: 1234, Timestamp: 1234, - SequencerAddress: internalUtils.RANDOM_FELT, + SequencerAddress: internalUtils.DeadBeef, L1GasPrice: ResourcePrice{ - PriceInFRI: internalUtils.RANDOM_FELT, - PriceInWei: internalUtils.RANDOM_FELT, + PriceInFRI: internalUtils.DeadBeef, + PriceInWei: internalUtils.DeadBeef, }, L2GasPrice: ResourcePrice{ - PriceInFRI: internalUtils.RANDOM_FELT, - PriceInWei: internalUtils.RANDOM_FELT, + PriceInFRI: internalUtils.DeadBeef, + PriceInWei: internalUtils.DeadBeef, }, L1DataGasPrice: ResourcePrice{ - PriceInFRI: internalUtils.RANDOM_FELT, - PriceInWei: internalUtils.RANDOM_FELT, + PriceInFRI: internalUtils.DeadBeef, + PriceInWei: internalUtils.DeadBeef, }, L1DAMode: L1DAModeBlob, StarknetVersion: "0.14.0", @@ -1203,13 +1228,13 @@ func mock_starknet_getBlockWithTxHashes(result interface{}, args ...interface{}) return err } - if blockId.Tag == BlockTagPre_confirmed { + if blockId.Tag == BlockTagPreConfirmed { pBlock, innerErr := json.Marshal( - Pre_confirmedBlockTxHashes{ - Pre_confirmedBlockHeader{ + PreConfirmedBlockTxHashes{ + PreConfirmedBlockHeader{ Number: 1234, Timestamp: 123, - SequencerAddress: internalUtils.RANDOM_FELT, + SequencerAddress: internalUtils.DeadBeef, }, txHashes, }) @@ -1224,12 +1249,12 @@ func mock_starknet_getBlockWithTxHashes(result interface{}, args ...interface{}) block, innerErr := json.Marshal( BlockTxHashes{ BlockHeader: BlockHeader{ - Hash: internalUtils.RANDOM_FELT, - ParentHash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, + ParentHash: internalUtils.DeadBeef, Timestamp: 124, - SequencerAddress: internalUtils.RANDOM_FELT, + SequencerAddress: internalUtils.DeadBeef, }, - Status: BlockStatus_AcceptedOnL1, + Status: BlockStatusAcceptedOnL1, Transactions: txHashes, }) if innerErr != nil { @@ -1259,30 +1284,30 @@ func mock_starknet_getBlockWithReceipts(result interface{}, args ...interface{}) return errWrongArgs } - if blockId.Tag == BlockTagPre_confirmed { + if blockId.Tag == BlockTagPreConfirmed { pBlock, innerErr := json.Marshal( - Pre_confirmedBlockWithReceipts{ - Pre_confirmedBlockHeader{ + PreConfirmedBlockWithReceipts{ + PreConfirmedBlockHeader{ Number: 1234, }, BlockBodyWithReceipts{ Transactions: []TransactionWithReceipt{ { Transaction: BlockTransaction{ - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, Transaction: InvokeTxnV1{ Type: "INVOKE", Version: TransactionV1, - SenderAddress: internalUtils.RANDOM_FELT, + SenderAddress: internalUtils.DeadBeef, }, }, Receipt: TransactionReceipt{ Type: "INVOKE", - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, ExecutionStatus: TxnExecutionStatusSUCCEEDED, FinalityStatus: TxnFinalityStatusAcceptedOnL1, ActualFee: FeePayment{ - Amount: internalUtils.RANDOM_FELT, + Amount: internalUtils.DeadBeef, Unit: UnitFri, }, }, @@ -1302,27 +1327,27 @@ func mock_starknet_getBlockWithReceipts(result interface{}, args ...interface{}) block, innerErr := json.Marshal( BlockWithReceipts{ BlockHeader{ - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, }, "ACCEPTED_ON_L1", BlockBodyWithReceipts{ Transactions: []TransactionWithReceipt{ { Transaction: BlockTransaction{ - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, Transaction: InvokeTxnV1{ Type: "INVOKE", Version: TransactionV1, - SenderAddress: internalUtils.RANDOM_FELT, + SenderAddress: internalUtils.DeadBeef, }, }, Receipt: TransactionReceipt{ Type: "INVOKE", - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, ExecutionStatus: TxnExecutionStatusSUCCEEDED, FinalityStatus: TxnFinalityStatusAcceptedOnL1, ActualFee: FeePayment{ - Amount: internalUtils.RANDOM_FELT, + Amount: internalUtils.DeadBeef, Unit: UnitFri, }, }, @@ -1369,7 +1394,8 @@ func mock_starknet_traceBlockTransactions(result interface{}, args ...interface{ if !ok { return fmt.Errorf("%w: args[0] should be BlockID, got %T\n", errWrongArgs, args[0]) } - if blockID.Hash != nil && blockID.Hash.String() == "0x42a4c6a4c3dffee2cce78f04259b499437049b0084c3296da9fbbec7eda79b2" { + if blockID.Hash != nil && + blockID.Hash.String() == "0x42a4c6a4c3dffee2cce78f04259b499437049b0084c3296da9fbbec7eda79b2" { rawBlockTrace, err := internalUtils.UnmarshalJSONFileToType[[]Trace]( "testData/trace/sepoliaBlockTrace_0x42a4c6a4c3dffee2cce78f04259b499437049b0084c3296da9fbbec7eda79b2.json", "", @@ -1474,17 +1500,22 @@ func mock_starknet_getCompiledCasm(result interface{}, args ...interface{}) erro return &RPCError{ Code: 100, Message: "Failed to compile the contract", - Data: &CompilationErrData{CompilationError: "compilation error: invalid sierra class"}, + Data: &CompilationErrData{ + CompilationError: "compilation error: invalid sierra class", + }, } } // Return error for specific test case - if classHash != internalUtils.RANDOM_FELT { + if classHash != internalUtils.DeadBeef { return ErrClassHashNotFound } // Read the test data from file - resp, err := internalUtils.UnmarshalJSONFileToType[json.RawMessage]("testData/compiledCasm/sepolia.json", "result") + resp, err := internalUtils.UnmarshalJSONFileToType[json.RawMessage]( + "testData/compiledCasm/sepolia.json", + "result", + ) if err != nil { return err } @@ -1520,12 +1551,12 @@ func mock_starknet_getMessagesStatus(result interface{}, args ...interface{}) er // Return mock response for successful case response := []MessageStatus{ { - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, FinalityStatus: TxnFinalityStatusAcceptedOnL2, ExecutionStatus: TxnExecutionStatusSUCCEEDED, }, { - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, FinalityStatus: TxnFinalityStatusAcceptedOnL2, ExecutionStatus: TxnExecutionStatusSUCCEEDED, }, diff --git a/rpc/provider.go b/rpc/provider.go index fe19e754f..90eb27f7e 100644 --- a/rpc/provider.go +++ b/rpc/provider.go @@ -15,7 +15,8 @@ import ( "golang.org/x/net/publicsuffix" ) -// rpcVersion is the version of the Starknet JSON-RPC specification that this SDK is compatible with. +// rpcVersion is the version of the Starknet JSON-RPC specification that +// this SDK is compatible with. // This should be updated when supporting new versions of the RPC specification. const rpcVersion = "0.9.0" @@ -25,8 +26,9 @@ var ( // Warning messages for version compatibility warnVersionCheckFailed = "warning: could not check RPC version compatibility" - //nolint:lll - warnVersionMismatch = "warning: the RPC provider version is %s, and is different from the version %s implemented by the SDK. This may cause unexpected behaviour." + + //nolint:lll // The line break would be outputted in the warning message + warnVersionMismatch = `warning: the RPC provider version is %s, and is different from the version %s implemented by the SDK. This may cause unexpected behaviour.` ) // Checks if the RPC provider version is compatible with the SDK version @@ -57,8 +59,8 @@ type WsProvider struct { } // Close closes the client, aborting any in-flight requests. -func (p *WsProvider) Close() { - p.c.Close() +func (ws *WsProvider) Close() { + ws.c.Close() } // NewProvider creates a new HTTP rpc Provider instance. @@ -67,7 +69,7 @@ func NewProvider(url string, options ...client.ClientOption) (*Provider, error) if err != nil { return nil, err } - httpClient := &http.Client{Jar: jar} //nolint:exhaustruct + httpClient := &http.Client{Jar: jar} //nolint:exhaustruct // Only the Jar field is used. // prepend the custom client to allow users to override options = append([]client.ClientOption{client.WithHTTPClient(httpClient)}, options...) c, err := client.DialOptions(context.Background(), url, options...) @@ -89,7 +91,7 @@ func NewWebsocketProvider(url string, options ...client.ClientOption) (*WsProvid if err != nil { return nil, err } - dialer := websocket.Dialer{Jar: jar} //nolint:exhaustruct + dialer := websocket.Dialer{Jar: jar} //nolint:exhaustruct // Only the Jar field is used. // prepend the custom client to allow users to override options = append([]client.ClientOption{client.WithWebsocketDialer(dialer)}, options...) @@ -102,9 +104,15 @@ func NewWebsocketProvider(url string, options ...client.ClientOption) (*WsProvid } //go:generate mockgen -destination=../mocks/mock_rpc_provider.go -package=mocks -source=provider.go api -type RpcProvider interface { - AddInvokeTransaction(ctx context.Context, invokeTxn *BroadcastInvokeTxnV3) (AddInvokeTransactionResponse, error) - AddDeclareTransaction(ctx context.Context, declareTransaction *BroadcastDeclareTxnV3) (AddDeclareTransactionResponse, error) +type RPCProvider interface { + AddInvokeTransaction( + ctx context.Context, + invokeTxn *BroadcastInvokeTxnV3, + ) (AddInvokeTransactionResponse, error) + AddDeclareTransaction( + ctx context.Context, + declareTransaction *BroadcastDeclareTxnV3, + ) (AddDeclareTransactionResponse, error) AddDeployAccountTransaction( ctx context.Context, deployAccountTransaction *BroadcastDeployAccountTxnV3, @@ -119,14 +127,25 @@ type RpcProvider interface { ChainID(ctx context.Context) (string, error) Class(ctx context.Context, blockID BlockID, classHash *felt.Felt) (ClassOutput, error) ClassAt(ctx context.Context, blockID BlockID, contractAddress *felt.Felt) (ClassOutput, error) - ClassHashAt(ctx context.Context, blockID BlockID, contractAddress *felt.Felt) (*felt.Felt, error) + ClassHashAt( + ctx context.Context, + blockID BlockID, + contractAddress *felt.Felt, + ) (*felt.Felt, error) CompiledCasm(ctx context.Context, classHash *felt.Felt) (*contracts.CasmClass, error) - EstimateFee(ctx context.Context, requests []BroadcastTxn, simulationFlags []SimulationFlag, blockID BlockID) ([]FeeEstimation, error) - EstimateMessageFee(ctx context.Context, msg MsgFromL1, blockID BlockID) (MessageFeeEstimation, error) + EstimateFee( + ctx context.Context, + requests []BroadcastTxn, + simulationFlags []SimulationFlag, + blockID BlockID, + ) ([]FeeEstimation, error) + EstimateMessageFee( + ctx context.Context, + msg MsgFromL1, + blockID BlockID, + ) (MessageFeeEstimation, error) Events(ctx context.Context, input EventsInput) (*EventChunk, error) - GetStorageProof(ctx context.Context, storageProofInput StorageProofInput) (*StorageProofResult, error) - GetTransactionStatus(ctx context.Context, transactionHash *felt.Felt) (*TxnStatusResult, error) - GetMessagesStatus(ctx context.Context, transactionHash NumAsHex) ([]MessageStatus, error) + MessagesStatus(ctx context.Context, transactionHash NumAsHex) ([]MessageStatus, error) Nonce(ctx context.Context, blockID BlockID, contractAddress *felt.Felt) (*felt.Felt, error) SimulateTransactions( ctx context.Context, @@ -134,15 +153,32 @@ type RpcProvider interface { txns []BroadcastTxn, simulationFlags []SimulationFlag, ) ([]SimulatedTransaction, error) - StateUpdate(ctx context.Context, blockID BlockID) (*StateUpdateOutput, error) - StorageAt(ctx context.Context, contractAddress *felt.Felt, key string, blockID BlockID) (string, error) SpecVersion(ctx context.Context) (string, error) + StateUpdate(ctx context.Context, blockID BlockID) (*StateUpdateOutput, error) + StorageAt( + ctx context.Context, + contractAddress *felt.Felt, + key string, + blockID BlockID, + ) (string, error) + StorageProof( + ctx context.Context, + storageProofInput StorageProofInput, + ) (*StorageProofResult, error) Syncing(ctx context.Context) (SyncStatus, error) TraceBlockTransactions(ctx context.Context, blockID BlockID) ([]Trace, error) - TransactionByBlockIdAndIndex(ctx context.Context, blockID BlockID, index uint64) (*BlockTransaction, error) - TransactionByHash(ctx context.Context, hash *felt.Felt) (*BlockTransaction, error) - TransactionReceipt(ctx context.Context, transactionHash *felt.Felt) (*TransactionReceiptWithBlockInfo, error) TraceTransaction(ctx context.Context, transactionHash *felt.Felt) (TxnTrace, error) + TransactionByBlockIDAndIndex( + ctx context.Context, + blockID BlockID, + index uint64, + ) (*BlockTransaction, error) + TransactionByHash(ctx context.Context, hash *felt.Felt) (*BlockTransaction, error) + TransactionReceipt( + ctx context.Context, + transactionHash *felt.Felt, + ) (*TransactionReceiptWithBlockInfo, error) + TransactionStatus(ctx context.Context, transactionHash *felt.Felt) (*TxnStatusResult, error) } type WebsocketProvider interface { @@ -151,7 +187,11 @@ type WebsocketProvider interface { events chan<- *EmittedEventWithFinalityStatus, options *EventSubscriptionInput, ) (*client.ClientSubscription, error) - SubscribeNewHeads(ctx context.Context, headers chan<- *BlockHeader, subBlockID SubscriptionBlockID) (*client.ClientSubscription, error) + SubscribeNewHeads( + ctx context.Context, + headers chan<- *BlockHeader, + subBlockID SubscriptionBlockID, + ) (*client.ClientSubscription, error) SubscribeNewTransactions( ctx context.Context, newTxns chan<- *TxnWithHashAndStatus, @@ -169,8 +209,7 @@ type WebsocketProvider interface { ) (*client.ClientSubscription, error) } -//nolint:exhaustruct var ( - _ RpcProvider = &Provider{} - _ WebsocketProvider = &WsProvider{} + _ RPCProvider = (*Provider)(nil) + _ WebsocketProvider = (*WsProvider)(nil) ) diff --git a/rpc/provider_test.go b/rpc/provider_test.go index 60a63f8a2..1f24507cb 100644 --- a/rpc/provider_test.go +++ b/rpc/provider_test.go @@ -180,7 +180,7 @@ func TestVersionCompatibility(t *testing.T) { require.NotNil(t, provider) // Read captured output - w.Close() + require.NoError(t, w.Close()) os.Stdout = old var buf bytes.Buffer _, err = io.Copy(&buf, r) diff --git a/rpc/trace.go b/rpc/trace.go index f3885a06a..541000bcc 100644 --- a/rpc/trace.go +++ b/rpc/trace.go @@ -17,9 +17,14 @@ import ( // Returns: // - TxnTrace: the transaction trace // - error: an error if the transaction trace cannot be retrieved -func (provider *Provider) TraceTransaction(ctx context.Context, transactionHash *felt.Felt) (TxnTrace, error) { +func (provider *Provider) TraceTransaction( + ctx context.Context, + transactionHash *felt.Felt, +) (TxnTrace, error) { var rawTxnTrace map[string]any - if err := do(ctx, provider.c, "starknet_traceTransaction", &rawTxnTrace, transactionHash); err != nil { + if err := do( + ctx, provider.c, "starknet_traceTransaction", &rawTxnTrace, transactionHash, + ); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrHashNotFound, ErrNoTraceAvailable) } @@ -29,7 +34,7 @@ func (provider *Provider) TraceTransaction(ctx context.Context, transactionHash } switch rawTxnTrace["type"] { - case string(TransactionType_Invoke): + case string(TransactionTypeInvoke): var trace InvokeTxnTrace err = json.Unmarshal(rawTraceByte, &trace) if err != nil { @@ -37,7 +42,7 @@ func (provider *Provider) TraceTransaction(ctx context.Context, transactionHash } return trace, nil - case string(TransactionType_Declare): + case string(TransactionTypeDeclare): var trace DeclareTxnTrace err = json.Unmarshal(rawTraceByte, &trace) if err != nil { @@ -45,7 +50,7 @@ func (provider *Provider) TraceTransaction(ctx context.Context, transactionHash } return trace, nil - case string(TransactionType_DeployAccount): + case string(TransactionTypeDeployAccount): var trace DeployAccountTxnTrace err = json.Unmarshal(rawTraceByte, &trace) if err != nil { @@ -53,7 +58,7 @@ func (provider *Provider) TraceTransaction(ctx context.Context, transactionHash } return trace, nil - case string(TransactionType_L1Handler): + case string(TransactionTypeL1Handler): var trace L1HandlerTxnTrace err = json.Unmarshal(rawTraceByte, &trace) if err != nil { @@ -75,14 +80,19 @@ func (provider *Provider) TraceTransaction(ctx context.Context, transactionHash // Returns: // - []Trace: a slice of Trace objects representing the traces of transactions in the block // - error: an error if there was a problem retrieving the traces. -func (provider *Provider) TraceBlockTransactions(ctx context.Context, blockID BlockID) ([]Trace, error) { - err := checkForPre_confirmed(blockID) +func (provider *Provider) TraceBlockTransactions( + ctx context.Context, + blockID BlockID, +) ([]Trace, error) { + err := checkForPreConfirmed(blockID) if err != nil { return nil, err } var output []Trace - if err := do(ctx, provider.c, "starknet_traceBlockTransactions", &output, blockID); err != nil { + if err := do( + ctx, provider.c, "starknet_traceBlockTransactions", &output, blockID, + ); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrBlockNotFound) } @@ -90,21 +100,26 @@ func (provider *Provider) TraceBlockTransactions(ctx context.Context, blockID Bl } // SimulateTransactions simulates transactions on the blockchain. -// Simulate a given sequence of transactions on the requested state, and generate the execution traces. -// Note that some of the transactions may revert, in which case no error is thrown, but revert details can be -// seen on the returned trace object. -// Note that some of the transactions may revert, this will be reflected by the revert_error property in the trace. Other -// types of failures (e.g. unexpected error or failure in the validation phase) will result in TRANSACTION_EXECUTION_ERROR. +// Simulate a given sequence of transactions on the requested state, and generate +// the execution traces. +// Note that some of the transactions may revert, in which case no error is thrown, +// but revert details can be seen on the returned trace object. +// Note that some of the transactions may revert, this will be reflected by the +// revert_error property in the trace. Other types of failures (e.g. unexpected error +// or failure in the validation phase) will result in TRANSACTION_EXECUTION_ERROR. // // Parameters: // - ctx: The context of the function call -// - blockID: The hash of the requested block, or number (height) of the requested block, or a block tag, for +// - blockID: The hash of the requested block, or number (height) of the requested +// block, or a block tag, for // the block referencing the state or call the transaction on. -// - txns: A sequence of transactions to simulate, running each transaction on the state resulting from applying all the previous ones +// - txns: A sequence of transactions to simulate, running each transaction on the +// state resulting from applying all the previous ones // - simulationFlags: Describes what parts of the transaction should be executed // // Returns: -// - []SimulatedTransaction: The execution trace and consumed resources of the required transactions +// - []SimulatedTransaction: The execution trace and consumed resources of the +// required transactions // - error: An error if any occurred during the execution func (provider *Provider) SimulateTransactions( ctx context.Context, @@ -113,7 +128,9 @@ func (provider *Provider) SimulateTransactions( simulationFlags []SimulationFlag, ) ([]SimulatedTransaction, error) { var output []SimulatedTransaction - if err := do(ctx, provider.c, "starknet_simulateTransactions", &output, blockID, txns, simulationFlags); err != nil { + if err := do( + ctx, provider.c, "starknet_simulateTransactions", &output, blockID, txns, simulationFlags, + ); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrTxnExec, ErrBlockNotFound) } diff --git a/rpc/trace_test.go b/rpc/trace_test.go index 3c041ca02..d998efec4 100644 --- a/rpc/trace_test.go +++ b/rpc/trace_test.go @@ -84,7 +84,10 @@ func TestTransactionTrace(t *testing.T) { t.Run(test.TransactionHash.String(), func(t *testing.T) { expectedResp := *internalUtils.TestUnmarshalJSONFileToType[InvokeTxnTrace](t, test.ExpectedRespFile, "") - resp, err := testConfig.Provider.TraceTransaction(context.Background(), test.TransactionHash) + resp, err := testConfig.Provider.TraceTransaction( + context.Background(), + test.TransactionHash, + ) if test.ExpectedError != nil { assert.EqualError(t, test.ExpectedError, err.Error()) @@ -148,7 +151,7 @@ func TestSimulateTransaction(t *testing.T) { { SimulateTxnInputFile: expectedInputFile, ExpectedRespFile: expectedRespFile, - AnotherBlockID: &BlockID{Tag: BlockTagPre_confirmed}, + AnotherBlockID: &BlockID{Tag: BlockTagPreConfirmed}, }, { SimulateTxnInputFile: expectedInputFile, @@ -186,7 +189,7 @@ func TestSimulateTransaction(t *testing.T) { // read file to compare JSONs expectedRespArr := *internalUtils.TestUnmarshalJSONFileToType[[]any](t, test.ExpectedRespFile, "result") - //nolint:dupl + //nolint:dupl // Similar to TestTraceBlockTransactions, but they're testing different things. for i, trace := range resp { assert.Equal(t, expectedResp[i].FeeEstimation, trace.FeeEstimation) compareTraceTxs(t, expectedResp[i].TxnTrace, trace.TxnTrace) @@ -280,7 +283,10 @@ func TestTraceBlockTransactions(t *testing.T) { for _, test := range testSet { t.Run(fmt.Sprintf("blockID: %v", test.BlockID), func(t *testing.T) { - resp, err := testConfig.Provider.TraceBlockTransactions(context.Background(), test.BlockID) + resp, err := testConfig.Provider.TraceBlockTransactions( + context.Background(), + test.BlockID, + ) if test.ExpectedErr != nil { require.Equal(t, test.ExpectedErr, err) @@ -301,7 +307,7 @@ func TestTraceBlockTransactions(t *testing.T) { expectedRespArr := make([]any, 0) require.NoError(t, json.Unmarshal(rawExpectedResp, &expectedRespArr)) - //nolint:dupl + //nolint:dupl // Similar to TestSimulateTransaction, but they're testing different things. for i, actualTrace := range resp { require.Equal(t, expectedTrace[i].TxnHash, actualTrace.TxnHash) compareTraceTxs(t, expectedTrace[i].TraceRoot, actualTrace.TraceRoot) @@ -377,7 +383,11 @@ func compareStateDiffs(t *testing.T, stateDiff1, stateDiff2 *StateDiff) { return } - assert.ElementsMatch(t, stateDiff1.DeprecatedDeclaredClasses, stateDiff2.DeprecatedDeclaredClasses) + assert.ElementsMatch( + t, + stateDiff1.DeprecatedDeclaredClasses, + stateDiff2.DeprecatedDeclaredClasses, + ) assert.ElementsMatch(t, stateDiff1.DeclaredClasses, stateDiff2.DeclaredClasses) assert.ElementsMatch(t, stateDiff1.DeployedContracts, stateDiff2.DeployedContracts) assert.ElementsMatch(t, stateDiff1.ReplacedClasses, stateDiff2.ReplacedClasses) diff --git a/rpc/transaction.go b/rpc/transaction.go index af47c089c..f4afe6307 100644 --- a/rpc/transaction.go +++ b/rpc/transaction.go @@ -16,7 +16,10 @@ import ( // Returns: // - BlockTransaction: The retrieved Transaction // - error: An error if any -func (provider *Provider) TransactionByHash(ctx context.Context, hash *felt.Felt) (*BlockTransaction, error) { +func (provider *Provider) TransactionByHash( + ctx context.Context, + hash *felt.Felt, +) (*BlockTransaction, error) { var tx BlockTransaction if err := do(ctx, provider.c, "starknet_getTransactionByHash", &tx, hash); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrHashNotFound) @@ -25,7 +28,7 @@ func (provider *Provider) TransactionByHash(ctx context.Context, hash *felt.Felt return &tx, nil } -// TransactionByBlockIdAndIndex retrieves a transaction by its block ID and index. +// TransactionByBlockIDAndIndex retrieves a transaction by its block ID and index. // // Parameters: // - ctx: The context.Context object for the request. @@ -35,9 +38,15 @@ func (provider *Provider) TransactionByHash(ctx context.Context, hash *felt.Felt // Returns: // - BlockTransaction: The retrieved Transaction object // - error: An error, if any -func (provider *Provider) TransactionByBlockIdAndIndex(ctx context.Context, blockID BlockID, index uint64) (*BlockTransaction, error) { +func (provider *Provider) TransactionByBlockIDAndIndex( + ctx context.Context, + blockID BlockID, + index uint64, +) (*BlockTransaction, error) { var tx BlockTransaction - if err := do(ctx, provider.c, "starknet_getTransactionByBlockIdAndIndex", &tx, blockID, index); err != nil { + if err := do( + ctx, provider.c, "starknet_getTransactionByBlockIdAndIndex", &tx, blockID, index, + ); err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrInvalidTxnIndex, ErrBlockNotFound) } @@ -53,7 +62,10 @@ func (provider *Provider) TransactionByBlockIdAndIndex(ctx context.Context, bloc // Returns: // - TransactionReceipt: the transaction receipt // - error: an error if any -func (provider *Provider) TransactionReceipt(ctx context.Context, transactionHash *felt.Felt) (*TransactionReceiptWithBlockInfo, error) { +func (provider *Provider) TransactionReceipt( + ctx context.Context, + transactionHash *felt.Felt, +) (*TransactionReceiptWithBlockInfo, error) { var receipt TransactionReceiptWithBlockInfo err := do(ctx, provider.c, "starknet_getTransactionReceipt", &receipt, transactionHash) if err != nil { @@ -63,15 +75,20 @@ func (provider *Provider) TransactionReceipt(ctx context.Context, transactionHas return &receipt, nil } -// GetTransactionStatus gets the transaction status (possibly reflecting that the tx is still in the mempool, or dropped from it) +// TransactionStatus gets the transaction status (possibly reflecting that +// the tx is still in the mempool, or dropped from it) // Parameters: // - ctx: the context.Context object for cancellation and timeouts. // - transactionHash: The hash of the requested transaction // // Returns: -// - *TxnStatusResult: Transaction status result, including finality status and execution status +// - *TxnStatusResult: Transaction status result, including finality status +// and execution status // - error, if one arose. -func (provider *Provider) GetTransactionStatus(ctx context.Context, transactionHash *felt.Felt) (*TxnStatusResult, error) { +func (provider *Provider) TransactionStatus( + ctx context.Context, + transactionHash *felt.Felt, +) (*TxnStatusResult, error) { var receipt TxnStatusResult err := do(ctx, provider.c, "starknet_getTransactionStatus", &receipt, transactionHash) if err != nil { @@ -81,17 +98,21 @@ func (provider *Provider) GetTransactionStatus(ctx context.Context, transactionH return &receipt, nil } -// Given an L1 tx hash, returns the associated l1_handler tx hashes and statuses for all L1 -> L2 messages -// sent by the l1 transaction, ordered by the L1 tx sending order +// Given an L1 tx hash, returns the associated l1_handler tx hashes and statuses +// for all L1 -> L2 messages sent by the l1 transaction, ordered by the L1 tx sending order // // Parameters: // - ctx: the context.Context object for cancellation and timeouts. // - transactionHash: The hash of the L1 transaction that sent L1->L2 messages // // Returns: -// - [] MessageStatusResp: An array containing the status of the messages sent by the L1 transaction +// - [] MessageStatusResp: An array containing the status of the messages sent +// by the L1 transaction // - error, if one arose. -func (provider *Provider) GetMessagesStatus(ctx context.Context, transactionHash NumAsHex) ([]MessageStatus, error) { +func (provider *Provider) MessagesStatus( + ctx context.Context, + transactionHash NumAsHex, +) ([]MessageStatus, error) { var response []MessageStatus err := do(ctx, provider.c, "starknet_getMessagesStatus", &response, transactionHash) if err != nil { diff --git a/rpc/transaction_test.go b/rpc/transaction_test.go index 1a09af793..4adcc54ef 100644 --- a/rpc/transaction_test.go +++ b/rpc/transaction_test.go @@ -30,19 +30,37 @@ func TestTransactionByHash(t *testing.T) { } BlockDeclareTxnV2Example := BlockTransaction{ - Hash: internalUtils.TestHexToFelt(t, "0xd109474cd037bad60a87ba0ccf3023d5f2d1cd45220c62091d41a614d38eda"), + Hash: internalUtils.TestHexToFelt( + t, + "0xd109474cd037bad60a87ba0ccf3023d5f2d1cd45220c62091d41a614d38eda", + ), Transaction: DeclareTxnV2{ - Type: TransactionType_Declare, - Version: TransactionV2, - MaxFee: internalUtils.TestHexToFelt(t, "0x4a0fbb2d7a43"), - ClassHash: internalUtils.TestHexToFelt(t, "0x79b7ec8fdf40a4ff6ed47123049dfe36b5c02db93aa77832682344775ef70c6"), - CompiledClassHash: internalUtils.TestHexToFelt(t, "0x7130f75fc2f1400813d1e96ea7ebee334b568a87b645a62aade0eb2fa2cf252"), - Nonce: internalUtils.TestHexToFelt(t, "0x16e"), + Type: TransactionTypeDeclare, + Version: TransactionV2, + MaxFee: internalUtils.TestHexToFelt(t, "0x4a0fbb2d7a43"), + ClassHash: internalUtils.TestHexToFelt( + t, + "0x79b7ec8fdf40a4ff6ed47123049dfe36b5c02db93aa77832682344775ef70c6", + ), + CompiledClassHash: internalUtils.TestHexToFelt( + t, + "0x7130f75fc2f1400813d1e96ea7ebee334b568a87b645a62aade0eb2fa2cf252", + ), + Nonce: internalUtils.TestHexToFelt(t, "0x16e"), Signature: []*felt.Felt{ - internalUtils.TestHexToFelt(t, "0x5569787df42fece1184537b0d480900a403386355b9d6a59e7c7a7e758287f0"), - internalUtils.TestHexToFelt(t, "0x2acaeea2e0817da33ed5dbeec295b0177819b5a5a50b0a669e6eecd88e42e92"), + internalUtils.TestHexToFelt( + t, + "0x5569787df42fece1184537b0d480900a403386355b9d6a59e7c7a7e758287f0", + ), + internalUtils.TestHexToFelt( + t, + "0x2acaeea2e0817da33ed5dbeec295b0177819b5a5a50b0a669e6eecd88e42e92", + ), }, - SenderAddress: internalUtils.TestHexToFelt(t, "0x5fd4befee268bf6880f955875cbed3ade8346b1f1e149cc87b317e62b6db569"), + SenderAddress: internalUtils.TestHexToFelt( + t, + "0x5fd4befee268bf6880f955875cbed3ade8346b1f1e149cc87b317e62b6db569", + ), }, } @@ -116,7 +134,7 @@ func TestTransactionByBlockIdAndIndex(t *testing.T) { ExpectedTxn: InvokeTxnV3example, }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), Index: 0, }, { @@ -138,7 +156,11 @@ func TestTransactionByBlockIdAndIndex(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { t.Run(fmt.Sprintf("Index: %d, BlockID: %v", test.Index, test.BlockID), func(t *testing.T) { - tx, err := testConfig.Provider.TransactionByBlockIdAndIndex(context.Background(), test.BlockID, test.Index) + tx, err := testConfig.Provider.TransactionByBlockIDAndIndex( + context.Background(), + test.BlockID, + test.Index, + ) if err != nil { // in case the block has no transactions assert.EqualError(t, err, ErrInvalidTxnIndex.Error()) @@ -198,7 +220,10 @@ func TestTransactionReceipt(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { - txReceiptWithBlockInfo, err := testConfig.Provider.TransactionReceipt(context.Background(), test.TxnHash) + txReceiptWithBlockInfo, err := testConfig.Provider.TransactionReceipt( + context.Background(), + test.TxnHash, + ) require.Nil(t, err) require.Equal(t, test.ExpectedResp, *txReceiptWithBlockInfo) } @@ -219,12 +244,12 @@ func TestGetTransactionStatus(t *testing.T) { tests.TestnetEnv: { { TxnHash: internalUtils.TestHexToFelt(t, "0xd109474cd037bad60a87ba0ccf3023d5f2d1cd45220c62091d41a614d38eda"), - ExpectedResp: TxnStatusResult{FinalityStatus: TxnStatus_Accepted_On_L1, ExecutionStatus: TxnExecutionStatusSUCCEEDED}, + ExpectedResp: TxnStatusResult{FinalityStatus: TxnStatusAcceptedOnL1, ExecutionStatus: TxnExecutionStatusSUCCEEDED}, }, { TxnHash: internalUtils.TestHexToFelt(t, "0x5adf825a4b7fc4d2d99e65be934bd85c83ca2b9383f2ff28fc2a4bc2e6382fc"), ExpectedResp: TxnStatusResult{ - FinalityStatus: TxnStatus_Accepted_On_L1, + FinalityStatus: TxnStatusAcceptedOnL1, ExecutionStatus: TxnExecutionStatusREVERTED, FailureReason: "Transaction execution has failed:\n0: Error in the called contract (contract address: 0x036d67ab362562a97f9fba8a1051cf8e37ff1a1449530fb9f1f0e32ac2da7d06, class hash: 0x061dac032f228abef9c6626f995015233097ae253a7f72d68552db02f2971b8f, selector: 0x015d40a3d6ca2ac30f4031e42be28da9b056fef9bb7357ac5e85627ee876e5ad):\nError at pc=0:4835:\nCairo traceback (most recent call last):\nUnknown location (pc=0:67)\nUnknown location (pc=0:1835)\nUnknown location (pc=0:2554)\nUnknown location (pc=0:3436)\nUnknown location (pc=0:4040)\n\n1: Error in the called contract (contract address: 0x00000000000000000000000000000000000000000000000000000000ffffffff, class hash: 0x0000000000000000000000000000000000000000000000000000000000000000, selector: 0x02f0b3c5710379609eb5495f1ecd348cb28167711b73609fe565a72734550354):\nRequested contract address 0x00000000000000000000000000000000000000000000000000000000ffffffff is not deployed.\n", }, @@ -233,13 +258,13 @@ func TestGetTransactionStatus(t *testing.T) { tests.IntegrationEnv: { { TxnHash: internalUtils.TestHexToFelt(t, "0x38f7c9972f2b6f6d92d474cf605a077d154d58de938125180e7c87f22c5b019"), - ExpectedResp: TxnStatusResult{FinalityStatus: TxnStatus_Accepted_On_L2, ExecutionStatus: TxnExecutionStatusSUCCEEDED}, + ExpectedResp: TxnStatusResult{FinalityStatus: TxnStatusAcceptedOnL2, ExecutionStatus: TxnExecutionStatusSUCCEEDED}, }, }, }[tests.TEST_ENV] for _, test := range testSet { - resp, err := testConfig.Provider.GetTransactionStatus(context.Background(), test.TxnHash) + resp, err := testConfig.Provider.TransactionStatus(context.Background(), test.TxnHash) require.Nil(t, err) require.Equal(t, resp.FinalityStatus, test.ExpectedResp.FinalityStatus) require.Equal(t, resp.ExecutionStatus, test.ExpectedResp.ExecutionStatus) @@ -266,12 +291,12 @@ func TestGetMessagesStatus(t *testing.T) { TxHash: "0x123", ExpectedResp: []MessageStatus{ { - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, FinalityStatus: TxnFinalityStatusAcceptedOnL2, ExecutionStatus: TxnExecutionStatusSUCCEEDED, }, { - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, FinalityStatus: TxnFinalityStatusAcceptedOnL2, ExecutionStatus: TxnExecutionStatusSUCCEEDED, }, @@ -307,7 +332,7 @@ func TestGetMessagesStatus(t *testing.T) { for _, test := range testSet { t.Run(string(test.TxHash), func(t *testing.T) { - resp, err := testConfig.Provider.GetMessagesStatus(context.Background(), test.TxHash) + resp, err := testConfig.Provider.MessagesStatus(context.Background(), test.TxHash) if test.ExpectedErr != nil { require.EqualError(t, err, test.ExpectedErr.Error()) } else { diff --git a/rpc/types.go b/rpc/types.go index 8d7cc214b..47b552f8b 100644 --- a/rpc/types.go +++ b/rpc/types.go @@ -9,7 +9,8 @@ import ( ) type ResultPageRequest struct { - // a pointer to the last element of the delivered page, use this token in a subsequent query to obtain the next page + // a pointer to the last element of the delivered page, use this token in a + // subsequent query to obtain the next page ContinuationToken string `json:"continuation_token,omitempty"` ChunkSize int `json:"chunk_size"` } @@ -85,11 +86,11 @@ type StateUpdateOutput struct { BlockHash *felt.Felt `json:"block_hash"` // NewRoot is the new global state root. Nil for pre_confirmed block. NewRoot *felt.Felt `json:"new_root"` - Pre_confirmedStateUpdate + PreConfirmedStateUpdate } // PRE_CONFIRMED_STATE_UPDATE in spec -type Pre_confirmedStateUpdate struct { +type PreConfirmedStateUpdate struct { // OldRoot is the previous global state root. OldRoot *felt.Felt `json:"old_root"` StateDiff StateDiff `json:"state_diff"` @@ -202,26 +203,30 @@ type TxDetails struct { // Fee estimation common fields type FeeEstimationCommon struct { - // The Ethereum gas consumption of the transaction, charged for L1->L2 messages and, depending on the block's DA_MODE, state diffs + // The Ethereum gas consumption of the transaction, charged for L1->L2 + // messages and, depending on the block's DA_MODE, state diffs L1GasConsumed *felt.Felt `json:"l1_gas_consumed"` - // The gas price (in wei or fri, depending on the tx version) that was used in the cost estimation. + // The gas price (in wei or fri, depending on the tx version) that was + // used in the cost estimation. L1GasPrice *felt.Felt `json:"l1_gas_price"` // The L2 gas consumption of the transaction L2GasConsumed *felt.Felt `json:"l2_gas_consumed"` - // The L2 gas price (in wei or fri, depending on the tx version) that was used in the cost estimation. + // The L2 gas price (in wei or fri, depending on the tx version) that + // was used in the cost estimation. L2GasPrice *felt.Felt `json:"l2_gas_price"` // The Ethereum data gas consumption of the transaction. L1DataGasConsumed *felt.Felt `json:"l1_data_gas_consumed"` - // The data gas price (in wei or fri, depending on the tx version) that was used in the cost estimation. + // The data gas price (in wei or fri, depending on the tx version) that + // was used in the cost estimation. L1DataGasPrice *felt.Felt `json:"l1_data_gas_price"` - // The estimated fee for the transaction (in wei or fri, depending on the tx version), equals to - // gas_consumed*gas_price + data_gas_consumed*data_gas_price. + // The estimated fee for the transaction (in wei or fri, depending on the + // tx version), equals to gas_consumed*gas_price + data_gas_consumed*data_gas_price. OverallFee *felt.Felt `json:"overall_fee"` } @@ -247,20 +252,21 @@ const ( // UnmarshalJSON unmarshals the JSON data into a TxnExecutionStatus struct. // // Parameters: -// - data: It takes a byte slice as a parameter, which represents the JSON data to be unmarshalled +// - data: It takes a byte slice as a parameter, which represents the JSON data to +// be unmarshalled // // Returns: // - error: an error if the unmarshaling fails -func (ts *TxnExecutionStatus) UnmarshalJSON(data []byte) error { +func (ex *TxnExecutionStatus) UnmarshalJSON(data []byte) error { unquoted, err := strconv.Unquote(string(data)) if err != nil { return err } switch unquoted { case "SUCCEEDED": - *ts = TxnExecutionStatusSUCCEEDED + *ex = TxnExecutionStatusSUCCEEDED case "REVERTED": - *ts = TxnExecutionStatusREVERTED + *ex = TxnExecutionStatusREVERTED default: return fmt.Errorf("unsupported execution status: %s", data) } @@ -270,7 +276,8 @@ func (ts *TxnExecutionStatus) UnmarshalJSON(data []byte) error { // MarshalJSON returns the JSON encoding of the TxnExecutionStatus. // -// It marshals the TxnExecutionStatus into a byte slice by quoting its string representation. +// It marshals the TxnExecutionStatus into a byte slice by quoting its string +// representation. // The function returns the marshalled byte slice and a nil error. // // Parameters: @@ -280,8 +287,8 @@ func (ts *TxnExecutionStatus) UnmarshalJSON(data []byte) error { // Returns: // - []byte: the JSON encoding of the TxnExecutionStatus // - error: the error if there was an issue marshalling -func (ts TxnExecutionStatus) MarshalJSON() ([]byte, error) { - return []byte(strconv.Quote(string(ts))), nil +func (ex TxnExecutionStatus) MarshalJSON() ([]byte, error) { + return []byte(strconv.Quote(string(ex))), nil } // String returns the string representation of the TxnExecutionStatus. @@ -292,37 +299,38 @@ func (ts TxnExecutionStatus) MarshalJSON() ([]byte, error) { // // Returns: // - string: the string representation of the TxnExecutionStatus -func (s TxnExecutionStatus) String() string { - return string(s) +func (ex TxnExecutionStatus) String() string { + return string(ex) } type TxnFinalityStatus string const ( - TxnFinalityStatusPre_confirmed TxnFinalityStatus = "PRE_CONFIRMED" - TxnFinalityStatusAcceptedOnL2 TxnFinalityStatus = "ACCEPTED_ON_L2" - TxnFinalityStatusAcceptedOnL1 TxnFinalityStatus = "ACCEPTED_ON_L1" + TxnFinalityStatusPreConfirmed TxnFinalityStatus = "PRE_CONFIRMED" + TxnFinalityStatusAcceptedOnL2 TxnFinalityStatus = "ACCEPTED_ON_L2" + TxnFinalityStatusAcceptedOnL1 TxnFinalityStatus = "ACCEPTED_ON_L1" ) // UnmarshalJSON unmarshals the JSON data into a TxnFinalityStatus. // // Parameters: -// - data: It takes a byte slice as a parameter, which represents the JSON data to be unmarshalled +// - data: It takes a byte slice as a parameter, which represents the JSON data to +// be unmarshalled // // Returns: // - error: an error if the unmarshaling fails -func (ts *TxnFinalityStatus) UnmarshalJSON(data []byte) error { +func (fs *TxnFinalityStatus) UnmarshalJSON(data []byte) error { unquoted, err := strconv.Unquote(string(data)) if err != nil { return err } switch unquoted { case "PRE_CONFIRMED": - *ts = TxnFinalityStatusPre_confirmed + *fs = TxnFinalityStatusPreConfirmed case "ACCEPTED_ON_L2": - *ts = TxnFinalityStatusAcceptedOnL2 + *fs = TxnFinalityStatusAcceptedOnL2 case "ACCEPTED_ON_L1": - *ts = TxnFinalityStatusAcceptedOnL1 + *fs = TxnFinalityStatusAcceptedOnL1 default: return fmt.Errorf("unsupported finality status: %s", data) } @@ -339,8 +347,8 @@ func (ts *TxnFinalityStatus) UnmarshalJSON(data []byte) error { // Returns: // - []byte: a byte slice // - error: an error if any -func (ts TxnFinalityStatus) MarshalJSON() ([]byte, error) { - return []byte(strconv.Quote(string(ts))), nil +func (fs TxnFinalityStatus) MarshalJSON() ([]byte, error) { + return []byte(strconv.Quote(string(fs))), nil } // String returns the string representation of the TxnFinalityStatus. @@ -351,6 +359,6 @@ func (ts TxnFinalityStatus) MarshalJSON() ([]byte, error) { // // Returns: // - string: the string representation of the TxnFinalityStatus -func (s TxnFinalityStatus) String() string { - return string(s) +func (fs TxnFinalityStatus) String() string { + return string(fs) } diff --git a/rpc/types_block.go b/rpc/types_block.go index f3ba14a0a..1e77a8feb 100644 --- a/rpc/types_block.go +++ b/rpc/types_block.go @@ -20,8 +20,8 @@ type Block struct { Transactions []BlockTransaction `json:"transactions"` } -type Pre_confirmedBlock struct { - Pre_confirmedBlockHeader +type PreConfirmedBlock struct { + PreConfirmedBlockHeader Transactions []BlockTransaction `json:"transactions"` } @@ -41,9 +41,10 @@ type TransactionWithReceipt struct { Receipt TransactionReceipt `json:"receipt"` } -// The dynamic block being constructed by the sequencer. Note that this object will be deprecated upon decentralisation. -type Pre_confirmedBlockWithReceipts struct { - Pre_confirmedBlockHeader +// The dynamic block being constructed by the sequencer. Note that this object +// will be deprecated upon decentralisation. +type PreConfirmedBlockWithReceipts struct { + PreConfirmedBlockHeader BlockBodyWithReceipts } @@ -54,8 +55,8 @@ type BlockTxHashes struct { Transactions []*felt.Felt `json:"transactions"` } -type Pre_confirmedBlockTxHashes struct { - Pre_confirmedBlockHeader +type PreConfirmedBlockTxHashes struct { + PreConfirmedBlockHeader Transactions []*felt.Felt `json:"transactions"` } @@ -84,9 +85,10 @@ type BlockHeader struct { StarknetVersion string `json:"starknet_version"` } -type Pre_confirmedBlockHeader struct { +type PreConfirmedBlockHeader struct { // The block number of the block that the proposer is currently building. - // Note that this is a local view of the node, whose accuracy depends on its polling interval length. + // Note that this is a local view of the node, whose accuracy depends on its + // polling interval length. Number uint64 `json:"block_number"` // Timestamp the time in which the block was created, encoded in Unix time Timestamp uint64 `json:"timestamp"` @@ -115,10 +117,11 @@ type BlockTag string const ( // The block which is currently being built by the block proposer in height `latest` + 1. - BlockTagPre_confirmed BlockTag = "pre_confirmed" + BlockTagPreConfirmed BlockTag = "pre_confirmed" // The latest Starknet block finalised by the consensus on L2. BlockTagLatest BlockTag = "latest" - // The latest Starknet block which was included in a state update on L1 and finalised by the consensus on L1. + // The latest Starknet block which was included in a state update on L1 and + // finalised by the consensus on L1. BlockTagL1Accepted BlockTag = "l1_accepted" ) @@ -173,7 +176,8 @@ func (b *BlockID) UnmarshalJSON(data []byte) error { var tag string if err := json.Unmarshal(data, &tag); err == nil { - if tag == string(BlockTagPre_confirmed) || tag == string(BlockTagLatest) || tag == string(BlockTagL1Accepted) { + if tag == string(BlockTagPreConfirmed) || tag == string(BlockTagLatest) || + tag == string(BlockTagL1Accepted) { b.Tag = BlockTag(tag) return nil @@ -197,7 +201,7 @@ func (b *SubscriptionBlockID) UnmarshalJSON(data []byte) error { return err } - if aux.Tag == BlockTagPre_confirmed || aux.Tag == BlockTagL1Accepted { + if aux.Tag == BlockTagPreConfirmed || aux.Tag == BlockTagL1Accepted { return fmt.Errorf("invalid block tag for this type: %s", aux.Tag) } @@ -208,8 +212,9 @@ func (b *SubscriptionBlockID) UnmarshalJSON(data []byte) error { // MarshalJSON marshals the BlockID to JSON format. // -// It returns a byte slice and an error. The byte slice contains the JSON representation of the BlockID, -// while the error indicates any error that occurred during the marshalling process. +// It returns a byte slice and an error. The byte slice contains the JSON +// representation of the BlockID, while the error indicates any error that +// occurred during the marshalling process. // // Parameters: // @@ -219,7 +224,7 @@ func (b *SubscriptionBlockID) UnmarshalJSON(data []byte) error { // - []byte: the JSON representation of the BlockID // - error: any error that occurred during the marshalling process func (b BlockID) MarshalJSON() ([]byte, error) { - if b.Tag == BlockTagPre_confirmed || b.Tag == BlockTagLatest || b.Tag == BlockTagL1Accepted { + if b.Tag == BlockTagPreConfirmed || b.Tag == BlockTagLatest || b.Tag == BlockTagL1Accepted { return []byte(strconv.Quote(string(b.Tag))), nil } @@ -239,18 +244,22 @@ func (b BlockID) MarshalJSON() ([]byte, error) { } func (b SubscriptionBlockID) MarshalJSON() ([]byte, error) { - if b.Tag == BlockTagPre_confirmed || b.Tag == BlockTagL1Accepted { + if b.Tag == BlockTagPreConfirmed || b.Tag == BlockTagL1Accepted { return nil, fmt.Errorf("invalid block tag for this type: %s", b.Tag) } return BlockID(b).MarshalJSON() } -// checkForPre_confirmed checks if the block ID has the 'pre_confirmed' tag. If it does, it returns an error. -// This is used to prevent the user from using the 'pre_confirmed' tag on methods that do not support it. -func checkForPre_confirmed(b BlockID) error { - if b.Tag == BlockTagPre_confirmed { - return errors.Join(ErrInvalidBlockID, errors.New("'pre_confirmed' tag is not supported on this method")) +// checkForPreConfirmed checks if the block ID has the 'pre_confirmed' tag. If it +// does, it returns an error. This is used to prevent the user from using the +// 'pre_confirmed' tag on methods that do not support it. +func checkForPreConfirmed(b BlockID) error { + if b.Tag == BlockTagPreConfirmed { + return errors.Join( + ErrInvalidBlockID, + errors.New("'pre_confirmed' tag is not supported on this method"), + ) } return nil @@ -259,9 +268,9 @@ func checkForPre_confirmed(b BlockID) error { type BlockStatus string const ( - BlockStatus_Pre_confirmed BlockStatus = "PRE_CONFIRMED" - BlockStatus_AcceptedOnL2 BlockStatus = "ACCEPTED_ON_L2" - BlockStatus_AcceptedOnL1 BlockStatus = "ACCEPTED_ON_L1" + BlockStatusPreConfirmed BlockStatus = "PRE_CONFIRMED" + BlockStatusAcceptedOnL2 BlockStatus = "ACCEPTED_ON_L2" + BlockStatusAcceptedOnL1 BlockStatus = "ACCEPTED_ON_L1" ) // UnmarshalJSON unmarshals the JSON representation of a BlockStatus. @@ -270,7 +279,8 @@ const ( // The function returns an error if there is an issue unmarshaling the data. // // Parameters: -// - data: It takes a byte slice as a parameter, which represents the JSON data to be unmarshaled +// - data: It takes a byte slice as a parameter, which represents the JSON data to +// be unmarshaled // // Returns: // - error: an error if the unmarshaling fails @@ -282,11 +292,11 @@ func (bs *BlockStatus) UnmarshalJSON(data []byte) error { switch unquoted { case "PRE_CONFIRMED": - *bs = BlockStatus_Pre_confirmed + *bs = BlockStatusPreConfirmed case "ACCEPTED_ON_L2": - *bs = BlockStatus_AcceptedOnL2 + *bs = BlockStatusAcceptedOnL2 case "ACCEPTED_ON_L1": - *bs = BlockStatus_AcceptedOnL1 + *bs = BlockStatusAcceptedOnL1 default: return fmt.Errorf("unsupported status: %s", data) } diff --git a/rpc/types_block_test.go b/rpc/types_block_test.go index 2f26fc26b..5fb5572a7 100644 --- a/rpc/types_block_test.go +++ b/rpc/types_block_test.go @@ -102,15 +102,15 @@ func TestBlockStatus(t *testing.T) { }{ { status: `"PRE_CONFIRMED"`, - want: BlockStatus_Pre_confirmed, + want: BlockStatusPreConfirmed, }, { status: `"ACCEPTED_ON_L2"`, - want: BlockStatus_AcceptedOnL2, + want: BlockStatusAcceptedOnL2, }, { status: `"ACCEPTED_ON_L1"`, - want: BlockStatus_AcceptedOnL1, + want: BlockStatusAcceptedOnL1, }, } { tx := new(BlockStatus) @@ -149,9 +149,9 @@ func TestBlockWithReceipts(t *testing.T) { testConfig := BeforeEach(t, false) type testSetType struct { - BlockID BlockID - ExpectedBlockWithReceipts *BlockWithReceipts - ExpectedPre_confirmedBlockWithReceipts *Pre_confirmedBlockWithReceipts + BlockID BlockID + ExpectedBlockWithReceipts *BlockWithReceipts + ExpectedPreConfirmedBlockWithReceipts *PreConfirmedBlockWithReceipts } var blockWithReceipt BlockWithReceipts @@ -167,27 +167,27 @@ func TestBlockWithReceipts(t *testing.T) { blockMock123 := BlockWithReceipts{ BlockHeader{ - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, }, "ACCEPTED_ON_L1", BlockBodyWithReceipts{ Transactions: []TransactionWithReceipt{ { Transaction: BlockTransaction{ - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, Transaction: InvokeTxnV1{ Type: "INVOKE", Version: TransactionV1, - SenderAddress: internalUtils.RANDOM_FELT, + SenderAddress: internalUtils.DeadBeef, }, }, Receipt: TransactionReceipt{ Type: "INVOKE", - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, ExecutionStatus: TxnExecutionStatusSUCCEEDED, FinalityStatus: TxnFinalityStatusAcceptedOnL1, ActualFee: FeePayment{ - Amount: internalUtils.RANDOM_FELT, + Amount: internalUtils.DeadBeef, Unit: UnitFri, }, }, @@ -196,28 +196,28 @@ func TestBlockWithReceipts(t *testing.T) { }, } - pre_confirmedBlockMock123 := Pre_confirmedBlockWithReceipts{ - Pre_confirmedBlockHeader{ + preConfirmedBlockMock123 := PreConfirmedBlockWithReceipts{ + PreConfirmedBlockHeader{ Number: 1234, }, BlockBodyWithReceipts{ Transactions: []TransactionWithReceipt{ { Transaction: BlockTransaction{ - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, Transaction: InvokeTxnV1{ Type: "INVOKE", Version: TransactionV1, - SenderAddress: internalUtils.RANDOM_FELT, + SenderAddress: internalUtils.DeadBeef, }, }, Receipt: TransactionReceipt{ Type: "INVOKE", - Hash: internalUtils.RANDOM_FELT, + Hash: internalUtils.DeadBeef, ExecutionStatus: TxnExecutionStatusSUCCEEDED, FinalityStatus: TxnFinalityStatusAcceptedOnL1, ActualFee: FeePayment{ - Amount: internalUtils.RANDOM_FELT, + Amount: internalUtils.DeadBeef, Unit: UnitFri, }, }, @@ -229,19 +229,19 @@ func TestBlockWithReceipts(t *testing.T) { testSet := map[tests.TestEnv][]testSetType{ tests.MockEnv: { { - BlockID: WithBlockTag(BlockTagLatest), - ExpectedBlockWithReceipts: &blockMock123, - ExpectedPre_confirmedBlockWithReceipts: nil, + BlockID: WithBlockTag(BlockTagLatest), + ExpectedBlockWithReceipts: &blockMock123, + ExpectedPreConfirmedBlockWithReceipts: nil, }, { - BlockID: WithBlockTag(BlockTagL1Accepted), - ExpectedBlockWithReceipts: &blockMock123, - ExpectedPre_confirmedBlockWithReceipts: nil, + BlockID: WithBlockTag(BlockTagL1Accepted), + ExpectedBlockWithReceipts: &blockMock123, + ExpectedPreConfirmedBlockWithReceipts: nil, }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), - ExpectedBlockWithReceipts: nil, - ExpectedPre_confirmedBlockWithReceipts: &pre_confirmedBlockMock123, + BlockID: WithBlockTag(BlockTagPreConfirmed), + ExpectedBlockWithReceipts: nil, + ExpectedPreConfirmedBlockWithReceipts: &preConfirmedBlockMock123, }, }, tests.TestnetEnv: { @@ -252,7 +252,7 @@ func TestBlockWithReceipts(t *testing.T) { BlockID: WithBlockTag(BlockTagLatest), }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), }, { BlockID: WithBlockNumber(64159), @@ -267,7 +267,7 @@ func TestBlockWithReceipts(t *testing.T) { BlockID: WithBlockTag(BlockTagLatest), }, { - BlockID: WithBlockTag(BlockTagPre_confirmed), + BlockID: WithBlockTag(BlockTagPreConfirmed), }, { BlockID: WithBlockNumber(1_300_000), @@ -301,12 +301,12 @@ func TestBlockWithReceipts(t *testing.T) { if test.ExpectedBlockWithReceipts != nil { assert.Exactly(t, block, test.ExpectedBlockWithReceipts) } - case *Pre_confirmedBlockWithReceipts: - pBlock, ok := result.(*Pre_confirmedBlockWithReceipts) + case *PreConfirmedBlockWithReceipts: + pBlock, ok := result.(*PreConfirmedBlockWithReceipts) require.True(t, ok, fmt.Sprintf("should return *Pre_confirmedBlockWithReceipts, instead: %T\n", result)) if tests.TEST_ENV == tests.MockEnv { - assert.Exactly(t, pBlock, test.ExpectedPre_confirmedBlockWithReceipts) + assert.Exactly(t, pBlock, test.ExpectedPreConfirmedBlockWithReceipts) } else { assert.NotEmpty(t, pBlock.Number, "Error in Pre_confirmedBlockWithReceipts ParentHash") assert.NotEmpty(t, pBlock.SequencerAddress, "Error in Pre_confirmedBlockWithReceipts SequencerAddress") diff --git a/rpc/types_broadcast_transaction.go b/rpc/types_broadcast_transaction.go index 871e54de3..d18e5f7c6 100644 --- a/rpc/types_broadcast_transaction.go +++ b/rpc/types_broadcast_transaction.go @@ -9,12 +9,10 @@ type BroadcastTxn interface{} // Note: this allow all types to pass, but are to help users of starknet.go // understand which types are allowed where. -// -//nolint:exhaustruct var ( - _ BroadcastTxn = BroadcastInvokeTxnV3{} - _ BroadcastTxn = BroadcastDeclareTxnV3{} - _ BroadcastTxn = BroadcastDeployAccountTxnV3{} + _ BroadcastTxn = (*BroadcastInvokeTxnV3)(nil) + _ BroadcastTxn = (*BroadcastDeclareTxnV3)(nil) + _ BroadcastTxn = (*BroadcastDeployAccountTxnV3)(nil) ) type BroadcastInvokeTxnV3 = InvokeTxnV3 diff --git a/rpc/types_contract.go b/rpc/types_contract.go index 8ef2865b5..dae89bbfd 100644 --- a/rpc/types_contract.go +++ b/rpc/types_contract.go @@ -35,18 +35,20 @@ type U128 string type ClassOutput interface{} -//nolint:exhaustruct var ( - _ ClassOutput = &contracts.DeprecatedContractClass{} - _ ClassOutput = &contracts.ContractClass{} + _ ClassOutput = (*contracts.DeprecatedContractClass)(nil) + _ ClassOutput = (*contracts.ContractClass)(nil) ) type StorageProofInput struct { - // Required. The hash of the requested block, or number (height) of the requested block, or a block tag + // Required. The hash of the requested block, or number (height) of the + // requested block, or a block tag BlockID BlockID `json:"block_id"` - // Optional. A list of the class hashes for which we want to prove membership in the classes trie + // Optional. A list of the class hashes for which we want to prove + // membership in the classes trie ClassHashes []*felt.Felt `json:"class_hashes,omitempty"` - // Optional. A list of contracts for which we want to prove membership in the global state trie + // Optional. A list of contracts for which we want to prove membership in the + // global state trie ContractAddresses []*felt.Felt `json:"contract_addresses,omitempty"` // Optional. A list of (contract_address, storage_keys) pairs ContractsStorageKeys []ContractStorageKeys `json:"contracts_storage_keys,omitempty"` @@ -57,9 +59,9 @@ type ContractStorageKeys struct { StorageKeys []*felt.Felt `json:"storage_keys"` } -// The requested storage proofs. Note that if a requested leaf has the default value, -// the path to it may end in an edge node whose path is not a prefix of the requested leaf, -// thus effectively proving non-membership +// The requested storage proofs. Note that if a requested leaf has the default +// value, the path to it may end in an edge node whose path is not a prefix of +// the requested leaf, thus effectively proving non-membership type StorageProofResult struct { ClassesProof []NodeHashToNode `json:"classes_proof"` ContractsProof ContractsProof `json:"contracts_proof"` @@ -68,13 +70,15 @@ type StorageProofResult struct { } type ContractsProof struct { - // The nodes in the union of the paths from the contracts tree root to the requested leaves + // The nodes in the union of the paths from the contracts tree root to the + // requested leaves Nodes []NodeHashToNode `json:"nodes"` ContractLeavesData []ContractLeavesData `json:"contract_leaves_data"` } -// The nonce and class hash for each requested contract address, in the order in which -// they appear in the request. These values are needed to construct the associated leaf node +// The nonce and class hash for each requested contract address, in the order +// in which they appear in the request. These values are needed to construct the +// associated leaf node type ContractLeavesData struct { Nonce *felt.Felt `json:"nonce"` ClassHash *felt.Felt `json:"class_hash"` @@ -84,17 +88,20 @@ type ContractLeavesData struct { type GlobalRoots struct { ContractsTreeRoot *felt.Felt `json:"contracts_tree_root"` ClassesTreeRoot *felt.Felt `json:"classes_tree_root"` - // the associated block hash (needed in case the caller used a block tag for the block_id parameter) + // the associated block hash (needed in case the caller used a block tag + // for the block_id parameter) BlockHash *felt.Felt `json:"block_hash"` } -// A node_hash -> node mapping of all the nodes in the union of the paths between the requested leaves and the root +// A node_hash -> node mapping of all the nodes in the union of the paths +// between the requested leaves and the root type NodeHashToNode struct { NodeHash *felt.Felt `json:"node_hash"` Node MerkleNode `json:"node"` } -// A node in the Merkle-Patricia tree, can be a leaf, binary node, or an edge node (EdgeNode or BinaryNode types) +// A node in the Merkle-Patricia tree, can be a leaf, binary node, or an edge +// node (EdgeNode or BinaryNode types) type MerkleNode struct { Type string Data any @@ -143,8 +150,8 @@ func (m *MerkleNode) MarshalJSON() ([]byte, error) { // Represents a path to the highest non-zero descendant node type EdgeNode struct { - // an unsigned integer whose binary representation represents the path from the current node - // to its highest non-zero descendant (bounded by 2^251) + // an unsigned integer whose binary representation represents the path from + // the current node to its highest non-zero descendant (bounded by 2^251) Path NumAsHex `json:"path"` // the length of the path (bounded by 251) Length uint `json:"length"` diff --git a/rpc/types_event.go b/rpc/types_event.go index 1a90579ef..596f6686c 100644 --- a/rpc/types_event.go +++ b/rpc/types_event.go @@ -60,16 +60,19 @@ type EventSubscriptionInput struct { // (Optional) Per key (by position), designate the possible values to be // matched for events to be returned. Empty array designates 'any' value Keys [][]*felt.Felt `json:"keys,omitempty"` - // (Optional) The block to get notifications from, default is latest, limited to 1024 blocks back + // (Optional) The block to get notifications from, default is latest, limited + // to 1024 blocks back SubBlockID SubscriptionBlockID `json:"block_id,omitzero"` // (Optional) The finality status of the most recent events to include. // Only `PRE_CONFIRMED` and `ACCEPTED_ON_L2` are supported. Default is `ACCEPTED_ON_L2`. - // If PRE_CONFIRMED finality is selected, events might appear multiple times, once for each finality status update. + // If PRE_CONFIRMED finality is selected, events might appear multiple times, + // once for each finality status update. FinalityStatus TxnFinalityStatus `json:"finality_status,omitempty"` } // Notification from the server about a new event. -// The event also includes the finality status of the transaction emitting the event. +// The event also includes the finality status of the transaction emitting the +// event. type EmittedEventWithFinalityStatus struct { EmittedEvent FinalityStatus TxnFinalityStatus `json:"finality_status"` diff --git a/rpc/types_trace.go b/rpc/types_trace.go index d97c88932..361751cdd 100644 --- a/rpc/types_trace.go +++ b/rpc/types_trace.go @@ -10,7 +10,8 @@ import ( ) type SimulateTransactionInput struct { - // a sequence of transactions to simulate, running each transaction on the state resulting from applying all the previous ones + // a sequence of transactions to simulate, running each transaction on the + // state resulting from applying all the previous ones Txns []BroadcastTxn `json:"transactions"` BlockID BlockID `json:"block_id"` SimulationFlags []SimulationFlag `json:"simulation_flags"` @@ -19,9 +20,10 @@ type SimulateTransactionInput struct { type SimulationFlag string const ( - SKIP_FEE_CHARGE SimulationFlag = "SKIP_FEE_CHARGE" - // Flags that indicate how to simulate a given transaction. By default, the sequencer behaviour is replicated locally - SKIP_VALIDATE SimulationFlag = "SKIP_VALIDATE" + SkipFeeCharge SimulationFlag = "SKIP_FEE_CHARGE" + // Flags that indicate how to simulate a given transaction. By default, the + // sequencer behaviour is replicated locally + SkipValidate SimulationFlag = "SKIP_VALIDATE" ) type SimulatedTransaction struct { @@ -31,12 +33,11 @@ type SimulatedTransaction struct { type TxnTrace interface{} -//nolint:exhaustruct var ( - _ TxnTrace = InvokeTxnTrace{} - _ TxnTrace = DeclareTxnTrace{} - _ TxnTrace = DeployAccountTxnTrace{} - _ TxnTrace = L1HandlerTxnTrace{} + _ TxnTrace = (*InvokeTxnTrace)(nil) + _ TxnTrace = (*DeclareTxnTrace)(nil) + _ TxnTrace = (*DeployAccountTxnTrace)(nil) + _ TxnTrace = (*L1HandlerTxnTrace)(nil) ) // the execution trace of an invoke transaction @@ -127,9 +128,11 @@ type FnInvocation struct { IsReverted bool `json:"is_reverted"` } -// the resources consumed by an inner call (does not account for state diffs since data is squashed across the transaction) +// the resources consumed by an inner call (does not account for state diffs +// since data is squashed across the transaction) type InnerCallExecutionResources struct { - // l1 gas consumed by this transaction, used for l2-->l1 messages and state updates if blobs are not used + // l1 gas consumed by this transaction, used for l2-->l1 messages and + // state updates if blobs are not used L1Gas uint `json:"l1_gas"` // l2 gas consumed by this transaction, used for computation and calldata L2Gas uint `json:"l2_gas"` @@ -224,7 +227,9 @@ func (txn *Trace) UnmarshalJSON(data []byte) error { if txHashData, ok := dec["transaction_hash"]; ok { txHashString, ok := txHashData.(string) if !ok { - return errors.New("failed to unmarshal transaction hash, transaction_hash is not a string") + return errors.New( + "failed to unmarshal transaction hash, transaction_hash is not a string", + ) } txHash, err = internalUtils.HexToFelt(txHashString) if err != nil { @@ -253,22 +258,22 @@ func (txn *Trace) UnmarshalJSON(data []byte) error { func unmarshalTraceTxn(t interface{}) (TxnTrace, error) { if casted, ok := t.(map[string]interface{}); ok { switch TransactionType(casted["type"].(string)) { - case TransactionType_Declare: + case TransactionTypeDeclare: var txn DeclareTxnTrace err := remarshal(casted, &txn) return txn, err - case TransactionType_DeployAccount: + case TransactionTypeDeployAccount: var txn DeployAccountTxnTrace err := remarshal(casted, &txn) return txn, err - case TransactionType_Invoke: + case TransactionTypeInvoke: var txn InvokeTxnTrace err := remarshal(casted, &txn) return txn, err - case TransactionType_L1Handler: + case TransactionTypeL1Handler: var txn L1HandlerTxnTrace err := remarshal(casted, &txn) diff --git a/rpc/types_transaction.go b/rpc/types_transaction.go index ade869aea..1fa4dae71 100644 --- a/rpc/types_transaction.go +++ b/rpc/types_transaction.go @@ -127,7 +127,8 @@ type ResourceBoundsMapping struct { L2Gas ResourceBounds `json:"l2_gas"` } -// DA_MODE: Specifies a storage domain in Starknet. Each domain has different guarantees regarding availability +// DA_MODE: Specifies a storage domain in Starknet. Each domain has different +// guarantees regarding availability type DataAvailabilityMode string const ( @@ -142,7 +143,10 @@ func (da DataAvailabilityMode) MarshalJSON() ([]byte, error) { case DAModeL1, DAModeL2: return json.Marshal(string(da)) default: - return nil, fmt.Errorf("invalid DataAvailabilityMode: %s, must be either L1 or L2", string(da)) + return nil, fmt.Errorf( + "invalid DataAvailabilityMode: %s, must be either L1 or L2", + string(da), + ) } } @@ -161,6 +165,8 @@ type Resource string // Values used in the Resource Bounds hash calculation // Ref: https://docs.starknet.io/architecture-and-concepts/network-architecture/transactions/#v3_hash_calculation +// +//nolint:lll // The link would be unclickable if we break the line. const ( ResourceL1Gas Resource = "L1_GAS" ResourceL2Gas Resource = "L2_GAS" @@ -196,8 +202,8 @@ func (rb ResourceBounds) Bytes(resource Resource) ([]byte, error) { ), nil } -// DeployTxn The structure of a deploy transaction. Note that this transaction type is deprecated and -// will no longer be supported in future versions +// DeployTxn The structure of a deploy transaction. Note that this transaction type +// is deprecated and will no longer be supported in future versions type DeployTxn struct { // ClassHash The hash of the deployed contract's class ClassHash *felt.Felt `json:"class_hash"` @@ -243,9 +249,10 @@ type DeployAccountTxnV3 struct { FeeMode DataAvailabilityMode `json:"fee_data_availability_mode"` } -// remarshal is a function that takes in an interface{} value 'v' and an interface{} value 'dst'. -// It marshals the 'v' value to JSON using the json.Marshal function and then unmarshals the JSON data -// to 'dst' using the json.Unmarshal function. +// remarshal is a function that takes in an interface{} value 'v' and an +// interface{} value 'dst'. It marshals the 'v' value to JSON using the +// json.Marshal function and then unmarshals the JSON data to 'dst' using the +// json.Unmarshal function. // // Parameters: // - v: The interface{} value to be marshalled @@ -299,7 +306,7 @@ func (v *TransactionVersion) BigInt() (*big.Int, error) { // Handle versions with query bit. // Remove the 0x prefix and convert to big.Int - version, ok := new(big.Int).SetString(string(*v)[2:], 16) //nolint:mnd + version, ok := new(big.Int).SetString(string(*v)[2:], 16) //nolint:mnd // hex base if !ok { return big.NewInt(-1), errors.New(fmt.Sprint("TransactionVersion %i not supported", *v)) } @@ -308,7 +315,8 @@ func (v *TransactionVersion) BigInt() (*big.Int, error) { } // Int returns an integer corresponding to the transaction version. -// For versions with query bit, it returns the base version number (e.g. TransactionV2WithQueryBit returns 2). +// For versions with query bit, it returns the base version number (e.g. +// TransactionV2WithQueryBit returns 2). // Returns -1 for invalid versions. // // Returns: @@ -329,25 +337,32 @@ func (v *TransactionVersion) Int() int { return -1 } -// SubPendingTxnsInput is the optional input of the starknet_subscribeNewTransactionReceipts subscription. +// SubPendingTxnsInput is the optional input of the +// starknet_subscribeNewTransactionReceipts subscription. type SubNewTxnReceiptsInput struct { // Optional: A vector of finality statuses to receive updates for. - // Only `PRE_CONFIRMED` and `ACCEPTED_ON_L2` are supported. Default is `ACCEPTED_ON_L2`. + // Only `PRE_CONFIRMED` and `ACCEPTED_ON_L2` are supported. Default is + // `ACCEPTED_ON_L2`. FinalityStatus []TxnFinalityStatus `json:"finality_status,omitempty"` - // Optional: Filter transaction receipts to only include transactions sent by the specified addresses + // Optional: Filter transaction receipts to only include transactions + // sent by the specified addresses SenderAddress []*felt.Felt `json:"sender_address,omitempty"` } -// SubNewTxnsInput is the optional input of the starknet_subscribeNewTransactions subscription. +// SubNewTxnsInput is the optional input of the +// starknet_subscribeNewTransactions subscription. type SubNewTxnsInput struct { // Optional: A vector of finality statuses to receive updates for. - // Support all transaction statuses, except `ACCEPTED_ON_L1`. Default is `ACCEPTED_ON_L2`. + // Support all transaction statuses, except `ACCEPTED_ON_L1`. Default is + // `ACCEPTED_ON_L2`. FinalityStatus []TxnStatus `json:"finality_status,omitempty"` - // Optional: Filter transaction receipts to only include transactions sent by the specified addresses + // Optional: Filter transaction receipts to only include transactions sent + // by the specified addresses SenderAddress []*felt.Felt `json:"sender_address,omitempty"` } -// TxnWithHashAndStatus is the response of the starknet_subscribeNewTransactions subscription. +// TxnWithHashAndStatus is the response of the +// starknet_subscribeNewTransactions subscription. type TxnWithHashAndStatus struct { // Transaction with hash and status BlockTransaction @@ -381,7 +396,8 @@ func (txn *TxnWithHashAndStatus) UnmarshalJSON(data []byte) error { // UnmarshalJSON unmarshals the data into a BlockTransaction object. // -// It takes a byte slice as the parameter, representing the JSON data to be unmarshalled. +// It takes a byte slice as the parameter, representing the JSON data to be +// unmarshalled. // The function returns an error if the unmarshalling process fails. // // Parameters: @@ -412,7 +428,8 @@ func (blockTxn *BlockTransaction) UnmarshalJSON(data []byte) error { // MarshalJSON marshals the BlockTransaction object into a JSON byte slice. // // It takes a pointer to a BlockTransaction object as the parameter. -// The function returns a byte slice representing the JSON data and an error if the marshalling process fails. +// The function returns a byte slice representing the JSON data and an error if +// the marshalling process fails. func (blockTxn *BlockTransaction) MarshalJSON() ([]byte, error) { // First marshal the transaction to get all its fields txnData, err := json.Marshal(blockTxn.Transaction) diff --git a/rpc/types_transaction_interfaces.go b/rpc/types_transaction_interfaces.go index 2ce199887..90901cc73 100644 --- a/rpc/types_transaction_interfaces.go +++ b/rpc/types_transaction_interfaces.go @@ -29,7 +29,8 @@ var ( _ Transaction = L1HandlerTxn{} ) -// unmarshalTxn unmarshals a given txn as a byte slice and returns a concrete transaction type wrapped in the Transaction interface. +// unmarshalTxn unmarshals a given txn as a byte slice and returns a concrete +// transaction type wrapped in the Transaction interface. // // Parameters: // - data: The transaction to be unmarshaled @@ -46,7 +47,7 @@ func unmarshalTxn(data []byte) (Transaction, error) { } switch TransactionType(txnAsMap["type"].(string)) { - case TransactionType_Declare: + case TransactionTypeDeclare: switch TransactionVersion(txnAsMap["version"].(string)) { case TransactionV0: return unmarshalTxnToType[DeclareTxnV0](data) @@ -57,18 +58,20 @@ func unmarshalTxn(data []byte) (Transaction, error) { case TransactionV3: return unmarshalTxnToType[DeclareTxnV3](data) default: - return nil, errors.New("internal error with Declare transaction version and unmarshalTxn()") + return nil, errors.New( + "internal error with Declare transaction version and unmarshalTxn()", + ) } - case TransactionType_Deploy: + case TransactionTypeDeploy: return unmarshalTxnToType[DeployTxn](data) - case TransactionType_DeployAccount: + case TransactionTypeDeployAccount: switch TransactionVersion(txnAsMap["version"].(string)) { case TransactionV1: return unmarshalTxnToType[DeployAccountTxnV1](data) case TransactionV3: return unmarshalTxnToType[DeployAccountTxnV3](data) } - case TransactionType_Invoke: + case TransactionTypeInvoke: switch TransactionVersion(txnAsMap["version"].(string)) { case TransactionV0: return unmarshalTxnToType[InvokeTxnV0](data) @@ -77,15 +80,16 @@ func unmarshalTxn(data []byte) (Transaction, error) { case TransactionV3: return unmarshalTxnToType[InvokeTxnV3](data) } - case TransactionType_L1Handler: + case TransactionTypeL1Handler: return unmarshalTxnToType[L1HandlerTxn](data) } return nil, fmt.Errorf("unknown transaction type: %v", txnAsMap["type"]) } -// unmarshalTxnToType is a generic function that takes in a byte slice 'data', unmarshals it to a -// concrete transaction of type T, and returns the concrete transaction wrapped in the Transaction interface. +// unmarshalTxnToType is a generic function that takes in a byte slice 'data', +// unmarshals it to a concrete transaction of type T, and returns the concrete +// transaction wrapped in the Transaction interface. func unmarshalTxnToType[T Transaction](data []byte) (T, error) { var resp T diff --git a/rpc/types_transaction_receipt.go b/rpc/types_transaction_receipt.go index 5d26770f2..d2d4b88c3 100644 --- a/rpc/types_transaction_receipt.go +++ b/rpc/types_transaction_receipt.go @@ -28,11 +28,13 @@ type MsgFromL1 struct { Payload []*felt.Felt `json:"payload"` } -// MessageStatus represents the status of a message sent from an L1 transaction to an L2 contract. +// MessageStatus represents the status of a message sent from an L1 transaction +// to an L2 contract. type MessageStatus struct { // The hash of the L1_HANDLER transaction in L2 that contains the message Hash *felt.Felt `json:"transaction_hash"` - // The finality status of the L1_HANDLER transaction, including the case the txn is still in the mempool or + // The finality status of the L1_HANDLER transaction, including the case the txn + // is still in the mempool or // failed validation during the block construction phase FinalityStatus TxnFinalityStatus `json:"finality_status"` // The execution status of the L1_HANDLER transaction @@ -146,16 +148,17 @@ type TransactionReceipt struct { type TransactionType string const ( - TransactionType_Declare TransactionType = "DECLARE" - TransactionType_DeployAccount TransactionType = "DEPLOY_ACCOUNT" - TransactionType_Deploy TransactionType = "DEPLOY" - TransactionType_Invoke TransactionType = "INVOKE" - TransactionType_L1Handler TransactionType = "L1_HANDLER" + TransactionTypeDeclare TransactionType = "DECLARE" + TransactionTypeDeployAccount TransactionType = "DEPLOY_ACCOUNT" + TransactionTypeDeploy TransactionType = "DEPLOY" + TransactionTypeInvoke TransactionType = "INVOKE" + TransactionTypeL1Handler TransactionType = "L1_HANDLER" ) // UnmarshalJSON unmarshals the JSON data into a TransactionType. // -// The function modifies the value of the TransactionType pointer tt based on the unmarshaled data. +// The function modifies the value of the TransactionType pointer tt based on the +// unmarshaled data. // The supported JSON values and their corresponding TransactionType values are: // - "DECLARE" maps to TransactionType_Declare // - "DEPLOY_ACCOUNT" maps to TransactionType_DeployAccount @@ -180,15 +183,15 @@ func (tt *TransactionType) UnmarshalJSON(data []byte) error { switch unquoted { case "DECLARE": - *tt = TransactionType_Declare + *tt = TransactionTypeDeclare case "DEPLOY_ACCOUNT": - *tt = TransactionType_DeployAccount + *tt = TransactionTypeDeployAccount case "DEPLOY": - *tt = TransactionType_Deploy + *tt = TransactionTypeDeploy case "INVOKE": - *tt = TransactionType_Invoke + *tt = TransactionTypeInvoke case "L1_HANDLER": - *tt = TransactionType_L1Handler + *tt = TransactionTypeL1Handler default: return fmt.Errorf("unsupported transaction type: %s", data) } @@ -206,7 +209,8 @@ func (tt TransactionType) MarshalJSON() ([]byte, error) { } type ExecutionResources struct { - // l1 gas consumed by this transaction, used for l2-->l1 messages and state updates if blobs are not used + // l1 gas consumed by this transaction, used for l2-->l1 messages and state + // updates if blobs are not used L1Gas uint `json:"l1_gas"` // data gas consumed by this transaction, 0 if blobs are not used L1DataGas uint `json:"l1_data_gas"` @@ -217,11 +221,11 @@ type ExecutionResources struct { type TxnStatus string const ( - TxnStatus_Received TxnStatus = "RECEIVED" - TxnStatus_Candidate TxnStatus = "CANDIDATE" - TxnStatus_Pre_confirmed TxnStatus = "PRE_CONFIRMED" - TxnStatus_Accepted_On_L2 TxnStatus = "ACCEPTED_ON_L2" - TxnStatus_Accepted_On_L1 TxnStatus = "ACCEPTED_ON_L1" + TxnStatusReceived TxnStatus = "RECEIVED" + TxnStatusCandidate TxnStatus = "CANDIDATE" + TxnStatusPreConfirmed TxnStatus = "PRE_CONFIRMED" + TxnStatusAcceptedOnL2 TxnStatus = "ACCEPTED_ON_L2" + TxnStatusAcceptedOnL1 TxnStatus = "ACCEPTED_ON_L1" ) // Transaction status result, including finality status and execution status @@ -244,15 +248,15 @@ type TransactionReceiptWithBlockInfo struct { BlockNumber uint `json:"block_number,omitempty"` } -func (t *TransactionReceiptWithBlockInfo) MarshalJSON() ([]byte, error) { +func (tr *TransactionReceiptWithBlockInfo) MarshalJSON() ([]byte, error) { aux := &struct { TransactionReceipt BlockHash string `json:"block_hash,omitempty"` BlockNumber uint `json:"block_number,omitempty"` }{ - TransactionReceipt: t.TransactionReceipt, - BlockHash: t.BlockHash.String(), - BlockNumber: t.BlockNumber, + TransactionReceipt: tr.TransactionReceipt, + BlockHash: tr.BlockHash.String(), + BlockNumber: tr.BlockNumber, } return json.Marshal(aux) @@ -266,7 +270,8 @@ func (tr *TransactionReceiptWithBlockInfo) UnmarshalJSON(data []byte) error { return err } - // If the block hash is nil (txn from pre_confirmed block), set it to felt.Zero to avoid nil pointer dereference + // If the block hash is nil (txn from pre_confirmed block), set it to felt.Zero + // to avoid nil pointer dereference if txnResp.BlockHash == nil { txnResp.BlockHash = new(felt.Felt) } diff --git a/rpc/websocket.go b/rpc/websocket.go index ed3af8c15..ab60c2ad1 100644 --- a/rpc/websocket.go +++ b/rpc/websocket.go @@ -9,28 +9,36 @@ import ( ) // Events subscription. -// Creates a WebSocket stream which will fire events for new Starknet events with applied filters. -// Events are emitted for all events from the specified block_id, up to the latest block. -// If PRE_CONFIRMED finality status is provided, events might appear multiple times, for each finality -// status update. If a single event is required, ACCEPTED_ON_L2 must be selected (the default). +// Creates a WebSocket stream which will fire events for new Starknet events +// with applied filters. Events are emitted for all events from the specified +// block_id, up to the latest block. If PRE_CONFIRMED finality status is provided, +// events might appear multiple times, for each finality status update. If a single +// event is required, ACCEPTED_ON_L2 must be selected (the default). // // Parameters: // // - ctx: The context.Context object for controlling the function call // - events: The channel to send the new events to -// - options: The optional input struct containing the optional filters. Set to nil if no filters are needed. +// - options: The optional input struct containing the optional filters. Set to +// nil if no filters are needed. // // Returns: -// - clientSubscription: The client subscription object, used to unsubscribe from the stream and to get errors +// - clientSubscription: The client subscription object, used to unsubscribe from +// the stream and to get errors // - error: An error, if any -func (provider *WsProvider) SubscribeEvents( +func (ws *WsProvider) SubscribeEvents( ctx context.Context, events chan<- *EmittedEventWithFinalityStatus, options *EventSubscriptionInput, ) (*client.ClientSubscription, error) { - sub, err := provider.c.Subscribe(ctx, "starknet", "_subscribeEvents", events, options) + sub, err := ws.c.Subscribe(ctx, "starknet", "_subscribeEvents", events, options) if err != nil { - return nil, rpcerr.UnwrapToRPCErr(err, ErrTooManyKeysInFilter, ErrTooManyBlocksBack, ErrBlockNotFound) + return nil, rpcerr.UnwrapToRPCErr( + err, + ErrTooManyKeysInFilter, + ErrTooManyBlocksBack, + ErrBlockNotFound, + ) } return sub, nil @@ -42,12 +50,14 @@ func (provider *WsProvider) SubscribeEvents( // Parameters: // - ctx: The context.Context object for controlling the function call // - headers: The channel to send the new block headers to -// - blockID (optional): The block to get notifications from, limited to 1024 blocks back. If empty, the latest block will be used +// - blockID (optional): The block to get notifications from, limited to 1024 +// blocks back. If empty, the latest block will be used // // Returns: -// - clientSubscription: The client subscription object, used to unsubscribe from the stream and to get errors +// - clientSubscription: The client subscription object, used to unsubscribe from +// the stream and to get errors // - error: An error, if any -func (provider *WsProvider) SubscribeNewHeads( +func (ws *WsProvider) SubscribeNewHeads( ctx context.Context, headers chan<- *BlockHeader, subBlockID SubscriptionBlockID, @@ -56,10 +66,12 @@ func (provider *WsProvider) SubscribeNewHeads( var err error // if subBlockID is empty, don't send it to the server to avoid it being marshalled as 'null' - if subBlockID == (SubscriptionBlockID{}) { //nolint:exhaustruct - sub, err = provider.c.SubscribeWithSliceArgs(ctx, "starknet", "_subscribeNewHeads", headers) + if subBlockID == (SubscriptionBlockID{}) { //nolint:exhaustruct // Asserting the type + sub, err = ws.c.SubscribeWithSliceArgs(ctx, "starknet", "_subscribeNewHeads", headers) } else { - sub, err = provider.c.SubscribeWithSliceArgs(ctx, "starknet", "_subscribeNewHeads", headers, subBlockID) + sub, err = ws.c.SubscribeWithSliceArgs( + ctx, "starknet", "_subscribeNewHeads", headers, subBlockID, + ) } if err != nil { @@ -70,24 +82,34 @@ func (provider *WsProvider) SubscribeNewHeads( } // New transactions receipts subscription -// Creates a WebSocket stream which will fire events when new transaction receipts are created. -// The endpoint receives a vector of finality statuses. An event is fired for each finality status update. -// It is possible for receipts for pre-confirmed transactions to be received multiple times, or not at all. +// Creates a WebSocket stream which will fire events when new transaction +// receipts are created. The endpoint receives a vector of finality statuses. +// An event is fired for each finality status update. +// It is possible for receipts for pre-confirmed transactions to be received +// multiple times, or not at all. // // Parameters: // - ctx: The context.Context object for controlling the function call // - txnReceipts: The channel to send the new transaction receipts to -// - options: The optional input struct containing the optional filters. Set to nil if no filters are needed. +// - options: The optional input struct containing the optional filters. Set +// to nil if no filters are needed. // // Returns: -// - clientSubscription: The client subscription object, used to unsubscribe from the stream and to get errors +// - clientSubscription: The client subscription object, used to unsubscribe +// from the stream and to get errors // - error: An error, if any -func (provider *WsProvider) SubscribeNewTransactionReceipts( +func (ws *WsProvider) SubscribeNewTransactionReceipts( ctx context.Context, txnReceipts chan<- *TransactionReceiptWithBlockInfo, options *SubNewTxnReceiptsInput, ) (*client.ClientSubscription, error) { - sub, err := provider.c.Subscribe(ctx, "starknet", "_subscribeNewTransactionReceipts", txnReceipts, options) + sub, err := ws.c.Subscribe( + ctx, + "starknet", + "_subscribeNewTransactionReceipts", + txnReceipts, + options, + ) if err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrTooManyAddressesInFilter) } @@ -104,17 +126,19 @@ func (provider *WsProvider) SubscribeNewTransactionReceipts( // Parameters: // - ctx: The context.Context object for controlling the function call // - newTxns: The channel to send the new transactions to -// - options: The optional input struct containing the optional filters. Set to nil if no filters are needed. +// - options: The optional input struct containing the optional filters. Set to nil if +// no filters are needed. // // Returns: -// - clientSubscription: The client subscription object, used to unsubscribe from the stream and to get errors +// - clientSubscription: The client subscription object, used to unsubscribe from +// the stream and to get errors // - error: An error, if any -func (provider *WsProvider) SubscribeNewTransactions( +func (ws *WsProvider) SubscribeNewTransactions( ctx context.Context, newTxns chan<- *TxnWithHashAndStatus, options *SubNewTxnsInput, ) (*client.ClientSubscription, error) { - sub, err := provider.c.Subscribe(ctx, "starknet", "_subscribeNewTransactions", newTxns, options) + sub, err := ws.c.Subscribe(ctx, "starknet", "_subscribeNewTransactions", newTxns, options) if err != nil { return nil, rpcerr.UnwrapToRPCErr(err, ErrTooManyAddressesInFilter) } @@ -123,7 +147,8 @@ func (provider *WsProvider) SubscribeNewTransactions( } // Transaction Status subscription. -// Creates a WebSocket stream which at first fires an event with the current known transaction status, +// Creates a WebSocket stream which at first fires an event with the current known +// transaction status, // followed by events for every transaction status update // // Parameters: @@ -132,14 +157,21 @@ func (provider *WsProvider) SubscribeNewTransactions( // - transactionHash: The transaction hash to fetch status updates for // // Returns: -// - clientSubscription: The client subscription object, used to unsubscribe from the stream and to get errors +// - clientSubscription: The client subscription object, used to unsubscribe from +// the stream and to get errors // - error: An error, if any -func (provider *WsProvider) SubscribeTransactionStatus( +func (ws *WsProvider) SubscribeTransactionStatus( ctx context.Context, newStatus chan<- *NewTxnStatus, transactionHash *felt.Felt, ) (*client.ClientSubscription, error) { - sub, err := provider.c.SubscribeWithSliceArgs(ctx, "starknet", "_subscribeTransactionStatus", newStatus, transactionHash) + sub, err := ws.c.SubscribeWithSliceArgs( + ctx, + "starknet", + "_subscribeTransactionStatus", + newStatus, + transactionHash, + ) if err != nil { return nil, rpcerr.UnwrapToRPCErr(err) } diff --git a/rpc/websocket_external_test.go b/rpc/websocket_external_test.go index d635b0187..1a2b9449b 100644 --- a/rpc/websocket_external_test.go +++ b/rpc/websocket_external_test.go @@ -34,7 +34,13 @@ func setupAcc(t *testing.T, tConfig *rpc.TestConfiguration) (*account.Account, e return nil, fmt.Errorf("failed to convert accountAddress to felt: %w", err) } - acc, err := account.NewAccount(tConfig.Provider, accAddress, tConfig.PubKey, ks, account.CairoV2) + acc, err := account.NewAccount( + tConfig.Provider, + accAddress, + tConfig.PubKey, + ks, + account.CairoV2, + ) if err != nil { return nil, fmt.Errorf("failed to create account: %w", err) } @@ -42,7 +48,7 @@ func setupAcc(t *testing.T, tConfig *rpc.TestConfiguration) (*account.Account, e return acc, nil } -//nolint:tparallel +//nolint:tparallel // I want only sub-tests to run in parallel, but the main test to run sequentially with the others. func TestSubscribeTransactionStatus(t *testing.T) { tests.RunTestOn(t, tests.TestnetEnv) @@ -63,7 +69,10 @@ func TestSubscribeTransactionStatus(t *testing.T) { calldata, err := acc.FmtCalldata([]rpc.FunctionCall{ { // same ERC20 contract as in examples/simpleInvoke - ContractAddress: internalUtils.TestHexToFelt(t, "0x0669e24364ce0ae7ec2864fb03eedbe60cfbc9d1c74438d10fa4b86552907d54"), + ContractAddress: internalUtils.TestHexToFelt( + t, + "0x0669e24364ce0ae7ec2864fb03eedbe60cfbc9d1c74438d10fa4b86552907d54", + ), EntryPointSelector: utils.GetSelectorFromNameFelt("mint"), Calldata: []*felt.Felt{new(felt.Felt).SetUint64(10000), &felt.Zero}, }, @@ -121,11 +130,15 @@ func TestSubscribeTransactionStatus(t *testing.T) { t.Parallel() txnStatus := make(chan *rpc.NewTxnStatus) - sub, err := wsProvider.SubscribeTransactionStatus(context.Background(), txnStatus, txnHash) //nolint:govet - require.NoError(t, err, "Error subscribing to txn status") + sub, innerErr := wsProvider.SubscribeTransactionStatus( + context.Background(), + txnStatus, + txnHash, + ) + require.NoError(t, innerErr, "Error subscribing to txn status") defer sub.Unsubscribe() - expectedStatus := rpc.TxnStatus_Received + expectedStatus := rpc.TxnStatusReceived for { select { @@ -134,29 +147,44 @@ func TestSubscribeTransactionStatus(t *testing.T) { // (e.g: it can go directly from RECEIVED to ACCEPTED_ON_L2), // we'll only check if the txn has been marked at least as received switch txnStatus.Status.FinalityStatus { - case rpc.TxnStatus_Received: + case rpc.TxnStatusReceived: t.Logf("Txn status: %v", txnStatus.Status.FinalityStatus) - assert.Equal(t, expectedStatus, rpc.TxnStatus_Received) + assert.Equal(t, expectedStatus, rpc.TxnStatusReceived) - expectedStatus = rpc.TxnStatus_Candidate - case rpc.TxnStatus_Candidate: + expectedStatus = rpc.TxnStatusCandidate + case rpc.TxnStatusCandidate: t.Logf("Txn status: %v", txnStatus.Status.FinalityStatus) - assert.NotEqual(t, expectedStatus, rpc.TxnStatus_Received, "txn should have been marked as received first") - - expectedStatus = rpc.TxnStatus_Pre_confirmed - case rpc.TxnStatus_Pre_confirmed: + assert.NotEqual( + t, + expectedStatus, + rpc.TxnStatusReceived, + "txn should have been marked as received first", + ) + + expectedStatus = rpc.TxnStatusPreConfirmed + case rpc.TxnStatusPreConfirmed: t.Logf("Txn status: %v", txnStatus.Status.FinalityStatus) - assert.NotEqual(t, expectedStatus, rpc.TxnStatus_Received, "txn should have been marked as received first") - - expectedStatus = rpc.TxnStatus_Accepted_On_L2 - case rpc.TxnStatus_Accepted_On_L2: + assert.NotEqual( + t, + expectedStatus, + rpc.TxnStatusReceived, + "txn should have been marked as received first", + ) + + expectedStatus = rpc.TxnStatusAcceptedOnL2 + case rpc.TxnStatusAcceptedOnL2: t.Logf("Txn status: %v", txnStatus.Status.FinalityStatus) - assert.NotEqual(t, expectedStatus, rpc.TxnStatus_Received, "txn should have been marked as received first") + assert.NotEqual( + t, + expectedStatus, + rpc.TxnStatusReceived, + "txn should have been marked as received first", + ) return } - case err = <-sub.Err(): - t.Fatal("error in subscription: ", err) + case innerErr = <-sub.Err(): + t.Fatal("error in subscription: ", innerErr) } } }) diff --git a/rpc/websocket_test.go b/rpc/websocket_test.go index 1de1bc61f..6e606e5ea 100644 --- a/rpc/websocket_test.go +++ b/rpc/websocket_test.go @@ -33,7 +33,10 @@ func TestSubscribeNewHeads(t *testing.T) { blockNumber, err := provider.BlockNumber(context.Background()) require.NoError(t, err) - latestBlockNumbers := []uint64{blockNumber, blockNumber + 1} // for the case the latest block number is updated + latestBlockNumbers := []uint64{ + blockNumber, + blockNumber + 1, + } // for the case the latest block number is updated testSet := map[tests.TestEnv][]testSetType{ tests.TestnetEnv: { @@ -97,7 +100,11 @@ func TestSubscribeNewHeads(t *testing.T) { wsProvider := testConfig.WsProvider var sub *client.ClientSubscription - sub, err = wsProvider.SubscribeNewHeads(context.Background(), test.headers, test.subBlockID) + sub, err = wsProvider.SubscribeNewHeads( + context.Background(), + test.headers, + test.subBlockID, + ) if sub != nil { defer sub.Unsubscribe() } @@ -134,7 +141,7 @@ func TestSubscribeNewHeads(t *testing.T) { } } -//nolint:gocyclo +//nolint:gocyclo // False positive since it's counting for the entire test, not each sub-test. func TestSubscribeEvents(t *testing.T) { tests.RunTestOn(t, tests.TestnetEnv, tests.IntegrationEnv) @@ -176,7 +183,11 @@ func TestSubscribeEvents(t *testing.T) { wsProvider := testConfig.WsProvider events := make(chan *EmittedEventWithFinalityStatus) - sub, err := wsProvider.SubscribeEvents(context.Background(), events, &EventSubscriptionInput{}) + sub, err := wsProvider.SubscribeEvents( + context.Background(), + events, + &EventSubscriptionInput{}, + ) if sub != nil { defer sub.Unsubscribe() } @@ -206,9 +217,13 @@ func TestSubscribeEvents(t *testing.T) { wsProvider := testConfig.WsProvider events := make(chan *EmittedEventWithFinalityStatus) - sub, err := wsProvider.SubscribeEvents(context.Background(), events, &EventSubscriptionInput{ - SubBlockID: new(SubscriptionBlockID).WithBlockNumber(blockNumber - 1000), - }) + sub, err := wsProvider.SubscribeEvents( + context.Background(), + events, + &EventSubscriptionInput{ + SubBlockID: new(SubscriptionBlockID).WithBlockNumber(blockNumber - 1000), + }, + ) if sub != nil { defer sub.Unsubscribe() } @@ -239,9 +254,13 @@ func TestSubscribeEvents(t *testing.T) { wsProvider := testConfig.WsProvider events := make(chan *EmittedEventWithFinalityStatus) - sub, err := wsProvider.SubscribeEvents(context.Background(), events, &EventSubscriptionInput{ - SubBlockID: new(SubscriptionBlockID).WithLatestTag(), - }) + sub, err := wsProvider.SubscribeEvents( + context.Background(), + events, + &EventSubscriptionInput{ + SubBlockID: new(SubscriptionBlockID).WithLatestTag(), + }, + ) if sub != nil { defer sub.Unsubscribe() } @@ -274,9 +293,13 @@ func TestSubscribeEvents(t *testing.T) { t.Parallel() events := make(chan *EmittedEventWithFinalityStatus) - sub, err := wsProvider.SubscribeEvents(context.Background(), events, &EventSubscriptionInput{ - FinalityStatus: TxnFinalityStatusAcceptedOnL2, - }) + sub, err := wsProvider.SubscribeEvents( + context.Background(), + events, + &EventSubscriptionInput{ + FinalityStatus: TxnFinalityStatusAcceptedOnL2, + }, + ) if sub != nil { defer sub.Unsubscribe() } @@ -305,9 +328,13 @@ func TestSubscribeEvents(t *testing.T) { t.Parallel() events := make(chan *EmittedEventWithFinalityStatus) - sub, err := wsProvider.SubscribeEvents(context.Background(), events, &EventSubscriptionInput{ - FinalityStatus: TxnFinalityStatusPre_confirmed, - }) + sub, err := wsProvider.SubscribeEvents( + context.Background(), + events, + &EventSubscriptionInput{ + FinalityStatus: TxnFinalityStatusPreConfirmed, + }, + ) if sub != nil { defer sub.Unsubscribe() } @@ -331,7 +358,7 @@ func TestSubscribeEvents(t *testing.T) { } switch resp.FinalityStatus { - case TxnFinalityStatusPre_confirmed: + case TxnFinalityStatusPreConfirmed: preConfirmedEventFound = true case TxnFinalityStatusAcceptedOnL2: acceptedOnL2EventFound = true @@ -353,10 +380,14 @@ func TestSubscribeEvents(t *testing.T) { wsProvider := testConfig.WsProvider events := make(chan *EmittedEventWithFinalityStatus) - sub, err := wsProvider.SubscribeEvents(context.Background(), events, &EventSubscriptionInput{ - FromAddress: testSet.fromAddressExample, - SubBlockID: new(SubscriptionBlockID).WithBlockNumber(blockNumber - 1000), - }) + sub, err := wsProvider.SubscribeEvents( + context.Background(), + events, + &EventSubscriptionInput{ + FromAddress: testSet.fromAddressExample, + SubBlockID: new(SubscriptionBlockID).WithBlockNumber(blockNumber - 1000), + }, + ) if sub != nil { defer sub.Unsubscribe() } @@ -389,10 +420,14 @@ func TestSubscribeEvents(t *testing.T) { wsProvider := testConfig.WsProvider events := make(chan *EmittedEventWithFinalityStatus) - sub, err := wsProvider.SubscribeEvents(context.Background(), events, &EventSubscriptionInput{ - Keys: [][]*felt.Felt{{testSet.keyExample}}, - SubBlockID: new(SubscriptionBlockID).WithBlockNumber(blockNumber - 1000), - }) + sub, err := wsProvider.SubscribeEvents( + context.Background(), + events, + &EventSubscriptionInput{ + Keys: [][]*felt.Felt{{testSet.keyExample}}, + SubBlockID: new(SubscriptionBlockID).WithBlockNumber(blockNumber - 1000), + }, + ) if sub != nil { defer sub.Unsubscribe() } @@ -426,12 +461,16 @@ func TestSubscribeEvents(t *testing.T) { wsProvider := testConfig.WsProvider events := make(chan *EmittedEventWithFinalityStatus) - sub, err := wsProvider.SubscribeEvents(context.Background(), events, &EventSubscriptionInput{ - SubBlockID: new(SubscriptionBlockID).WithBlockNumber(blockNumber - 1000), - FromAddress: testSet.fromAddressExample, - Keys: [][]*felt.Felt{{testSet.keyExample}}, - FinalityStatus: TxnFinalityStatusAcceptedOnL2, - }) + sub, err := wsProvider.SubscribeEvents( + context.Background(), + events, + &EventSubscriptionInput{ + SubBlockID: new(SubscriptionBlockID).WithBlockNumber(blockNumber - 1000), + FromAddress: testSet.fromAddressExample, + Keys: [][]*felt.Felt{{testSet.keyExample}}, + FinalityStatus: TxnFinalityStatusAcceptedOnL2, + }, + ) if sub != nil { defer sub.Unsubscribe() } @@ -513,7 +552,7 @@ func TestSubscribeEvents(t *testing.T) { }) } -//nolint:dupl,gocyclo +//nolint:dupl,gocyclo // dupl: The tests are similar, but they are testing different things. //gocyclo: False positive since it's counting for the entire test, not each sub-test. func TestSubscribeNewTransactionReceipts(t *testing.T) { tests.RunTestOn(t, tests.TestnetEnv, tests.IntegrationEnv) @@ -560,7 +599,11 @@ func TestSubscribeNewTransactionReceipts(t *testing.T) { t.Run("test: "+test.description, func(t *testing.T) { t.Parallel() - sub, err := wsProvider.SubscribeNewTransactionReceipts(context.Background(), test.txnReceipts, test.options) + sub, err := wsProvider.SubscribeNewTransactionReceipts( + context.Background(), + test.txnReceipts, + test.options, + ) if test.expectedError != nil { require.EqualError(t, err, test.expectedError.Error()) @@ -575,7 +618,11 @@ func TestSubscribeNewTransactionReceipts(t *testing.T) { select { case resp := <-test.txnReceipts: assert.IsType(t, &TransactionReceiptWithBlockInfo{}, resp) - assert.Equal(t, TxnFinalityStatusAcceptedOnL2, resp.FinalityStatus) // default finality status is ACCEPTED_ON_L2 + assert.Equal( + t, + TxnFinalityStatusAcceptedOnL2, + resp.FinalityStatus, + ) // default finality status is ACCEPTED_ON_L2 return case err := <-sub.Err(): @@ -594,7 +641,11 @@ func TestSubscribeNewTransactionReceipts(t *testing.T) { FinalityStatus: []TxnFinalityStatus{TxnFinalityStatusAcceptedOnL2}, } - sub, err := wsProvider.SubscribeNewTransactionReceipts(context.Background(), txnReceipts, options) + sub, err := wsProvider.SubscribeNewTransactionReceipts( + context.Background(), + txnReceipts, + options, + ) require.NoError(t, err) require.NotNil(t, sub) @@ -628,10 +679,14 @@ func TestSubscribeNewTransactionReceipts(t *testing.T) { txnReceipts := make(chan *TransactionReceiptWithBlockInfo) options := &SubNewTxnReceiptsInput{ - FinalityStatus: []TxnFinalityStatus{TxnFinalityStatusPre_confirmed}, + FinalityStatus: []TxnFinalityStatus{TxnFinalityStatusPreConfirmed}, } - sub, err := wsProvider.SubscribeNewTransactionReceipts(context.Background(), txnReceipts, options) + sub, err := wsProvider.SubscribeNewTransactionReceipts( + context.Background(), + txnReceipts, + options, + ) require.NoError(t, err) require.NotNil(t, sub) @@ -644,7 +699,7 @@ func TestSubscribeNewTransactionReceipts(t *testing.T) { select { case resp := <-txnReceipts: assert.IsType(t, &TransactionReceiptWithBlockInfo{}, resp) - assert.Equal(t, TxnFinalityStatusPre_confirmed, resp.FinalityStatus) + assert.Equal(t, TxnFinalityStatusPreConfirmed, resp.FinalityStatus) assert.Empty(t, resp.BlockHash) assert.NotEmpty(t, resp.BlockNumber) assert.NotEmpty(t, resp.TransactionReceipt) @@ -665,10 +720,17 @@ func TestSubscribeNewTransactionReceipts(t *testing.T) { txnReceipts := make(chan *TransactionReceiptWithBlockInfo) options := &SubNewTxnReceiptsInput{ - FinalityStatus: []TxnFinalityStatus{TxnFinalityStatusPre_confirmed, TxnFinalityStatusAcceptedOnL2}, + FinalityStatus: []TxnFinalityStatus{ + TxnFinalityStatusPreConfirmed, + TxnFinalityStatusAcceptedOnL2, + }, } - sub, err := wsProvider.SubscribeNewTransactionReceipts(context.Background(), txnReceipts, options) + sub, err := wsProvider.SubscribeNewTransactionReceipts( + context.Background(), + txnReceipts, + options, + ) require.NoError(t, err) require.NotNil(t, sub) @@ -686,7 +748,7 @@ func TestSubscribeNewTransactionReceipts(t *testing.T) { assert.NotEmpty(t, resp.BlockNumber) assert.NotEmpty(t, resp.TransactionReceipt) - if resp.FinalityStatus == TxnFinalityStatusPre_confirmed { + if resp.FinalityStatus == TxnFinalityStatusPreConfirmed { preConfirmedReceived = true } @@ -701,7 +763,11 @@ func TestSubscribeNewTransactionReceipts(t *testing.T) { require.NoError(t, err) case <-timeout: - assert.True(t, (preConfirmedReceived && acceptedOnL2Received), "no txns received from both finality statuses") + assert.True( + t, + (preConfirmedReceived && acceptedOnL2Received), + "no txns received from both finality statuses", + ) return } @@ -712,7 +778,10 @@ func TestSubscribeNewTransactionReceipts(t *testing.T) { t.Parallel() // and address currently sending a lot of transactions in Sepolia - randAddress := internalUtils.TestHexToFelt(t, "0x00395a96a5b6343fc0f543692fd36e7034b54c2a276cd1a021e8c0b02aee1f43") + randAddress := internalUtils.TestHexToFelt( + t, + "0x00395a96a5b6343fc0f543692fd36e7034b54c2a276cd1a021e8c0b02aee1f43", + ) provider := testConfig.Provider tempStruct := struct { SenderAddress *felt.Felt `json:"sender_address"` @@ -723,7 +792,11 @@ func TestSubscribeNewTransactionReceipts(t *testing.T) { SenderAddress: []*felt.Felt{randAddress}, } - sub, err := wsProvider.SubscribeNewTransactionReceipts(context.Background(), txnReceipts, options) + sub, err := wsProvider.SubscribeNewTransactionReceipts( + context.Background(), + txnReceipts, + options, + ) require.NoError(t, err) require.NotNil(t, sub) @@ -760,7 +833,7 @@ func TestSubscribeNewTransactionReceipts(t *testing.T) { }) } -//nolint:dupl,gocyclo +//nolint:dupl,gocyclo // dupl: The tests are similar, but they are testing different things. //gocyclo: False positive since it's counting for the entire test, not each sub-test. func TestSubscribeNewTransactions(t *testing.T) { tests.RunTestOn(t, tests.TestnetEnv, tests.IntegrationEnv) @@ -807,7 +880,11 @@ func TestSubscribeNewTransactions(t *testing.T) { t.Run("test: "+test.description, func(t *testing.T) { t.Parallel() - sub, err := wsProvider.SubscribeNewTransactions(context.Background(), test.newTxns, test.options) + sub, err := wsProvider.SubscribeNewTransactions( + context.Background(), + test.newTxns, + test.options, + ) if test.expectedError != nil { require.EqualError(t, err, test.expectedError.Error()) @@ -824,7 +901,11 @@ func TestSubscribeNewTransactions(t *testing.T) { select { case resp := <-test.newTxns: assert.IsType(t, &TxnWithHashAndStatus{}, resp) - assert.Equal(t, TxnStatus_Accepted_On_L2, resp.FinalityStatus) // default finality status is ACCEPTED_ON_L2 + assert.Equal( + t, + TxnStatusAcceptedOnL2, + resp.FinalityStatus, + ) // default finality status is ACCEPTED_ON_L2 return case <-timeout: @@ -844,7 +925,7 @@ func TestSubscribeNewTransactions(t *testing.T) { newTxns := make(chan *TxnWithHashAndStatus) options := &SubNewTxnsInput{ - FinalityStatus: []TxnStatus{TxnStatus_Accepted_On_L2}, + FinalityStatus: []TxnStatus{TxnStatusAcceptedOnL2}, } sub, err := wsProvider.SubscribeNewTransactions(context.Background(), newTxns, options) @@ -861,7 +942,7 @@ func TestSubscribeNewTransactions(t *testing.T) { select { case resp := <-newTxns: assert.IsType(t, &TxnWithHashAndStatus{}, resp) - assert.Equal(t, TxnStatus_Accepted_On_L2, resp.FinalityStatus) + assert.Equal(t, TxnStatusAcceptedOnL2, resp.FinalityStatus) assert.NotEmpty(t, resp.Transaction) assert.NotEmpty(t, resp.Hash) @@ -881,7 +962,7 @@ func TestSubscribeNewTransactions(t *testing.T) { newTxns := make(chan *TxnWithHashAndStatus) options := &SubNewTxnsInput{ - FinalityStatus: []TxnStatus{TxnStatus_Pre_confirmed}, + FinalityStatus: []TxnStatus{TxnStatusPreConfirmed}, } sub, err := wsProvider.SubscribeNewTransactions(context.Background(), newTxns, options) @@ -898,7 +979,7 @@ func TestSubscribeNewTransactions(t *testing.T) { select { case resp := <-newTxns: assert.IsType(t, &TxnWithHashAndStatus{}, resp) - assert.Equal(t, TxnStatus_Pre_confirmed, resp.FinalityStatus) + assert.Equal(t, TxnStatusPreConfirmed, resp.FinalityStatus) assert.NotEmpty(t, resp.Hash) assert.NotEmpty(t, resp.Transaction) @@ -918,7 +999,7 @@ func TestSubscribeNewTransactions(t *testing.T) { newTxns := make(chan *TxnWithHashAndStatus) options := &SubNewTxnsInput{ - FinalityStatus: []TxnStatus{TxnStatus_Pre_confirmed, TxnStatus_Accepted_On_L2}, + FinalityStatus: []TxnStatus{TxnStatusPreConfirmed, TxnStatusAcceptedOnL2}, } sub, err := wsProvider.SubscribeNewTransactions(context.Background(), newTxns, options) @@ -940,11 +1021,11 @@ func TestSubscribeNewTransactions(t *testing.T) { assert.NotEmpty(t, resp.Hash) assert.NotEmpty(t, resp.Transaction) - if resp.FinalityStatus == TxnStatus_Pre_confirmed { + if resp.FinalityStatus == TxnStatusPreConfirmed { preConfirmedReceived = true } - if resp.FinalityStatus == TxnStatus_Accepted_On_L2 { + if resp.FinalityStatus == TxnStatusAcceptedOnL2 { acceptedOnL2Received = true } @@ -954,7 +1035,11 @@ func TestSubscribeNewTransactions(t *testing.T) { case err := <-sub.Err(): require.NoError(t, err) case <-timeout: - assert.True(t, (preConfirmedReceived && acceptedOnL2Received), "no txns received from both finality statuses") + assert.True( + t, + (preConfirmedReceived && acceptedOnL2Received), + "no txns received from both finality statuses", + ) return } @@ -966,7 +1051,12 @@ func TestSubscribeNewTransactions(t *testing.T) { newTxns := make(chan *TxnWithHashAndStatus) options := &SubNewTxnsInput{ - FinalityStatus: []TxnStatus{TxnStatus_Received, TxnStatus_Candidate, TxnStatus_Pre_confirmed, TxnStatus_Accepted_On_L2}, + FinalityStatus: []TxnStatus{ + TxnStatusReceived, + TxnStatusCandidate, + TxnStatusPreConfirmed, + TxnStatusAcceptedOnL2, + }, } sub, err := wsProvider.SubscribeNewTransactions(context.Background(), newTxns, options) @@ -991,16 +1081,16 @@ func TestSubscribeNewTransactions(t *testing.T) { assert.NotEmpty(t, resp.Transaction) switch resp.FinalityStatus { - case TxnStatus_Received: + case TxnStatusReceived: t.Log("RECEIVED txn received") receivedReceived = true - case TxnStatus_Candidate: + case TxnStatusCandidate: t.Log("CANDIDATE txn received") candidateReceived = true - case TxnStatus_Pre_confirmed: + case TxnStatusPreConfirmed: t.Log("PRE_CONFIRMED txn received") preConfirmedReceived = true - case TxnStatus_Accepted_On_L2: + case TxnStatusAcceptedOnL2: t.Log("ACCEPTED_ON_L2 txn received") acceptedOnL2Received = true } @@ -1023,7 +1113,10 @@ func TestSubscribeNewTransactions(t *testing.T) { t.Parallel() // and address currently sending a lot of transactions in Sepolia - randAddress := internalUtils.TestHexToFelt(t, "0x00395a96a5b6343fc0f543692fd36e7034b54c2a276cd1a021e8c0b02aee1f43") + randAddress := internalUtils.TestHexToFelt( + t, + "0x00395a96a5b6343fc0f543692fd36e7034b54c2a276cd1a021e8c0b02aee1f43", + ) provider := testConfig.Provider tempStruct := struct { SenderAddress *felt.Felt `json:"sender_address"` diff --git a/rpc/write.go b/rpc/write.go index f609199af..3721e7ec3 100644 --- a/rpc/write.go +++ b/rpc/write.go @@ -53,7 +53,9 @@ func (provider *Provider) AddDeclareTransaction( declareTransaction *BroadcastDeclareTxnV3, ) (AddDeclareTransactionResponse, error) { var result AddDeclareTransactionResponse - if err := do(ctx, provider.c, "starknet_addDeclareTransaction", &result, declareTransaction); err != nil { + if err := do( + ctx, provider.c, "starknet_addDeclareTransaction", &result, declareTransaction, + ); err != nil { return AddDeclareTransactionResponse{}, rpcerr.UnwrapToRPCErr( err, ErrClassAlreadyDeclared, @@ -83,13 +85,16 @@ func (provider *Provider) AddDeclareTransaction( // - deployAccountTransaction: The deploy account transaction to be added // // Returns: -// - AddDeployAccountTransactionResponse: the response of adding the deploy account transaction or an error +// - AddDeployAccountTransactionResponse: the response of adding the deploy +// account transaction or an error func (provider *Provider) AddDeployAccountTransaction( ctx context.Context, deployAccountTransaction *BroadcastDeployAccountTxnV3, ) (AddDeployAccountTransactionResponse, error) { var result AddDeployAccountTransactionResponse - if err := do(ctx, provider.c, "starknet_addDeployAccountTransaction", &result, deployAccountTransaction); err != nil { + if err := do( + ctx, provider.c, "starknet_addDeployAccountTransaction", &result, deployAccountTransaction, + ); err != nil { return AddDeployAccountTransactionResponse{}, rpcerr.UnwrapToRPCErr( err, ErrInsufficientAccountBalance, diff --git a/rpc/write_test.go b/rpc/write_test.go index 345eed145..1db76d59c 100644 --- a/rpc/write_test.go +++ b/rpc/write_test.go @@ -34,7 +34,10 @@ func TestDeclareTransaction(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { - resp, err := testConfig.Provider.AddDeclareTransaction(context.Background(), &test.DeclareTx) + resp, err := testConfig.Provider.AddDeclareTransaction( + context.Background(), + &test.DeclareTx, + ) if test.ExpectedError != nil { require.Error(t, err) rpcErr, ok := err.(*RPCError) @@ -63,7 +66,7 @@ func TestAddInvokeTransaction(t *testing.T) { tests.MockEnv: { { InvokeTx: BroadcastInvokeTxnV3{ - Type: TransactionType_Invoke, + Type: TransactionTypeInvoke, Version: TransactionV3, Signature: []*felt.Felt{ internalUtils.TestHexToFelt(t, "0x71a9b2cd8a8a6a4ca284dcddcdefc6c4fd20b92c1b201bd9836e4ce376fad16"), @@ -134,7 +137,7 @@ func TestAddDeployAccountTransaction(t *testing.T) { tests.MockEnv: { { DeployTx: BroadcastDeployAccountTxnV3{ - Type: TransactionType_DeployAccount, + Type: TransactionTypeDeployAccount, Version: TransactionV3, ClassHash: internalUtils.TestHexToFelt(t, "0x2338634f11772ea342365abd5be9d9dc8a6f44f159ad782fdebd3db5d969738"), Signature: []*felt.Felt{ @@ -171,7 +174,10 @@ func TestAddDeployAccountTransaction(t *testing.T) { }[tests.TEST_ENV] for _, test := range testSet { - resp, err := testConfig.Provider.AddDeployAccountTransaction(context.Background(), &test.DeployTx) + resp, err := testConfig.Provider.AddDeployAccountTransaction( + context.Background(), + &test.DeployTx, + ) if err != nil { require.Equal(t, err.Error(), test.ExpectedError) } else { diff --git a/typedData/revision.go b/typedata/revision.go similarity index 74% rename from typedData/revision.go rename to typedata/revision.go index 72a91533d..be45a7e02 100644 --- a/typedData/revision.go +++ b/typedata/revision.go @@ -1,4 +1,4 @@ -package typedData +package typedata import ( "errors" @@ -10,8 +10,9 @@ import ( ) var ( - // There is also an array version of each type. The array is defined like this: 'type' + '*' (e.g.: "felt*", "bool*", "string*"...) - revision_0_basic_types []string = []string{ + // There is also an array version of each type. The array is defined like + // this: 'type' + '*' (e.g.: "felt*", "bool*", "string*"...) + revision0BasicTypes []string = []string{ "felt", "bool", "string", // up to 31 ASCII characters @@ -19,13 +20,14 @@ var ( "merkletree", } - // Revision 1 includes all types from Revision 0 plus these. The only difference is that for Revision 1 "string" - // represents an arbitrary size string instead of having a 31 ASCII characters limit in Revision 0; for this limit, + // Revision 1 includes all types from Revision 0 plus these. The only difference is + // that for Revision 1 "string" represents an arbitrary size string instead of having + // a 31 ASCII characters limit in Revision 0; for this limit, // use the new type "shortstring" instead. // // There is also an array version of each type. The array is defined like this: // 'type' + '*' (e.g.: "ClassHash*", "timestamp*", "shortstring*"...) - revision_1_basic_types []string = []string{ + revision1BasicTypes []string = []string{ "enum", "u128", "i128", @@ -36,7 +38,7 @@ var ( } //lint:ignore U1000 Variable used to check Preset types in other pieces of code - revision_1_preset_types []string = []string{ + revision1PresetTypes []string = []string{ "NftId", "TokenAmount", "u256", @@ -48,7 +50,7 @@ var ( RevisionV1 revision ) -//nolint:gochecknoinits +//nolint:gochecknoinits // Setup for the revisions global variables func init() { presetMap := make(map[string]TypeDefinition) @@ -58,7 +60,7 @@ func init() { hashMethod: curve.PedersenArray, hashMerkleMethod: curve.Pedersen, types: RevisionTypes{ - Basic: revision_0_basic_types, + Basic: revision0BasicTypes, Preset: presetMap, }, } @@ -71,7 +73,7 @@ func init() { hashMethod: curve.PoseidonArray, hashMerkleMethod: curve.Poseidon, types: RevisionTypes{ - Basic: append(revision_1_basic_types, revision_0_basic_types...), + Basic: append(revision1BasicTypes, revision0BasicTypes...), Preset: presetMap, }, } @@ -131,15 +133,22 @@ func GetRevision(version uint8) (rev *revision, err error) { } func getRevisionV1PresetTypes() map[string]TypeDefinition { - NftIdEnc, _ := new(felt.Felt).SetString("0xaf7d0f5e34446178d80fadf5ddaaed52347121d2fac19ff184ff508d4776f2") - TokenAmountEnc, _ := new(felt.Felt).SetString("0x14648649d4413eb385eea9ac7e6f2b9769671f5d9d7ad40f7b4aadd67839d4") - u256dEnc, _ := new(felt.Felt).SetString("0x3b143be38b811560b45593fb2a071ec4ddd0a020e10782be62ffe6f39e0e82c") + NftIDEnc, _ := new( + felt.Felt, + ).SetString("0xaf7d0f5e34446178d80fadf5ddaaed52347121d2fac19ff184ff508d4776f2") + TokenAmountEnc, _ := new( + felt.Felt, + ).SetString("0x14648649d4413eb385eea9ac7e6f2b9769671f5d9d7ad40f7b4aadd67839d4") + u256dEnc, _ := new( + felt.Felt, + ).SetString("0x3b143be38b811560b45593fb2a071ec4ddd0a020e10782be62ffe6f39e0e82c") presetTypes := []TypeDefinition{ { - Name: "NftId", - Encoding: NftIdEnc, - EncoddingString: `"NftId"("collection_address":"ContractAddress","token_id":"u256")"u256"("low":"u128","high":"u128")`, + Name: "NftId", + Encoding: NftIDEnc, + EncoddingString: `"NftId"("collection_address":"ContractAddress", + "token_id":"u256")"u256"("low":"u128","high":"u128")`, SingleEncString: `"NftId"("collection_address":"ContractAddress","token_id":"u256")`, ReferencedTypesEnc: []string{`"u256"("low":"u128","high":"u128")`}, Parameters: []TypeParameter{ @@ -156,9 +165,10 @@ func getRevisionV1PresetTypes() map[string]TypeDefinition { }, }, { - Name: "TokenAmount", - Encoding: TokenAmountEnc, - EncoddingString: `"TokenAmount"("token_address":"ContractAddress","amount":"u256")"u256"("low":"u128","high":"u128")`, + Name: "TokenAmount", + Encoding: TokenAmountEnc, + EncoddingString: `"TokenAmount"("token_address":"ContractAddress","amount":"u256") + "u256"("low":"u128","high":"u128")`, SingleEncString: `"TokenAmount"("token_address":"ContractAddress","amount":"u256")`, ReferencedTypesEnc: []string{`"u256"("low":"u128","high":"u128")`}, Parameters: []TypeParameter{ @@ -208,9 +218,9 @@ func getRevisionV1PresetTypes() map[string]TypeDefinition { func isStandardType(typeName string) bool { typeName, _ = strings.CutSuffix(typeName, "*") - if slices.Contains(revision_0_basic_types, typeName) || - slices.Contains(revision_1_basic_types, typeName) || - slices.Contains(revision_1_preset_types, typeName) { + if slices.Contains(revision0BasicTypes, typeName) || + slices.Contains(revision1BasicTypes, typeName) || + slices.Contains(revision1PresetTypes, typeName) { return true } @@ -221,8 +231,8 @@ func isStandardType(typeName string) bool { func isBasicType(typeName string) bool { typeName, _ = strings.CutSuffix(typeName, "*") - if slices.Contains(revision_0_basic_types, typeName) || - slices.Contains(revision_1_basic_types, typeName) { + if slices.Contains(revision0BasicTypes, typeName) || + slices.Contains(revision1BasicTypes, typeName) { return true } @@ -233,5 +243,5 @@ func isBasicType(typeName string) bool { func isPresetType(typeName string) bool { typeName, _ = strings.CutSuffix(typeName, "*") - return slices.Contains(revision_1_preset_types, typeName) + return slices.Contains(revision1PresetTypes, typeName) } diff --git a/typedData/testData/allInOne.json b/typedata/testData/allInOne.json similarity index 100% rename from typedData/testData/allInOne.json rename to typedata/testData/allInOne.json diff --git a/typedData/testData/avnu_paymaster_invoke.json b/typedata/testData/avnu_paymaster_invoke.json similarity index 100% rename from typedData/testData/avnu_paymaster_invoke.json rename to typedata/testData/avnu_paymaster_invoke.json diff --git a/typedData/testData/baseExample.json b/typedata/testData/baseExample.json similarity index 100% rename from typedData/testData/baseExample.json rename to typedata/testData/baseExample.json diff --git a/typedData/testData/example_array.json b/typedata/testData/example_array.json similarity index 100% rename from typedData/testData/example_array.json rename to typedata/testData/example_array.json diff --git a/typedData/testData/example_baseTypes.json b/typedata/testData/example_baseTypes.json similarity index 100% rename from typedData/testData/example_baseTypes.json rename to typedata/testData/example_baseTypes.json diff --git a/typedData/testData/example_enum.json b/typedata/testData/example_enum.json similarity index 100% rename from typedData/testData/example_enum.json rename to typedata/testData/example_enum.json diff --git a/typedData/testData/example_enumNested.json b/typedata/testData/example_enumNested.json similarity index 100% rename from typedData/testData/example_enumNested.json rename to typedata/testData/example_enumNested.json diff --git a/typedData/testData/example_presetTypes.json b/typedata/testData/example_presetTypes.json similarity index 100% rename from typedData/testData/example_presetTypes.json rename to typedata/testData/example_presetTypes.json diff --git a/typedData/testData/mail_StructArray.json b/typedata/testData/mail_StructArray.json similarity index 100% rename from typedData/testData/mail_StructArray.json rename to typedata/testData/mail_StructArray.json diff --git a/typedData/testData/session_MerkleTree.json b/typedata/testData/session_MerkleTree.json similarity index 100% rename from typedData/testData/session_MerkleTree.json rename to typedata/testData/session_MerkleTree.json diff --git a/typedData/testData/v1Nested.json b/typedata/testData/v1Nested.json similarity index 100% rename from typedData/testData/v1Nested.json rename to typedata/testData/v1Nested.json diff --git a/typedData/typedData.go b/typedata/typedData.go similarity index 83% rename from typedData/typedData.go rename to typedata/typedData.go index 10e915866..06e0ee4e7 100644 --- a/typedData/typedData.go +++ b/typedata/typedData.go @@ -1,4 +1,4 @@ -package typedData +package typedata import ( "bytes" @@ -29,12 +29,13 @@ type TypedData struct { type Domain struct { Name string `json:"name"` Version string `json:"version"` - ChainId string `json:"chainId"` + ChainID string `json:"chainId"` Revision uint8 `json:"revision,omitempty"` - // Flags to deal with edge cases, used to marshal the `Domain` exactly as it is in the original JSON. - hasStringChainId bool `json:"-"` - hasOldChainIdName bool `json:"-"` + // Flags to deal with edge cases, used to marshal the `Domain` exactly + // as it is in the original JSON. + hasStringChainID bool `json:"-"` + hasOldChainIDName bool `json:"-"` HasStringRevision bool `json:"-"` } @@ -64,7 +65,12 @@ type TypeParameter struct { // Returns: // - td: a pointer to the newly created TypedData instance. // - err: an error if any occurred during the creation of the TypedData. -func NewTypedData(types []TypeDefinition, primaryType string, domain Domain, message []byte) (td *TypedData, err error) { +func NewTypedData( + types []TypeDefinition, + primaryType string, + domain Domain, + message []byte, +) (td *TypedData, err error) { // types typesMap := make(map[string]TypeDefinition) for _, typeDef := range types { @@ -105,7 +111,10 @@ func NewTypedData(types []TypeDefinition, primaryType string, domain Domain, mes for _, typeDef := range typesMap { if typeDef.EncoddingString == "" { - return td, fmt.Errorf("'encodeTypes' failed: type '%s' doesn't have encode value", typeDef.Name) + return td, fmt.Errorf( + "'encodeTypes' failed: type '%s' doesn't have encode value", + typeDef.Name, + ) } } @@ -129,6 +138,8 @@ func NewTypedData(types []TypeDefinition, primaryType string, domain Domain, mes // // Returns: // - hash: A pointer to a felt.Felt representing the calculated hash. +// +//nolint:lll // The docs link would be unclickable if we break the line. func (td *TypedData) GetMessageHash(account string) (hash *felt.Felt, err error) { // A signed_data is equal to: encode(PREFIX_MESSAGE, Enc[domain_separator], account, Enc[message]) @@ -165,15 +176,21 @@ func (td *TypedData) GetMessageHash(account string) (hash *felt.Felt, err error) // - typeName: the name of the type to be hashed. // - context: optional context strings to be included in the hash calculation. // -// You can use 'context' to specify the path of the type you want to hash. Example: if you want to hash the type "ExampleInner" -// that is within the "Example" primary type with the name of "example_inner", you can specify the context as ["example_inner"]. -// If "ExampleInner" has a parameter with the name of "example_inner_inner" that you want to know the hash, you can specify the context +// You can use 'context' to specify the path of the type you want to hash. +// Example: if you want to hash the type "ExampleInner" that is within the "Example" +// primary type with the name of "example_inner", you can specify the context +// as ["example_inner"]. +// If "ExampleInner" has a parameter with the name of "example_inner_inner" that +// you want to know the hash, you can specify the context // as ["example_inner", "example_inner_inner"]. // // Returns: // - hash: A pointer to a felt.Felt representing the calculated hash. // - err: an error if any occurred during the hash calculation. -func (td *TypedData) GetStructHash(typeName string, context ...string) (hash *felt.Felt, err error) { +func (td *TypedData) GetStructHash( + typeName string, + context ...string, +) (hash *felt.Felt, err error) { typeDef, ok := td.Types[typeName] if !ok { if typeDef, ok = td.Revision.Types().Preset[typeName]; !ok { @@ -188,7 +205,8 @@ func (td *TypedData) GetStructHash(typeName string, context ...string) (hash *fe return td.Revision.HashMethod(append([]*felt.Felt{typeDef.Encoding}, encTypeData...)...), nil } -// shortGetStructHash is a helper function that calculates the hash of a struct type and its respective data. +// shortGetStructHash is a helper function that calculates the hash of a +// struct type and its respective data. func shortGetStructHash( typeDef *TypeDefinition, typedData *TypedData, @@ -201,8 +219,9 @@ func shortGetStructHash( return hash, err } - // This is not correct according to the SNIP-12 specification, but in order to be compatible with the Starknet.js library - // (and consequently other libraries and dapps), it will be kept this way until Starknet.js is updated. + // This is not correct according to the SNIP-12 specification, but in order to be + // compatible with the Starknet.js library (and consequently other libraries and dapps), + // it will be kept this way until Starknet.js is updated. // Ref: https://github.com/starknet-io/starknet.js/pull/1292 // Ref: https://github.com/starknet-io/starknet.js/issues/1278 // TODO: remove this once Starknet.js is updated. @@ -210,7 +229,8 @@ func shortGetStructHash( return typedData.Revision.HashMethod(encTypeData...), nil } - return typedData.Revision.HashMethod(append([]*felt.Felt{typeDef.Encoding}, encTypeData...)...), nil + return typedData.Revision.HashMethod( + append([]*felt.Felt{typeDef.Encoding}, encTypeData...)...), nil } // GetTypeHash returns the hash of the given type. @@ -275,7 +295,10 @@ func encodeTypes( if isPresetType(singleTypeName) { typeEnc, ok := revision.Types().Preset[singleTypeName] if !ok { - return fmt.Errorf("error trying to get the type definition of '%s'", singleTypeName) + return fmt.Errorf( + "error trying to get the type definition of '%s'", + singleTypeName, + ) } *customTypesStringEnc = append( *customTypesStringEnc, @@ -287,7 +310,9 @@ func encodeTypes( if innerNewTypeDef := types[singleTypeName]; innerNewTypeDef.SingleEncString != "" { *customTypesStringEnc = append( *customTypesStringEnc, - append([]string{innerNewTypeDef.SingleEncString}, innerNewTypeDef.ReferencedTypesEnc...)...) + append( + []string{innerNewTypeDef.SingleEncString}, + innerNewTypeDef.ReferencedTypesEnc...)...) return nil } @@ -299,7 +324,9 @@ func encodeTypes( *customTypesStringEnc = append( *customTypesStringEnc, - append([]string{innerNewTypeDef.SingleEncString}, innerNewTypeDef.ReferencedTypesEnc...)...) + append( + []string{innerNewTypeDef.SingleEncString}, + innerNewTypeDef.ReferencedTypesEnc...)...) types[singleTypeName] = innerNewTypeDef return nil @@ -324,7 +351,13 @@ func encodeTypes( fullTypeName += `,` } } - buf.WriteString(fmt.Sprintf(quotationMark+"%s"+quotationMark+":"+`(`+"%s"+`)`, param.Name, fullTypeName)) + buf.WriteString( + fmt.Sprintf( + quotationMark+"%s"+quotationMark+":"+`(`+"%s"+`)`, + param.Name, + fullTypeName, + ), + ) for _, typeNam := range typesArr { err = verifyTypeName(TypeParameter{Type: typeNam, Name: "", Contains: ""}) @@ -340,13 +373,19 @@ func encodeTypes( return "", fmt.Errorf("missing 'contains' value from '%s'", param.Name) } currentTypeName = param.Contains - err = verifyTypeName(TypeParameter{Type: currentTypeName, Name: "", Contains: ""}, true) + err = verifyTypeName( + TypeParameter{Type: currentTypeName, Name: "", Contains: ""}, true, + ) if err != nil { return "", err } } - buf.WriteString(fmt.Sprintf(quotationMark+"%s"+quotationMark+":"+quotationMark+"%s"+quotationMark, param.Name, currentTypeName)) + buf.WriteString(fmt.Sprintf( + quotationMark+"%s"+quotationMark+":"+quotationMark+"%s"+quotationMark, + param.Name, + currentTypeName, + )) err = verifyTypeName(param) if err != nil { @@ -414,7 +453,11 @@ func encodeTypes( } // EncodeData encodes the given type definition using the TypedData struct. -func EncodeData(typeDef *TypeDefinition, td *TypedData, context ...string) (enc []*felt.Felt, err error) { +func EncodeData( + typeDef *TypeDefinition, + td *TypedData, + context ...string, +) (enc []*felt.Felt, err error) { if typeDef.Name == "StarkNetDomain" || typeDef.Name == "StarknetDomain" { domainMap := make(map[string]any) domainBytes, err := json.Marshal(td.Domain) @@ -443,7 +486,8 @@ func EncodeData(typeDef *TypeDefinition, td *TypedData, context ...string) (enc return encodeData(typeDef, td, td.Message, false, context...) } -// encodeData is a helper function that encodes the given type definition using the TypedData struct. +// encodeData is a helper function that encodes the given type +// definition using the TypedData struct. // // Parameters: // - typeDef: a pointer to the TypeDefinition representing the type to be encoded. @@ -472,7 +516,10 @@ func encodeData( for _, paramName := range context { value, ok := data[paramName] if !ok { - return enc, fmt.Errorf("context error: parameter '%s' not found in the data map", paramName) + return enc, fmt.Errorf( + "context error: parameter '%s' not found in the data map", + paramName, + ) } newData, ok := value.(map[string]any) if !ok { @@ -485,11 +532,28 @@ func encodeData( // helper functions verifyType := func(param TypeParameter, data any, isEnum bool) (result *felt.Felt, err error) { // helper functions - var handleStandardTypes func(param TypeParameter, data any, rev *revision) (resp *felt.Felt, err error) - var handleObjectTypes func(typeDef *TypeDefinition, data any, isEnum ...bool) (resp *felt.Felt, err error) - var handleArrays func(param TypeParameter, data any, rev *revision, isMerkle ...bool) (resp *felt.Felt, err error) - - handleStandardTypes = func(param TypeParameter, data any, rev *revision) (resp *felt.Felt, err error) { + var handleStandardTypes func( + param TypeParameter, + data any, + rev *revision, + ) (resp *felt.Felt, err error) + var handleObjectTypes func( + typeDef *TypeDefinition, + data any, + isEnum ...bool, + ) (resp *felt.Felt, err error) + var handleArrays func( + param TypeParameter, + data any, + rev *revision, + isMerkle ...bool, + ) (resp *felt.Felt, err error) + + handleStandardTypes = func( + param TypeParameter, + data any, + rev *revision, + ) (resp *felt.Felt, err error) { switch param.Type { case "merkletree": tempParam := TypeParameter{ @@ -521,7 +585,10 @@ func encodeData( case "NftId", "TokenAmount", "u256": typeDef, ok := rev.Types().Preset[param.Type] if !ok { - return resp, fmt.Errorf("error trying to get the type definition of '%s'", param.Type) + return resp, fmt.Errorf( + "error trying to get the type definition of '%s'", + param.Type, + ) } resp, err := handleObjectTypes(&typeDef, data) if err != nil { @@ -539,10 +606,17 @@ func encodeData( } } - handleObjectTypes = func(typeDef *TypeDefinition, data any, isEnum ...bool) (resp *felt.Felt, err error) { + handleObjectTypes = func( + typeDef *TypeDefinition, + data any, + isEnum ...bool, + ) (resp *felt.Felt, err error) { mapData, ok := data.(map[string]any) if !ok { - return resp, fmt.Errorf("error trying to convert the value of '%s' to an map", typeDef) + return resp, fmt.Errorf( + "error trying to convert the value of '%s' to an map", + typeDef, + ) } if len(isEnum) != 0 && isEnum[0] { @@ -557,8 +631,14 @@ func encodeData( return resp, nil } - handleArrays = func(param TypeParameter, data any, rev *revision, isMerkle ...bool) (resp *felt.Felt, err error) { + handleArrays = func( + param TypeParameter, + data any, + rev *revision, + isMerkle ...bool, + ) (resp *felt.Felt, err error) { var handleMerkleTree func(felts []*felt.Felt) *felt.Felt + //nolint:lll // The link would be unclickable if we break the line. // ref https://github.com/starknet-io/starknet.js/blob/3cfdd8448538128bf9fd158d2e87be20310a69e3/src/utils/merkle.ts#L41 handleMerkleTree = func(felts []*felt.Felt) *felt.Felt { if len(felts) == 1 { @@ -579,7 +659,10 @@ func encodeData( dataArray, ok := data.([]any) if !ok { - return resp, fmt.Errorf("error trying to convert the value of '%s' to an array", param.Name) + return resp, fmt.Errorf( + "error trying to convert the value of '%s' to an array", + param.Name, + ) } localEncode := []*felt.Felt{} singleParamType, _ := strings.CutSuffix(param.Type, "*") @@ -587,7 +670,11 @@ func encodeData( if isBasicType(singleParamType) { for _, item := range dataArray { innerResp, err := handleStandardTypes( - TypeParameter{Name: param.Name, Type: singleParamType, Contains: param.Contains}, + TypeParameter{ + Name: param.Name, + Type: singleParamType, + Contains: param.Contains, + }, item, rev, ) @@ -607,7 +694,10 @@ func encodeData( typeDef, ok = typedData.Types[singleParamType] } if !ok { - return resp, fmt.Errorf("error trying to get the type definition of '%s'", singleParamType) + return resp, fmt.Errorf( + "error trying to get the type definition of '%s'", + singleParamType, + ) } for _, item := range dataArray { @@ -672,7 +762,10 @@ func encodeData( // check if it's the selected enum option if !exists { if paramIndex == len(typeDef.Parameters)-1 { - return enc, fmt.Errorf("no enum option selected for '%s', the data is not valid", typeDef.Name) + return enc, fmt.Errorf( + "no enum option selected for '%s', the data is not valid", + typeDef.Name, + ) } continue @@ -680,10 +773,16 @@ func encodeData( dataArr, ok := value.([]any) if !ok { - return enc, fmt.Errorf("error trying to convert the data value of '%s' to an array", param.Name) + return enc, fmt.Errorf( + "error trying to convert the data value of '%s' to an array", + param.Name, + ) } - enc = append(enc, new(felt.Felt).SetUint64(uint64(paramIndex))) + enc = append( + enc, + new(felt.Felt).SetUint64(uint64(paramIndex)), //nolint:gosec // Never underflows + ) if len(dataArr) == 0 { enc = append(enc, &felt.Zero) @@ -694,7 +793,11 @@ func encodeData( typesArr := typeNameRegexp.FindAllString(param.Type, -1) for i, typeName := range typesArr { - resp, err := verifyType(TypeParameter{Type: typeName, Name: "", Contains: ""}, dataArr[i], false) + resp, err := verifyType( + TypeParameter{Type: typeName, Name: "", Contains: ""}, + dataArr[i], + false, + ) if err != nil { return enc, err } @@ -860,7 +963,10 @@ func (td *TypedData) UnmarshalJSON(data []byte) error { } // types - rawTypes, err := internalUtils.GetAndUnmarshalJSONFromMap[map[string]json.RawMessage](dec, "types") + rawTypes, err := internalUtils.GetAndUnmarshalJSONFromMap[map[string]json.RawMessage]( + dec, + "types", + ) if err != nil { return err } @@ -914,7 +1020,10 @@ func (domain *Domain) UnmarshalJSON(data []byte) error { getField := func(fieldName string) (string, error) { value, ok := dec[fieldName] if !ok { - return "", fmt.Errorf("error getting the value of '%s' from 'domain' JSON field", fieldName) + return "", fmt.Errorf( + "error getting the value of '%s' from 'domain' JSON field", + fieldName, + ) } return fmt.Sprintf("%v", value), nil @@ -952,7 +1061,7 @@ func (domain *Domain) UnmarshalJSON(data []byte) error { // Custom logic to handle the `chainId` field, // used to marshal the ChainId exactly as it is in the original JSON. - rawChainId, ok := dec["chainId"] + rawChainID, ok := dec["chainId"] if !ok { err = errors.New("error getting the value of 'chainId' from 'domain' JSON field") if numRevision == 1 { @@ -961,32 +1070,32 @@ func (domain *Domain) UnmarshalJSON(data []byte) error { // `chain_id` was also used in the past, so we check for it if the `chainId` field is not found // ref: https://community.starknet.io/t/signing-transactions-and-off-chain-messages/66 - rawChainId, ok = dec["chain_id"] + rawChainID, ok = dec["chain_id"] if !ok { err2 := errors.New("error getting the value of 'chain_id' from 'domain' JSON field") return fmt.Errorf("%w: %w", err, err2) } - domain.hasOldChainIdName = true + domain.hasOldChainIDName = true } - switch rawChainId.(type) { + switch rawChainID.(type) { case string: - domain.hasStringChainId = true + domain.hasStringChainID = true case float64: - domain.hasStringChainId = false + domain.hasStringChainID = false } - chainId := fmt.Sprintf("%v", rawChainId) + chainID := fmt.Sprintf("%v", rawChainID) // Final step *domain = Domain{ Name: name, Version: version, - ChainId: chainId, + ChainID: chainID, Revision: uint8(numRevision), - hasStringChainId: domain.hasStringChainId, - hasOldChainIdName: domain.hasOldChainIdName, + hasStringChainID: domain.hasStringChainID, + hasOldChainIDName: domain.hasOldChainIDName, HasStringRevision: domain.HasStringRevision, } @@ -996,15 +1105,15 @@ func (domain *Domain) UnmarshalJSON(data []byte) error { // MarshalJSON implements the json.Marshaler interface for Domain. // Some logic was added to marshal the `Domain` exactly as it is in the original JSON. func (domain Domain) MarshalJSON() ([]byte, error) { - var chainId any + var chainID any var revision any var err error // E.g: if it's `1`, we will marshal it as `1`, not `"1"`. - if domain.hasStringChainId { - chainId = domain.ChainId + if domain.hasStringChainID { + chainID = domain.ChainID } else { - chainId, err = strconv.Atoi(domain.ChainId) + chainID, err = strconv.Atoi(domain.ChainID) if err != nil { return nil, fmt.Errorf("cannot parse 'chain_id' value: %w", err) } @@ -1022,26 +1131,27 @@ func (domain Domain) MarshalJSON() ([]byte, error) { // The purpose here is to marshal the `Domain` exactly as it is in the original JSON. // This is achieved by having two chainId fields, one for the old name and one for the new name, - // and using the `omitempty` tag to only include one of them, the one that is the same as the original JSON. + // and using the `omitempty` tag to only include one of them, the one that is the + // same as the original JSON. // Similar for the `Revision` field. var temp struct { Name string `json:"name"` Version string `json:"version"` - ChainIdOld any `json:"chain_id,omitempty"` // old chainId json name - ChainIdNew any `json:"chainId,omitempty"` // new chainId json name + ChainIDOld any `json:"chain_id,omitempty"` // old chainId json name + ChainIDNew any `json:"chainId,omitempty"` // new chainId json name Revision any `json:"revision,omitempty"` } temp.Name = domain.Name temp.Version = domain.Version temp.Revision = revision - if domain.hasOldChainIdName { - temp.ChainIdOld = chainId + if domain.hasOldChainIDName { + temp.ChainIDOld = chainID return json.Marshal(temp) } - temp.ChainIdNew = chainId + temp.ChainIDNew = chainID return json.Marshal(temp) } diff --git a/typedData/typedData_test.go b/typedata/typedData_test.go similarity index 99% rename from typedData/typedData_test.go rename to typedata/typedData_test.go index 21bc2052c..8a8ab9d9c 100644 --- a/typedData/typedData_test.go +++ b/typedata/typedData_test.go @@ -1,4 +1,4 @@ -package typedData +package typedata import ( "encoding/json" diff --git a/utils/data.go b/utils/data.go index a4fe3072c..16a040250 100644 --- a/utils/data.go +++ b/utils/data.go @@ -2,7 +2,8 @@ package utils import internalUtils "github.com/NethermindEth/starknet.go/internal/utils" -// UnmarshalJSONFileToType reads a JSON file at the given path and unmarshals it into the specified type T. +// UnmarshalJSONFileToType reads a JSON file at the given path and unmarshals it +// into the specified type T. // If any error occurs during file reading or unmarshalling, it returns an error. // // Parameters: diff --git a/utils/felt.go b/utils/felt.go index 8ad8fbb28..4194f2cab 100644 --- a/utils/felt.go +++ b/utils/felt.go @@ -32,9 +32,10 @@ func HexToFelt(hex string) (*felt.Felt, error) { // HexArrToFelt converts an array of hexadecimal strings to an array of felt objects. // -// The function iterates over each element in the hexArr array and calls the HexToFelt function to convert -// each hexadecimal value to a felt object. -// If any error occurs during the conversion, the function will return nil and the corresponding error. +// The function iterates over each element in the hexArr array and calls the HexToFelt +// function to convert each hexadecimal value to a felt object. +// If any error occurs during the conversion, the function will return nil and the +// corresponding error. // Otherwise, it appends the converted felt object to the feltArr array. // Finally, the function returns the feltArr array containing all the converted felt objects. // @@ -95,21 +96,20 @@ func FeltArrToStringArr(f []*felt.Felt) []string { // StringToByteArrFelt converts string to array of Felt objects. // The returned array of felts will be of the format // -// [number of felts with 31 characters in length, 31 byte felts..., pending word with max size of 30 bytes, pending words bytes size] -// +// [number of felts with 31 characters in length, 31 byte felts..., pending word with +// max size of 30 bytes, pending words bytes size] // For further explanation, refer the [article] // // Parameters: -// // - s: string/bytearray to convert // // Returns: -// // - []*felt.Felt: the array of felt.Felt objects -// // - error: an error, if any // // [article]: https://docs.starknet.io/architecture-and-concepts/smart-contracts/serialization-of-cairo-types/#serialization_of_byte_arrays +// +//nolint:lll // The link would be unclickable if we break the line. func StringToByteArrFelt(s string) ([]*felt.Felt, error) { return internalUtils.StringToByteArrFelt(s) } @@ -117,21 +117,20 @@ func StringToByteArrFelt(s string) ([]*felt.Felt, error) { // ByteArrFeltToString converts array of Felts to string. // The input array of felts will be of the format // -// [number of felts with 31 characters in length, 31 byte felts..., pending word with max size of 30 bytes, pending words bytes size] -// +// [number of felts with 31 characters in length, 31 byte felts..., pending word with +// max size of 30 bytes, pending words bytes size] // For further explanation, refer the [article] // // Parameters: -// // - []*felt.Felt: the array of felt.Felt objects // // Returns: -// // - s: string/bytearray -// // - error: an error, if any // // [article]: https://docs.starknet.io/architecture-and-concepts/smart-contracts/serialization-of-cairo-types/#serialization_of_byte_arrays +// +//nolint:lll // The link would be unclickable if we break the line. func ByteArrFeltToString(arr []*felt.Felt) (string, error) { return internalUtils.ByteArrFeltToString(arr) } @@ -162,7 +161,8 @@ func HexToU256Felt(hexStr string) ([]*felt.Felt, error) { return internalUtils.HexToU256Felt(hexStr) } -// U256FeltToHex converts a Cairo u256 representation (two felt.Felt values) back to a hexadecimal string. +// U256FeltToHex converts a Cairo u256 representation (two felt.Felt values) +// back to a hexadecimal string. // The Cairo u256 is represented as two felt.Felt values: // - The first felt.Felt contains the 128 least significant bits (low part) // - The second felt.Felt contains the 128 most significant bits (high part) diff --git a/utils/keccak.go b/utils/keccak.go index 6ed888ab6..242ccae46 100644 --- a/utils/keccak.go +++ b/utils/keccak.go @@ -191,17 +191,20 @@ func ComputeFact(programHash *big.Int, programOutputs []*big.Int) *big.Int { return internalUtils.ComputeFact(programHash, programOutputs) } -// SplitFactStr splits a given fact, with maximum 256 bits size, into two parts (felts): fact_low and fact_high. +// SplitFactStr splits a given fact, with maximum 256 bits size, into two +// parts (felts): fact_low and fact_high. // -// The function takes a fact string as input and converts it to a big number using the HexToBN function. -// It then converts the big number to bytes using the Bytes method. -// If the length of the bytes is less than 32, it pads the bytes with zeros using the bytes.Repeat method. +// The function takes a fact string as input and converts it to a big number +// using the HexToBN function. It then converts the big number to bytes using +// the Bytes method. If the length of the bytes is less than 32, it pads the +// bytes with zeros using the bytes.Repeat method. // The padded bytes are then appended to the original bytes. -// The function then extracts the low part of the bytes by taking the last 16 bytes and converts it to a -// big number using the BytesToBig function. -// It also extracts the high part of the bytes by taking the first 16 bytes and converts it to a big number -// using the BytesToBig function. -// Finally, it converts the low and high big numbers to hexadecimal strings using the BigToHex function and returns them. +// The function then extracts the low part of the bytes by taking the last 16 +// bytes and converts it to a big number using the BytesToBig function. +// It also extracts the high part of the bytes by taking the first 16 bytes and +// converts it to a big number using the BytesToBig function. +// Finally, it converts the low and high big numbers to hexadecimal strings using +// the BigToHex function and returns them. // // Parameters: // - fact: The fact string to be split @@ -210,21 +213,23 @@ func ComputeFact(programHash *big.Int, programOutputs []*big.Int) *big.Int { // - fact_low: The low part of the fact string in hexadecimal format // - fact_high: The high part of the fact string in hexadecimal format // - err: An error if any -func SplitFactStr(fact string) (fact_low, fact_high string, err error) { +func SplitFactStr(fact string) (factLow, factHigh string, err error) { return internalUtils.SplitFactStr(fact) } -// FmtKecBytes formats the given big.Int as a byte slice (Keccak hash) with a specified length. +// FmtKecBytes formats the given big.Int as a byte slice (Keccak hash) with +// a specified length. // // The function appends the bytes of the big.Int to a buffer and returns it. -// If the length of the buffer is less than the specified length, the function pads the buffer with zeros. +// If the length of the buffer is less than the specified length, the function +// pads the buffer with zeros. // // Parameters: // - in: the big.Int to be formatted // - rolen: the length of the buffer // // Returns: -// buf: the formatted buffer +// - buf: the formatted buffer func FmtKecBytes(in *big.Int, rolen int) (buf []byte) { return internalUtils.FmtKecBytes(in, rolen) } diff --git a/utils/transactions.go b/utils/transactions.go index c614c6d33..ed585a788 100644 --- a/utils/transactions.go +++ b/utils/transactions.go @@ -44,7 +44,8 @@ func (opts *TxnOptions) TxnVersion() rpc.TransactionVersion { return rpc.TransactionV3 } -// SafeTip returns the tip amount in FRI for the transaction. If the tip is not set or invalid, returns "0x0". +// SafeTip returns the tip amount in FRI for the transaction. If the tip is not set +// or invalid, returns "0x0". func (opts *TxnOptions) SafeTip() rpc.U64 { if opts.Tip == "" { return "0x0" @@ -82,7 +83,7 @@ func BuildInvokeTxn( } invokeTxn := rpc.BroadcastInvokeTxnV3{ - Type: rpc.TransactionType_Invoke, + Type: rpc.TransactionTypeInvoke, SenderAddress: senderAddress, Calldata: calldata, Version: opts.TxnVersion(), @@ -131,7 +132,7 @@ func BuildDeclareTxn( } declareTxn := rpc.BroadcastDeclareTxnV3{ - Type: rpc.TransactionType_Declare, + Type: rpc.TransactionTypeDeclare, SenderAddress: senderAddress, CompiledClassHash: compiledClassHash, Version: opts.TxnVersion(), @@ -176,7 +177,7 @@ func BuildDeployAccountTxn( } deployAccountTxn := rpc.BroadcastDeployAccountTxnV3{ - Type: rpc.TransactionType_DeployAccount, + Type: rpc.TransactionTypeDeployAccount, Version: opts.TxnVersion(), Signature: []*felt.Felt{}, Nonce: nonce, @@ -216,7 +217,8 @@ func InvokeFuncCallsToFunctionCalls(invokeFuncCalls []rpc.InvokeFunctionCall) [] // FeeEstToResBoundsMap converts a FeeEstimation to ResourceBoundsMapping with applied multipliers. // Parameters: // - feeEstimation: The fee estimation to convert -// - multiplier: Multiplier for max amount and max price per unit. Recommended to be 1.5, but at least greater than 0. +// - multiplier: Multiplier for max amount and max price per unit. Recommended to be 1.5, +// but at least greater than 0. // If multiplier < 0, all resources bounds will be set to 0. // If resource bounds overflow, they will be set to the max allowed value (U64 or U128). // @@ -228,7 +230,11 @@ func FeeEstToResBoundsMap( ) *rpc.ResourceBoundsMapping { // Create L1 resources bounds l1Gas := toResourceBounds(feeEstimation.L1GasPrice, feeEstimation.L1GasConsumed, multiplier) - l1DataGas := toResourceBounds(feeEstimation.L1DataGasPrice, feeEstimation.L1DataGasConsumed, multiplier) + l1DataGas := toResourceBounds( + feeEstimation.L1DataGasPrice, + feeEstimation.L1DataGasConsumed, + multiplier, + ) // Create L2 resource bounds l2Gas := toResourceBounds(feeEstimation.L2GasPrice, feeEstimation.L2GasConsumed, multiplier) @@ -239,7 +245,8 @@ func FeeEstToResBoundsMap( } } -// toResourceBounds converts a gas price and gas consumed to a ResourceBounds with applied multiplier. +// toResourceBounds converts a gas price and gas consumed to a ResourceBounds with +// applied multiplier. // // Parameters: // - gasPrice: The gas price @@ -301,10 +308,12 @@ func toResourceBounds( } } -// ResBoundsMapToOverallFee calculates the overall fee for a ResourceBoundsMapping with applied multipliers. +// ResBoundsMapToOverallFee calculates the overall fee for a ResourceBoundsMapping with +// applied multipliers. // Parameters: // - resBounds: The resource bounds to calculate the fee for -// - multiplier: Multiplier for max amount and max price per unit. Recommended to be 1.5, but at least greater than 0 +// - multiplier: Multiplier for max amount and max price per unit. Recommended to be 1.5, +// but at least greater than 0 // // Returns: // - *felt.Felt: The overall fee in FRI @@ -373,7 +382,9 @@ func ResBoundsMapToOverallFee( overallFee := l1GasFee.Add(l1GasFee, l1DataGasFee).Add(l1GasFee, l2GasFee) // multiply fee by multiplier - multipliedOverallFee := new(big.Float).Mul(new(big.Float).SetInt(overallFee), big.NewFloat(multiplier)) + multipliedOverallFee := new( + big.Float, + ).Mul(new(big.Float).SetInt(overallFee), big.NewFloat(multiplier)) overallFeeInt, _ := multipliedOverallFee.Int(nil) // truncated int // Convert big.Int to felt. SetString() validates if it's a valid felt diff --git a/utils/transactions_test.go b/utils/transactions_test.go index d32361960..90827a916 100644 --- a/utils/transactions_test.go +++ b/utils/transactions_test.go @@ -211,12 +211,17 @@ func TestResBoundsMapToOverallFee(t *testing.T) { expectedBigInt, ok := new(big.Int).SetString(tt.expectedRes, 0) require.True(t, ok) - assert.Equal(t, fmt.Sprintf("%#x", expectedBigInt), got.String(), "ResBoundsMapToOverallFee() returned incorrect value") + assert.Equal( + t, + fmt.Sprintf("%#x", expectedBigInt), + got.String(), + "ResBoundsMapToOverallFee() returned incorrect value", + ) }) } } -//nolint:dupl +//nolint:dupl // The tests are similar, but they are testing different things. func TestFeeEstToResBoundsMap(t *testing.T) { tests := []struct { name string @@ -256,12 +261,30 @@ func TestFeeEstToResBoundsMap(t *testing.T) { name: "Multiplier less than 1", feeEstimation: rpc.FeeEstimation{ FeeEstimationCommon: rpc.FeeEstimationCommon{ - L1GasPrice: internalUtils.TestHexToFelt(t, "0xabcdef1234567890abcdef1234567"), // valid uint128 - L1GasConsumed: internalUtils.TestHexToFelt(t, "0x8b2c3d4e5f607182"), // valid uint64 - L1DataGasPrice: internalUtils.TestHexToFelt(t, "0xa2ffe1d2c3b4a5968778695a4b3c2d15"), // valid uint128 - L1DataGasConsumed: internalUtils.TestHexToFelt(t, "0xac2b3c4d5e6f7a8b"), // valid uint64 - L2GasPrice: internalUtils.TestHexToFelt(t, "0x123456789abcdef0123456789abcdabcdabcd"), // invalid uint128 - L2GasConsumed: internalUtils.TestHexToFelt(t, "0x123456789abcdef0123456789abcdabcdabcd"), // invalid uint64 + L1GasPrice: internalUtils.TestHexToFelt( + t, + "0xabcdef1234567890abcdef1234567", + ), // valid uint128 + L1GasConsumed: internalUtils.TestHexToFelt( + t, + "0x8b2c3d4e5f607182", + ), // valid uint64 + L1DataGasPrice: internalUtils.TestHexToFelt( + t, + "0xa2ffe1d2c3b4a5968778695a4b3c2d15", + ), // valid uint128 + L1DataGasConsumed: internalUtils.TestHexToFelt( + t, + "0xac2b3c4d5e6f7a8b", + ), // valid uint64 + L2GasPrice: internalUtils.TestHexToFelt( + t, + "0x123456789abcdef0123456789abcdabcdabcd", + ), // invalid uint128 + L2GasConsumed: internalUtils.TestHexToFelt( + t, + "0x123456789abcdef0123456789abcdabcdabcd", + ), // invalid uint64 }, }, multiplier: 0.5, @@ -323,17 +346,26 @@ func TestFeeEstToResBoundsMap(t *testing.T) { t, "0xabcdef1234567890abcdef1234567", ), // 55753724871440480815496793359074663 - L1GasConsumed: internalUtils.TestHexToFelt(t, "0x8b2c3d4e5f607182"), // 10028457877064151426 + L1GasConsumed: internalUtils.TestHexToFelt( + t, + "0x8b2c3d4e5f607182", + ), // 10028457877064151426 L1DataGasPrice: internalUtils.TestHexToFelt( t, "0xf0e1d2c3b4a5968778695a4b3c2d1", ), // 78170717918204611383717257769370321 - L1DataGasConsumed: internalUtils.TestHexToFelt(t, "0x1a2b3c4d5e6f7a8b"), // 1885667171979197067 + L1DataGasConsumed: internalUtils.TestHexToFelt( + t, + "0x1a2b3c4d5e6f7a8b", + ), // 1885667171979197067 L2GasPrice: internalUtils.TestHexToFelt( t, "0x123456789abcdef0123456789abcd", ), // 5907679981266292691599931071900621 - L2GasConsumed: internalUtils.TestHexToFelt(t, "0xfedcba98765432"), // 71737338064426034 + L2GasConsumed: internalUtils.TestHexToFelt( + t, + "0xfedcba98765432", + ), // 71737338064426034 }, }, multiplier: 1.7, @@ -390,12 +422,30 @@ func TestFeeEstToResBoundsMap(t *testing.T) { name: "Overflow", feeEstimation: rpc.FeeEstimation{ FeeEstimationCommon: rpc.FeeEstimationCommon{ - L1GasPrice: internalUtils.TestHexToFelt(t, "0xabcdef1234567890abcdef1234567"), // valid uint128 - L1GasConsumed: internalUtils.TestHexToFelt(t, "0x8b2c3d4e5f607182"), // valid uint64 - L1DataGasPrice: internalUtils.TestHexToFelt(t, "0xa2ffe1d2c3b4a5968778695a4b3c2d15"), // valid uint128 - L1DataGasConsumed: internalUtils.TestHexToFelt(t, "0xac2b3c4d5e6f7a8b"), // valid uint64 - L2GasPrice: internalUtils.TestHexToFelt(t, "0x123456789abcdef0123456789abcdabcdabcd"), // invalid uint128 - L2GasConsumed: internalUtils.TestHexToFelt(t, "0x123456789abcdef0123456789abcdabcdabcd"), // invalid uint64 + L1GasPrice: internalUtils.TestHexToFelt( + t, + "0xabcdef1234567890abcdef1234567", + ), // valid uint128 + L1GasConsumed: internalUtils.TestHexToFelt( + t, + "0x8b2c3d4e5f607182", + ), // valid uint64 + L1DataGasPrice: internalUtils.TestHexToFelt( + t, + "0xa2ffe1d2c3b4a5968778695a4b3c2d15", + ), // valid uint128 + L1DataGasConsumed: internalUtils.TestHexToFelt( + t, + "0xac2b3c4d5e6f7a8b", + ), // valid uint64 + L2GasPrice: internalUtils.TestHexToFelt( + t, + "0x123456789abcdef0123456789abcdabcdabcd", + ), // invalid uint128 + L2GasConsumed: internalUtils.TestHexToFelt( + t, + "0x123456789abcdef0123456789abcdabcdabcd", + ), // invalid uint64 }, }, multiplier: 1.7, @@ -429,17 +479,26 @@ func TestFeeEstToResBoundsMap(t *testing.T) { t, "0xabcdef1234567890abcdef1234567", ), // 55753724871440480815496793359074663 - L1GasConsumed: internalUtils.TestHexToFelt(t, "0x8b2c3d4e5f607182"), // 10028457877064151426 + L1GasConsumed: internalUtils.TestHexToFelt( + t, + "0x8b2c3d4e5f607182", + ), // 10028457877064151426 L1DataGasPrice: internalUtils.TestHexToFelt( t, "0xf0e1d2c3b4a5968778695a4b3c2d1", ), // 78170717918204611383717257769370321 - L1DataGasConsumed: internalUtils.TestHexToFelt(t, "0x1a2b3c4d5e6f7a8b"), // 1885667171979197067 + L1DataGasConsumed: internalUtils.TestHexToFelt( + t, + "0x1a2b3c4d5e6f7a8b", + ), // 1885667171979197067 L2GasPrice: internalUtils.TestHexToFelt( t, "0x123456789abcdef0123456789abcd", ), // 5907679981266292691599931071900621 - L2GasConsumed: internalUtils.TestHexToFelt(t, "0xfedcba98765432"), // 71737338064426034 + L2GasConsumed: internalUtils.TestHexToFelt( + t, + "0xfedcba98765432", + ), // 71737338064426034 }, }, multiplier: -1.7, diff --git a/utils/udc.go b/utils/udc.go index 57602b77c..6a6554db8 100644 --- a/utils/udc.go +++ b/utils/udc.go @@ -12,11 +12,16 @@ import ( // TODO: migrate this to contracts package (hard to do now due to circular imports errors, // a new types pkg would solve this) +//nolint:lll // The links would be unclickable if we break the line. var ( // https://voyager.online/contract/0x041a78e741e5af2fec34b695679bc6891742439f7afb8484ecd7766661ad02bf - udcAddressCairoV0, _ = new(felt.Felt).SetString("0x041a78e741e5af2fec34b695679bc6891742439f7afb8484ecd7766661ad02bf") + udcAddressCairoV0, _ = new( + felt.Felt, + ).SetString("0x041a78e741e5af2fec34b695679bc6891742439f7afb8484ecd7766661ad02bf") // https://docs.openzeppelin.com/contracts-cairo/1.0.0/udc#udc_contract_address - udcAddressCairoV2, _ = new(felt.Felt).SetString("0x04a64cd09a853868621d94cae9952b106f2c36a3f81260f85de6696c6b050221") + udcAddressCairoV2, _ = new( + felt.Felt, + ).SetString("0x04a64cd09a853868621d94cae9952b106f2c36a3f81260f85de6696c6b050221") errInvalidUDCVersion = errors.New("invalid UDC version") errClassHashNotProvided = errors.New("classHash not provided") @@ -24,20 +29,23 @@ var ( // The options for building the UDC calldata // -//nolint:lll + type UDCOptions struct { // The salt to be used for the UDC deployment. If not provided, a random value will be used. Salt *felt.Felt - // This parameter is used to determine if the deployer’s address will be included in the contract address calculation. + // This parameter is used to determine if the deployer’s address will be included in + // the contract address calculation. // By making deployments dependent upon the origin address, users can reserve a whole address // space to prevent someone else from taking ownership of the address. Keep it `false` to include // the deployer’s address, and `true` to make it origin independent. // - // This parameter is agnostic to the UDC version. That means that, with `OriginIndependent` set to `true`: + // This parameter is agnostic to the UDC version. That means that, + // with `OriginIndependent` set to `true`: // - UDCCairoV0: `unique` will be set to `false`. // See more at: https://github.com/starknet-io/starknet-docs/blob/aa1772da8eb42dbc8e6b26ebc37cf898c207f54e/components/Starknet/modules/architecture_and_concepts/pages/Smart_Contracts/universal-deployer.adoc#deployment-types // - UDCCairoV2: `from_zero` will be set to `true`. // See more at: https://docs.openzeppelin.com/contracts-cairo/1.0.0/udc#deployment_types + //nolint:lll // The links would be unclickable if we break the line. OriginIndependent bool // The UDC version to be used. If not provided, UDCCairoV0 will be used. UDCVersion UDCVersion @@ -47,9 +55,11 @@ type UDCOptions struct { type UDCVersion int const ( - // Represents the UDC version with Cairo v0 code, with the address 0x041a78e741e5af2fec34b695679bc6891742439f7afb8484ecd7766661ad02bf + // Represents the UDC version with Cairo v0 code, with the + // address 0x041a78e741e5af2fec34b695679bc6891742439f7afb8484ecd7766661ad02bf UDCCairoV0 UDCVersion = iota - // Represents the UDC version with Cairo v2 code, with the address 0x04a64cd09a853868621d94cae9952b106f2c36a3f81260f85de6696c6b050221 + // Represents the UDC version with Cairo v2 code, with the + // address 0x04a64cd09a853868621d94cae9952b106f2c36a3f81260f85de6696c6b050221 UDCCairoV2 ) @@ -61,7 +71,8 @@ const ( // - opts: the options for the UDC deployment. If nil, the default options will be used. // // Returns: -// - the INVOKE txn function call to deploy the contract, including the UDC address and the calldata +// - the INVOKE txn function call to deploy the contract, including the UDC +// address and the calldata // - the salt used for the UDC deployment (either the provided one or the random one) // - an error if any func BuildUDCCalldata( @@ -69,7 +80,7 @@ func BuildUDCCalldata( constructorCalldata []*felt.Felt, opts *UDCOptions, ) (rpc.InvokeFunctionCall, *felt.Felt, error) { - result := rpc.InvokeFunctionCall{} //nolint:exhaustruct + var result rpc.InvokeFunctionCall if classHash == nil { return result, nil, errClassHashNotProvided } @@ -101,7 +112,9 @@ func BuildUDCCalldata( } calldataLen := new(felt.Felt).SetUint64(uint64(len(constructorCalldata))) - udcCallData = append([]*felt.Felt{classHash, opts.Salt, originIndFelt, calldataLen}, constructorCalldata...) + udcCallData = append( + []*felt.Felt{classHash, opts.Salt, originIndFelt, calldataLen}, + constructorCalldata...) udcAddress = udcAddressCairoV0 methodName = "deployContract" case UDCCairoV2: @@ -113,9 +126,14 @@ func BuildUDCCalldata( // The UDCCairoV2 `calldata` constructor parameter is of type `Span`, so // we need to pass the length of the array as the first element. // ref: https://book.cairo-lang.org/ch102-04-serialization-of-cairo-types.html#serialization-of-arrays-and-spans - constructorCalldata = append([]*felt.Felt{new(felt.Felt).SetUint64(uint64(len(constructorCalldata)))}, constructorCalldata...) - - udcCallData = append([]*felt.Felt{classHash, opts.Salt, originIndFelt}, constructorCalldata...) + //nolint:lll // The link would be unclickable if we break the line. + constructorCalldata = append( + []*felt.Felt{new(felt.Felt).SetUint64(uint64(len(constructorCalldata)))}, + constructorCalldata...) + + udcCallData = append( + []*felt.Felt{classHash, opts.Salt, originIndFelt}, + constructorCalldata...) udcAddress = udcAddressCairoV2 methodName = "deploy_contract" default: diff --git a/utils/udc_test.go b/utils/udc_test.go index db821bd45..bf4b6827f 100644 --- a/utils/udc_test.go +++ b/utils/udc_test.go @@ -24,9 +24,12 @@ func TestBuildUDCCalldata(t *testing.T) { checkCallDataContents bool }{ { - name: "UDC Cairo V0 with default options", - classHash: internalUtils.RANDOM_FELT, - constructorCalldata: []*felt.Felt{new(felt.Felt).SetUint64(100), new(felt.Felt).SetUint64(200)}, + name: "UDC Cairo V0 with default options", + classHash: internalUtils.DeadBeef, + constructorCalldata: []*felt.Felt{ + new(felt.Felt).SetUint64(100), + new(felt.Felt).SetUint64(200), + }, opts: nil, expectedUDCAddress: udcAddressCairoV0, expectedFunctionName: "deployContract", @@ -35,7 +38,7 @@ func TestBuildUDCCalldata(t *testing.T) { }, { name: "UDC Cairo V0 with custom salt", - classHash: internalUtils.RANDOM_FELT, + classHash: internalUtils.DeadBeef, constructorCalldata: []*felt.Felt{new(felt.Felt).SetUint64(100)}, opts: &UDCOptions{Salt: new(felt.Felt).SetUint64(999)}, expectedUDCAddress: udcAddressCairoV0, @@ -45,7 +48,7 @@ func TestBuildUDCCalldata(t *testing.T) { }, { name: "UDC Cairo V0 with origin independent", - classHash: internalUtils.RANDOM_FELT, + classHash: internalUtils.DeadBeef, constructorCalldata: []*felt.Felt{}, opts: &UDCOptions{OriginIndependent: true}, expectedUDCAddress: udcAddressCairoV0, @@ -54,9 +57,12 @@ func TestBuildUDCCalldata(t *testing.T) { checkCallDataContents: true, }, { - name: "UDC Cairo V2 with default options", - classHash: internalUtils.RANDOM_FELT, - constructorCalldata: []*felt.Felt{new(felt.Felt).SetUint64(100), new(felt.Felt).SetUint64(200)}, + name: "UDC Cairo V2 with default options", + classHash: internalUtils.DeadBeef, + constructorCalldata: []*felt.Felt{ + new(felt.Felt).SetUint64(100), + new(felt.Felt).SetUint64(200), + }, opts: &UDCOptions{UDCVersion: UDCCairoV2}, expectedUDCAddress: udcAddressCairoV2, expectedFunctionName: "deploy_contract", @@ -65,7 +71,7 @@ func TestBuildUDCCalldata(t *testing.T) { }, { name: "UDC Cairo V2 with origin independent", - classHash: internalUtils.RANDOM_FELT, + classHash: internalUtils.DeadBeef, constructorCalldata: []*felt.Felt{new(felt.Felt).SetUint64(100)}, opts: &UDCOptions{UDCVersion: UDCCairoV2, OriginIndependent: true}, expectedUDCAddress: udcAddressCairoV2, @@ -74,10 +80,14 @@ func TestBuildUDCCalldata(t *testing.T) { checkCallDataContents: true, }, { - name: "UDC Cairo V2 with custom salt and origin independent", - classHash: internalUtils.RANDOM_FELT, - constructorCalldata: []*felt.Felt{}, - opts: &UDCOptions{UDCVersion: UDCCairoV2, Salt: new(felt.Felt).SetUint64(888), OriginIndependent: true}, + name: "UDC Cairo V2 with custom salt and origin independent", + classHash: internalUtils.DeadBeef, + constructorCalldata: []*felt.Felt{}, + opts: &UDCOptions{ + UDCVersion: UDCCairoV2, + Salt: new(felt.Felt).SetUint64(888), + OriginIndependent: true, + }, expectedUDCAddress: udcAddressCairoV2, expectedFunctionName: "deploy_contract", expectedCallDataLen: 4, // classHash + salt + originInd + calldataLen @@ -85,7 +95,7 @@ func TestBuildUDCCalldata(t *testing.T) { }, { name: "Empty constructor calldata", - classHash: internalUtils.RANDOM_FELT, + classHash: internalUtils.DeadBeef, constructorCalldata: []*felt.Felt{}, opts: nil, expectedUDCAddress: udcAddressCairoV0, @@ -102,7 +112,7 @@ func TestBuildUDCCalldata(t *testing.T) { }, { name: "Invalid UDC version", - classHash: internalUtils.RANDOM_FELT, + classHash: internalUtils.DeadBeef, constructorCalldata: []*felt.Felt{new(felt.Felt).SetUint64(100)}, opts: &UDCOptions{UDCVersion: 999}, // Invalid version expectedError: errInvalidUDCVersion, @@ -202,12 +212,20 @@ func TestBuildUDCCalldata_UDCAddresses(t *testing.T) { constructorCalldata := []*felt.Felt{new(felt.Felt).SetUint64(100)} // Test Cairo V0 address - result, _, err := BuildUDCCalldata(classHash, constructorCalldata, &UDCOptions{UDCVersion: UDCCairoV0}) + result, _, err := BuildUDCCalldata( + classHash, + constructorCalldata, + &UDCOptions{UDCVersion: UDCCairoV0}, + ) require.NoError(t, err) assert.Equal(t, udcAddressCairoV0, result.ContractAddress) // Test Cairo V2 address - result, _, err = BuildUDCCalldata(classHash, constructorCalldata, &UDCOptions{UDCVersion: UDCCairoV2}) + result, _, err = BuildUDCCalldata( + classHash, + constructorCalldata, + &UDCOptions{UDCVersion: UDCCairoV2}, + ) require.NoError(t, err) assert.Equal(t, udcAddressCairoV2, result.ContractAddress) } @@ -219,26 +237,42 @@ func TestBuildUDCCalldata_OriginIndependent(t *testing.T) { // **** Test Cairo V0 **** // origin independent - result, _, err := BuildUDCCalldata(classHash, constructorCalldata, &UDCOptions{UDCVersion: UDCCairoV0, OriginIndependent: true}) + result, _, err := BuildUDCCalldata( + classHash, + constructorCalldata, + &UDCOptions{UDCVersion: UDCCairoV0, OriginIndependent: true}, + ) require.NoError(t, err) // Cairo V0: `unique` should be 0 (false) when OriginIndependent is true assert.Equal(t, new(felt.Felt).SetUint64(0), result.CallData[2]) // not origin independent - result, _, err = BuildUDCCalldata(classHash, constructorCalldata, &UDCOptions{UDCVersion: UDCCairoV0, OriginIndependent: false}) + result, _, err = BuildUDCCalldata( + classHash, + constructorCalldata, + &UDCOptions{UDCVersion: UDCCairoV0, OriginIndependent: false}, + ) require.NoError(t, err) // Cairo V0: `unique` should be 1 (true) when OriginIndependent is false assert.Equal(t, new(felt.Felt).SetUint64(1), result.CallData[2]) // **** Test Cairo V2 **** // origin independent - result, _, err = BuildUDCCalldata(classHash, constructorCalldata, &UDCOptions{UDCVersion: UDCCairoV2, OriginIndependent: true}) + result, _, err = BuildUDCCalldata( + classHash, + constructorCalldata, + &UDCOptions{UDCVersion: UDCCairoV2, OriginIndependent: true}, + ) require.NoError(t, err) // Cairo V2: `from_zero` should be 1 (true) when OriginIndependent is true assert.Equal(t, new(felt.Felt).SetUint64(1), result.CallData[2]) // not origin independent - result, _, err = BuildUDCCalldata(classHash, constructorCalldata, &UDCOptions{UDCVersion: UDCCairoV2, OriginIndependent: false}) + result, _, err = BuildUDCCalldata( + classHash, + constructorCalldata, + &UDCOptions{UDCVersion: UDCCairoV2, OriginIndependent: false}, + ) require.NoError(t, err) // Cairo V2: `from_zero` should be 0 (false) when OriginIndependent is false assert.Equal(t, new(felt.Felt).SetUint64(0), result.CallData[2]) @@ -273,7 +307,11 @@ func TestBuildUDCCalldata_Salt(t *testing.T) { customSalt := new(felt.Felt).SetUint64(999) // Test that when a custom salt is provided, it's used - result, salt, err := BuildUDCCalldata(classHash, constructorCalldata, &UDCOptions{Salt: customSalt}) + result, salt, err := BuildUDCCalldata( + classHash, + constructorCalldata, + &UDCOptions{Salt: customSalt}, + ) require.NoError(t, err) assert.Equal(t, customSalt, salt) @@ -291,11 +329,17 @@ func TestBuildUDCCalldata_LargeConstructorCalldata(t *testing.T) { largeCalldata[i] = new(felt.Felt).SetUint64(uint64(i)) } - result, _, err := BuildUDCCalldata(classHash, largeCalldata, &UDCOptions{UDCVersion: UDCCairoV0}) + result, _, err := BuildUDCCalldata( + classHash, + largeCalldata, + &UDCOptions{UDCVersion: UDCCairoV0}, + ) require.NoError(t, err) // Check that all constructor calldata is included - expectedLen := 4 + len(largeCalldata) // classHash + salt + originInd + calldataLen + constructor args + expectedLen := 4 + len( + largeCalldata, + ) // classHash + salt + originInd + calldataLen + constructor args assert.Equal(t, expectedLen, len(result.CallData)) // Check calldata length field @@ -326,82 +370,172 @@ func TestPrecomputeAddressForUDC(t *testing.T) { { // https://sepolia.voyager.online/tx/0x36f1ae1379dcea5e14938f6e9b5189d5ddb34e8b2eff404d5886e7a7e1ebb48 name: "UDCCairoV0: Origin-independent 0x36f1ae", originAccAddress: nil, - classHash: internalUtils.TestHexToFelt(t, "0x486002e9e1d1fd7f07852663c0e476853e68c1aaa6afaeaa58cce954e3cf7cf"), - salt: internalUtils.TestHexToFelt(t, "0x23fcbf2e9a467d3081182b138fc605f8743610c4327edf4f24104f478143f66"), + classHash: internalUtils.TestHexToFelt( + t, + "0x486002e9e1d1fd7f07852663c0e476853e68c1aaa6afaeaa58cce954e3cf7cf", + ), + salt: internalUtils.TestHexToFelt( + t, + "0x23fcbf2e9a467d3081182b138fc605f8743610c4327edf4f24104f478143f66", + ), constructorCalldata: []*felt.Felt{ - internalUtils.TestHexToFelt(t, "0x23fcbf2e9a467d3081182b138fc605f8743610c4327edf4f24104f478143f66"), + internalUtils.TestHexToFelt( + t, + "0x23fcbf2e9a467d3081182b138fc605f8743610c4327edf4f24104f478143f66", + ), }, - udcVersion: UDCCairoV0, - expectedAddress: internalUtils.TestHexToFelt(t, "0x77a249aefd797d3ce41ec9d434c26ca7fe929a6ec3458bcec97cc456741fa3f"), + udcVersion: UDCCairoV0, + expectedAddress: internalUtils.TestHexToFelt( + t, + "0x77a249aefd797d3ce41ec9d434c26ca7fe929a6ec3458bcec97cc456741fa3f", + ), }, { // https://sepolia.voyager.online/tx/0x3c79058b1a7a8904d4a5ade66ae87a1dcec6a568a5193a9f95f5c9646d383f3 name: "UDCCairoV0: Origin-independent 0x3c7905", originAccAddress: nil, - classHash: internalUtils.TestHexToFelt(t, "0x54328a1075b8820eb43caf0caa233923148c983742402dcfc38541dd843d01a"), - salt: internalUtils.TestHexToFelt(t, "0x52a06f2789d5229e87d5d0dc0d933d0e1e83366306ae069192ca9a3e4e6881f"), + classHash: internalUtils.TestHexToFelt( + t, + "0x54328a1075b8820eb43caf0caa233923148c983742402dcfc38541dd843d01a", + ), + salt: internalUtils.TestHexToFelt( + t, + "0x52a06f2789d5229e87d5d0dc0d933d0e1e83366306ae069192ca9a3e4e6881f", + ), constructorCalldata: []*felt.Felt{ internalUtils.TestHexToFelt(t, "0x546f6b656e"), internalUtils.TestHexToFelt(t, "0x4552433230"), - internalUtils.TestHexToFelt(t, "0xf9e998b2853e6d01f3ae3c598c754c1b9a7bd398fec7657de022f3b778679"), + internalUtils.TestHexToFelt( + t, + "0xf9e998b2853e6d01f3ae3c598c754c1b9a7bd398fec7657de022f3b778679", + ), }, - udcVersion: UDCCairoV0, - expectedAddress: internalUtils.TestHexToFelt(t, "0x48634f9843983eeb06b47bf7f5d156a55a1d297e958da1c86427f9ce077425b"), + udcVersion: UDCCairoV0, + expectedAddress: internalUtils.TestHexToFelt( + t, + "0x48634f9843983eeb06b47bf7f5d156a55a1d297e958da1c86427f9ce077425b", + ), }, { // https://sepolia.voyager.online/tx/0x4dadb8b32b286acd11ee6698a71206f274f1cf93fdf602f6fcf2d376c197ca4 - name: "UDCCairoV0: Origin-dependent 0x4dadb8", - originAccAddress: internalUtils.TestHexToFelt(t, "0x000f9e998b2853e6d01f3ae3c598c754c1b9a7bd398fec7657de022f3b778679"), - classHash: internalUtils.TestHexToFelt(t, "0x54328a1075b8820eb43caf0caa233923148c983742402dcfc38541dd843d01a"), - salt: internalUtils.TestHexToFelt(t, "0xb2334ec640982eb272cbfa72f4f9d32769e77166460c620ac950c8a4d94606"), + name: "UDCCairoV0: Origin-dependent 0x4dadb8", + originAccAddress: internalUtils.TestHexToFelt( + t, + "0x000f9e998b2853e6d01f3ae3c598c754c1b9a7bd398fec7657de022f3b778679", + ), + classHash: internalUtils.TestHexToFelt( + t, + "0x54328a1075b8820eb43caf0caa233923148c983742402dcfc38541dd843d01a", + ), + salt: internalUtils.TestHexToFelt( + t, + "0xb2334ec640982eb272cbfa72f4f9d32769e77166460c620ac950c8a4d94606", + ), constructorCalldata: []*felt.Felt{ internalUtils.TestHexToFelt(t, "0x546f6b656e"), internalUtils.TestHexToFelt(t, "0x4552433230"), - internalUtils.TestHexToFelt(t, "0x7d1f349d4d1c93d3e95bf584fd3f806fa61f4c72aa9b42ae624ef25470da0c6"), + internalUtils.TestHexToFelt( + t, + "0x7d1f349d4d1c93d3e95bf584fd3f806fa61f4c72aa9b42ae624ef25470da0c6", + ), }, - udcVersion: UDCCairoV0, - expectedAddress: internalUtils.TestHexToFelt(t, "0x770f3b98c5a23250bc237dbeeb0a9385621f99c04a1fe3842d899264f4a1268"), + udcVersion: UDCCairoV0, + expectedAddress: internalUtils.TestHexToFelt( + t, + "0x770f3b98c5a23250bc237dbeeb0a9385621f99c04a1fe3842d899264f4a1268", + ), }, { // https://sepolia.voyager.online/tx/0x17ffdf141abc5e5db10b7ec0f69a5f099e70390c0844e281cdd7877c7c98a54 - name: "UDCCairoV0: Origin-dependent 0x17ffdf", - originAccAddress: internalUtils.TestHexToFelt(t, "0x02d54b7dc47eafa80f8e451cf39e7601f51fef6f1bfe5cea44ff12fa563e5457"), - classHash: internalUtils.TestHexToFelt(t, "0x387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8"), - salt: internalUtils.TestHexToFelt(t, "0x18809706355007129cd38d1719447f454b7ff081c38817c53d9e2951d185243"), + name: "UDCCairoV0: Origin-dependent 0x17ffdf", + originAccAddress: internalUtils.TestHexToFelt( + t, + "0x02d54b7dc47eafa80f8e451cf39e7601f51fef6f1bfe5cea44ff12fa563e5457", + ), + classHash: internalUtils.TestHexToFelt( + t, + "0x387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8", + ), + salt: internalUtils.TestHexToFelt( + t, + "0x18809706355007129cd38d1719447f454b7ff081c38817c53d9e2951d185243", + ), constructorCalldata: []*felt.Felt{}, udcVersion: UDCCairoV0, - expectedAddress: internalUtils.TestHexToFelt(t, "0x43267890ad2798db4a6a5374ee361cb6f3669facad58e9e58ea88c078c567bb"), + expectedAddress: internalUtils.TestHexToFelt( + t, + "0x43267890ad2798db4a6a5374ee361cb6f3669facad58e9e58ea88c078c567bb", + ), }, { // https://sepolia.voyager.online/tx/0x1683dd3917260a8b1572cf703b1525ea9bd6501cd76a4c20d6e4aa316ddff86 - name: "UDCCairoV2: Origin-independent 0x1683dd", - originAccAddress: nil, - classHash: internalUtils.TestHexToFelt(t, "0x387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8"), - salt: internalUtils.TestHexToFelt(t, "0x357f0d6bf3f6931e6a0d579ec8936510dad2dbabb8593a3dda16c4cd8fe3dc6"), + name: "UDCCairoV2: Origin-independent 0x1683dd", + originAccAddress: nil, + classHash: internalUtils.TestHexToFelt( + t, + "0x387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8", + ), + salt: internalUtils.TestHexToFelt( + t, + "0x357f0d6bf3f6931e6a0d579ec8936510dad2dbabb8593a3dda16c4cd8fe3dc6", + ), constructorCalldata: []*felt.Felt{}, udcVersion: UDCCairoV2, - expectedAddress: internalUtils.TestHexToFelt(t, "0x2543d193907205cff1ba8818002fb0b7477493e093c7ea605516a21e838648e"), + expectedAddress: internalUtils.TestHexToFelt( + t, + "0x2543d193907205cff1ba8818002fb0b7477493e093c7ea605516a21e838648e", + ), }, { // https://sepolia.voyager.online/tx/0x5c76c4f41451f64276571d5f225ab203e9de19d1749372e548a6c5e5df775af - name: "UDCCairoV2: Origin-dependent 0x5c76c4", - originAccAddress: internalUtils.TestHexToFelt(t, "0x02d54b7dc47eafa80f8e451cf39e7601f51fef6f1bfe5cea44ff12fa563e5457"), - classHash: internalUtils.TestHexToFelt(t, "0x387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8"), - salt: internalUtils.TestHexToFelt(t, "0x35fd26c7a05d64130bb27636931282cd1fbc19930933c97974d15028771ab72"), + name: "UDCCairoV2: Origin-dependent 0x5c76c4", + originAccAddress: internalUtils.TestHexToFelt( + t, + "0x02d54b7dc47eafa80f8e451cf39e7601f51fef6f1bfe5cea44ff12fa563e5457", + ), + classHash: internalUtils.TestHexToFelt( + t, + "0x387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8", + ), + salt: internalUtils.TestHexToFelt( + t, + "0x35fd26c7a05d64130bb27636931282cd1fbc19930933c97974d15028771ab72", + ), constructorCalldata: []*felt.Felt{}, udcVersion: UDCCairoV2, - expectedAddress: internalUtils.TestHexToFelt(t, "0x6493b4567665272ef04b30d57abe07a51b5f2c7862eb1f02a84e633ae2f12c7"), + expectedAddress: internalUtils.TestHexToFelt( + t, + "0x6493b4567665272ef04b30d57abe07a51b5f2c7862eb1f02a84e633ae2f12c7", + ), }, { // https://sepolia.voyager.online/tx/0x337566e293faf471c13f249c91e72d574d207e16974f46eb96ea056eca272d5 - name: "UDCCairoV2: Origin-dependent 0x337566", - originAccAddress: internalUtils.TestHexToFelt(t, "0x02d54b7dc47eafa80f8e451cf39e7601f51fef6f1bfe5cea44ff12fa563e5457"), - classHash: internalUtils.TestHexToFelt(t, "0x387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8"), - salt: internalUtils.TestHexToFelt(t, "0xe70e5c84498d9c52430ca8bb8e9a89b0804dbb91efe1da91e36b88ff3a2508"), + name: "UDCCairoV2: Origin-dependent 0x337566", + originAccAddress: internalUtils.TestHexToFelt( + t, + "0x02d54b7dc47eafa80f8e451cf39e7601f51fef6f1bfe5cea44ff12fa563e5457", + ), + classHash: internalUtils.TestHexToFelt( + t, + "0x387edd4804deba7af741953fdf64189468f37593a66b618d00d2476be3168f8", + ), + salt: internalUtils.TestHexToFelt( + t, + "0xe70e5c84498d9c52430ca8bb8e9a89b0804dbb91efe1da91e36b88ff3a2508", + ), constructorCalldata: []*felt.Felt{}, udcVersion: UDCCairoV2, - expectedAddress: internalUtils.TestHexToFelt(t, "0x1899a818fea0c0ab6c3d6e078757f082610f0ccd5ce51a1ca5746d09c7828f3"), + expectedAddress: internalUtils.TestHexToFelt( + t, + "0x1899a818fea0c0ab6c3d6e078757f082610f0ccd5ce51a1ca5746d09c7828f3", + ), }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { t.Parallel() - address := PrecomputeAddressForUDC(test.classHash, test.salt, test.constructorCalldata, test.udcVersion, test.originAccAddress) + address := PrecomputeAddressForUDC( + test.classHash, + test.salt, + test.constructorCalldata, + test.udcVersion, + test.originAccAddress, + ) assert.Equal(t, test.expectedAddress, address) }) }