Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Thiagodeev/fixes before 7 1 release v2 #619

Merged
merged 18 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .github/workflows/main_ci_check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ jobs:

# Test rpc on testnet
- name: Test RPC on testnet
run: echo "Skip for now - need public endpoint that follows rpc spec"
#run: cd rpc && go test -timeout 1200s -v -env testnet .
run: cd rpc && go test -timeout 1200s -v -env testnet .
env:
TESTNET_ACCOUNT_PRIVATE_KEY: ${{ secrets.TESTNET_ACCOUNT_PRIVATE_KEY }}
INTEGRATION_BASE: "https://free-rpc.nethermind.io/sepolia-juno"
Expand Down
10 changes: 5 additions & 5 deletions account/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -682,9 +682,9 @@ func (account *Account) ClassHashAt(ctx context.Context, blockID rpc.BlockID, co
// - requests: An array of rpc.BroadcastTxn objects representing the requests to estimate the fee for.
// - blockID: The rpc.BlockID object representing the block ID for which to estimate the fee.
// Returns:
// - []rpc.FeeEstimate: An array of rpc.FeeEstimate objects representing the estimated fees.
// - []rpc.FeeEstimation: An array of rpc.FeeEstimation objects representing the estimated fees.
// - error: An error object if any error occurred during the estimation process.
func (account *Account) EstimateFee(ctx context.Context, requests []rpc.BroadcastTxn, simulationFlags []rpc.SimulationFlag, blockID rpc.BlockID) ([]rpc.FeeEstimate, error) {
func (account *Account) EstimateFee(ctx context.Context, requests []rpc.BroadcastTxn, simulationFlags []rpc.SimulationFlag, blockID rpc.BlockID) ([]rpc.FeeEstimation, error) {
return account.provider.EstimateFee(ctx, requests, simulationFlags, blockID)
}

Expand All @@ -695,9 +695,9 @@ func (account *Account) EstimateFee(ctx context.Context, requests []rpc.Broadcas
// - msg: The rpc.MsgFromL1 object representing the message.
// - blockID: The rpc.BlockID object representing the block ID.
// Returns:
// - *rpc.FeeEstimate: a pointer to rpc.FeeEstimate
// - *rpc.FeeEstimation: a pointer to rpc.FeeEstimation
// - error: an error if any.
func (account *Account) EstimateMessageFee(ctx context.Context, msg rpc.MsgFromL1, blockID rpc.BlockID) (*rpc.FeeEstimate, error) {
func (account *Account) EstimateMessageFee(ctx context.Context, msg rpc.MsgFromL1, blockID rpc.BlockID) (*rpc.FeeEstimation, error) {
return account.provider.EstimateMessageFee(ctx, msg, blockID)
}

Expand Down Expand Up @@ -735,7 +735,7 @@ func (account *Account) Nonce(ctx context.Context, blockID rpc.BlockID, contract
// Returns:
// - []rpc.SimulatedTransaction: a list of simulated transactions
// - error: an error, if any.
func (account *Account) SimulateTransactions(ctx context.Context, blockID rpc.BlockID, txns []rpc.Transaction, simulationFlags []rpc.SimulationFlag) ([]rpc.SimulatedTransaction, error) {
func (account *Account) SimulateTransactions(ctx context.Context, blockID rpc.BlockID, txns []rpc.BroadcastTxn, simulationFlags []rpc.SimulationFlag) ([]rpc.SimulatedTransaction, error) {
return account.provider.SimulateTransactions(ctx, blockID, txns, simulationFlags)
}

Expand Down
5 changes: 2 additions & 3 deletions examples/deployAccount/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,7 @@ func main() {
if err != nil {
panic(err)
}
fmt.Println("PrecomputedAddress:", precomputedAddress)

fmt.Println("PrecomputedAddress:", setup.PadZerosInFelt(precomputedAddress))
// Sign the transaction
err = accnt.SignDeployAccountTransaction(context.Background(), &tx.DeployAccountTxn, precomputedAddress)
if err != nil {
Expand Down Expand Up @@ -115,7 +114,7 @@ func main() {
// At this point you need to add funds to precomputed address to use it.
var input string

fmt.Println("The `precomputedAddress` account needs to have enough ETH to perform a transaction.")
fmt.Println("\nThe `precomputedAddress` account needs to have enough ETH to perform a transaction.")
fmt.Printf("Use the starknet faucet to send ETH to your `precomputedAddress`. You need aproximately %f ETH. \n", feeInETH)
fmt.Println("When your account has been funded by the faucet, press any key, then `enter` to continue : ")
fmt.Scan(&input)
Expand Down
21 changes: 21 additions & 0 deletions examples/internal/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"strconv"

"github.com/NethermindEth/juno/core/felt"
"github.com/NethermindEth/starknet.go/rpc"
"github.com/joho/godotenv"
)
Expand Down Expand Up @@ -72,3 +73,23 @@ func getEnv(envName string) string {
}
return env
}

// PadZerosInFelt pads zeros to the left of a hex felt value to make it 64 characters long.
func PadZerosInFelt(hexFelt *felt.Felt) string {
length := 66
hexStr := hexFelt.String()

// Check if the hex value is already of the desired length
if len(hexStr) >= length {
return hexStr
}

// Extract the hex value without the "0x" prefix
hexValue := hexStr[2:]
// Pad zeros after the "0x" prefix
paddedHexValue := fmt.Sprintf("%0*s", length-2, hexValue)
// Add back the "0x" prefix to the padded hex value
paddedHexStr := "0x" + paddedHexValue

return paddedHexStr
}
10 changes: 5 additions & 5 deletions mocks/mock_rpc_provider.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 3 additions & 6 deletions rpc/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ import (
// - error: An error if any
func (provider *Provider) BlockNumber(ctx context.Context) (uint64, error) {
var blockNumber uint64
if err := provider.c.CallContext(ctx, &blockNumber, "starknet_blockNumber"); err != nil {
if err := do(ctx, provider.c, "starknet_blockNumber", &blockNumber); err != nil {
if errors.Is(err, errNotFound) {
return 0, ErrNoBlocks
}
return 0, Err(InternalError, err)
return 0, tryUnwrapToRPCErr(err)
}
return blockNumber, nil
}
Expand Down Expand Up @@ -139,10 +139,7 @@ func (provider *Provider) StateUpdate(ctx context.Context, blockID BlockID) (*St
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 {
if errors.Is(err, errNotFound) {
return 0, ErrBlockNotFound
}
return 0, Err(InternalError, err)
return 0, tryUnwrapToRPCErr(err, ErrBlockNotFound)
}
return result, nil
}
Expand Down
96 changes: 21 additions & 75 deletions rpc/block_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,7 @@ import (
"github.com/stretchr/testify/require"
)

// TestBlockNumber is a test function to check the behavior of the BlockNumber function and check the returned value is strictly positive.
//
// The function performs the following steps:
// 1. Sets up the test configuration.
// 2. Defines a test set.
// 3. Loops over the test set.
// 4. Creates a new spy.
// 5. Calls the BlockNumber function on the test provider.
// 6. Validates the returned block number.
// TestBlockNumber is a test function to check the behavior of the BlockNumber function and check if there is no errors.
//
// Parameters:
// - t: the testing object for running the test cases
Expand All @@ -30,41 +22,14 @@ import (
func TestBlockNumber(t *testing.T) {
testConfig := beforeEach(t)

type testSetType struct{}

testSet := map[string][]testSetType{
"mock": {},
"testnet": {{}},
"mainnet": {{}},
"devnet": {},
}[testEnv]

for range testSet {
spy := NewSpy(testConfig.provider.c)
testConfig.provider.c = spy
blockNumber, err := testConfig.provider.BlockNumber(context.Background())
require.NoError(t, err, "BlockNumber should not return an error")

diff, err := spy.Compare(blockNumber, false)
require.NoError(t, err, "expecting to match")
require.Equal(t, "FullMatch", diff, "expecting to match, instead %s", diff)

require.False(t, blockNumber <= 3000, fmt.Sprintf("Block number should be > 3000, instead: %d", blockNumber))
blockNumber, err := testConfig.provider.BlockNumber(context.Background())
require.NoError(t, err, "BlockNumber should not return an error")
if testEnv == "mock" {
require.Equal(t, uint64(1234), blockNumber)
}
}

// TestBlockHashAndNumber is a test function that tests the BlockHashAndNumber function and check the returned value is strictly positive.
//
// It sets up a test configuration and creates a test set based on the test environment.
// Then it iterates through the test set and performs the following steps:
// - Creates a new spy using the testConfig provider.
// - Sets the testConfig provider to the spy.
// - Calls the BlockHashAndNumber function of the testConfig provider with a context.
// - Checks if there is an error and if it matches the expected error.
// - Compares the result with the spy and checks if it matches the expected result.
// - Checks if the block number is greater than 3000.
// - Checks if the block hash starts with "0x".
//
// TestBlockHashAndNumber is a test function that tests the BlockHashAndNumber function and check if there is no errors.
// Parameters:
// - t: the testing object for running the test cases
// Returns:
Expand All @@ -73,28 +38,12 @@ func TestBlockNumber(t *testing.T) {
func TestBlockHashAndNumber(t *testing.T) {
testConfig := beforeEach(t)

type testSetType struct{}
blockHashAndNumber, err := testConfig.provider.BlockHashAndNumber(context.Background())
require.NoError(t, err, "BlockHashAndNumber should not return an error")
require.True(t, strings.HasPrefix(blockHashAndNumber.BlockHash.String(), "0x"), "current block hash should return a string starting with 0x")

testSet := map[string][]testSetType{
"mock": {},
"testnet": {{}},
"mainnet": {{}},
"devnet": {},
}[testEnv]

for range testSet {
spy := NewSpy(testConfig.provider.c)
testConfig.provider.c = spy
blockHashAndNumber, err := testConfig.provider.BlockHashAndNumber(context.Background())
require.NoError(t, err, "BlockHashAndNumber should not return an error")

diff, err := spy.Compare(blockHashAndNumber, false)
require.NoError(t, err, "expecting to match")
require.Equal(t, "FullMatch", diff, "expecting to match, instead %s", diff)

require.False(t, blockHashAndNumber.BlockNumber <= 3000, "Block number should be > 3000, instead: %d", blockHashAndNumber.BlockNumber)

require.True(t, strings.HasPrefix(blockHashAndNumber.BlockHash.String(), "0x"), "current block hash should return a string starting with 0x")
if testEnv == "mock" {
require.Equal(t, &BlockHashAndNumberOutput{BlockNumber: 1234, BlockHash: utils.RANDOM_FELT}, blockHashAndNumber)
}
}

Expand Down Expand Up @@ -426,6 +375,7 @@ func TestBlockTransactionCount(t *testing.T) {
type testSetType struct {
BlockID BlockID
ExpectedCount uint64
ExpectedError error
}
testSet := map[string][]testSetType{
"mock": {
Expand All @@ -443,24 +393,20 @@ func TestBlockTransactionCount(t *testing.T) {
BlockID: WithBlockNumber(52959),
ExpectedCount: 58,
},
{
BlockID: WithBlockNumber(7338746823462834783),
ExpectedError: ErrBlockNotFound,
},
},
"mainnet": {},
}[testEnv]
for _, test := range testSet {
spy := NewSpy(testConfig.provider.c)
testConfig.provider.c = spy
count, err := testConfig.provider.BlockTransactionCount(context.Background(), test.BlockID)
require.NoError(t, err, "Unable to fetch the given block.")

diff, err := spy.Compare(count, false)
require.NoError(t, err, "Unable to compare the count.")

_, err = spy.Compare(count, true)
require.NoError(t, err, "Unable to compare the count.")

require.Equal(t, "FullMatch", diff, "structure expecting to be FullMatch, instead %s", diff)

require.Equal(t, test.ExpectedCount, count, fmt.Sprintf("structure expecting %d, instead: %d", test.ExpectedCount, count))
if err != nil {
require.EqualError(t, test.ExpectedError, err.Error())
} else {
require.Equalf(t, test.ExpectedCount, count, "structure expecting %d, instead: %d", test.ExpectedCount, count)
}
}
}

Expand Down
6 changes: 1 addition & 5 deletions rpc/call.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,9 @@ import (
// - []*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) {

if len(request.Calldata) == 0 {
request.Calldata = make([]*felt.Felt, 0)
}
var result []*felt.Felt
if err := do(ctx, provider.c, "starknet_call", &result, request, blockID); err != nil {
return nil, tryUnwrapToRPCErr(err, ErrContractNotFound, ErrBlockNotFound)
return nil, tryUnwrapToRPCErr(err, ErrContractNotFound, ErrContractError, ErrBlockNotFound)
}
return result, nil
}
38 changes: 35 additions & 3 deletions rpc/call_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func TestCall(t *testing.T) {
FunctionCall FunctionCall
BlockID BlockID
ExpectedPatternResult *felt.Felt
ExpectedError error
}
testSet := map[string][]testSetType{
"devnet": {
Expand Down Expand Up @@ -65,6 +66,33 @@ func TestCall(t *testing.T) {
BlockID: WithBlockTag("latest"),
ExpectedPatternResult: utils.TestHexToFelt(t, "0x506f736974696f6e"),
},
{
FunctionCall: FunctionCall{
ContractAddress: utils.TestHexToFelt(t, "0x025633c6142D9CA4126e3fD1D522Faa6e9f745144aba728c0B3FEE38170DF9e7"),
EntryPointSelector: utils.GetSelectorFromNameFelt("RANDOM_STRINGGG"),
Calldata: []*felt.Felt{},
},
BlockID: WithBlockTag("latest"),
ExpectedError: ErrContractError,
},
{
FunctionCall: FunctionCall{
ContractAddress: utils.TestHexToFelt(t, "0x025633c6142D9CA4126e3fD1D522Faa6e9f745144aba728c0B3FEE38170DF9e7"),
EntryPointSelector: utils.GetSelectorFromNameFelt("name"),
Calldata: []*felt.Felt{},
},
BlockID: WithBlockNumber(9999999999999999999),
ExpectedError: ErrBlockNotFound,
},
{
FunctionCall: FunctionCall{
ContractAddress: utils.RANDOM_FELT,
EntryPointSelector: utils.GetSelectorFromNameFelt("name"),
Calldata: []*felt.Felt{},
},
BlockID: WithBlockTag("latest"),
ExpectedError: ErrContractNotFound,
},
},
"mainnet": {
{
Expand All @@ -82,8 +110,12 @@ func TestCall(t *testing.T) {
for _, test := range testSet {
require := require.New(t)
output, err := testConfig.provider.Call(context.Background(), FunctionCall(test.FunctionCall), test.BlockID)
require.NoError(err)
require.NotEmpty(output, "should return an output")
require.Equal(test.ExpectedPatternResult, output[0])
if test.ExpectedError != nil {
require.EqualError(test.ExpectedError, err.Error())
} else {
require.NoError(err)
require.NotEmpty(output, "should return an output")
require.Equal(test.ExpectedPatternResult, output[0])
}
}
}
7 changes: 3 additions & 4 deletions rpc/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ func (provider *Provider) ChainID(ctx context.Context) (string, error) {
return provider.chainID, nil
}
var result string
// Note: []interface{}{}...force an empty `params[]` in the jsonrpc request
if err := provider.c.CallContext(ctx, &result, "starknet_chainId", []interface{}{}...); err != nil {
return "", Err(InternalError, err)
if err := do(ctx, provider.c, "starknet_chainId", &result); err != nil {
return "", tryUnwrapToRPCErr(err)
}
provider.chainID = utils.HexToShortStr(result)
return provider.chainID, nil
Expand All @@ -41,7 +40,7 @@ func (provider *Provider) Syncing(ctx context.Context) (*SyncStatus, error) {
}
switch res := result.(type) {
case bool:
return &SyncStatus{SyncStatus: res}, nil
return &SyncStatus{SyncStatus: &res}, nil
case SyncStatus:
return &res, nil
default:
Expand Down
Loading
Loading