Linked Questions

Popular Questions

I am calling a function from inside a goroutine which is inside a loop. However, the RPC call inside the function is returning unexpected results:

main function code:

// Define the channel to collect results from all goroutines
    resultsChan := make(chan *ExperimentResult, 10)
    errorChan := make(chan *FunctionCallError, 10)

    var wg sync.WaitGroup
    // Spawn goroutines
    go func() {
        for err := range errorChan {
            log.Printf("Error from goroutine %d: %v", err.GoroutineID, err.Err)
        }
    }()
    for i := 0; i < 3; i++ {
        wg.Add(1) // Add a counter for each goroutine we're about to launch
        i := i
        go func(id int) {
            defer wg.Done()
            log.Printf("Goroutine %d starting for counter contract", id)
            makeFunctionCall(cctx, rpc, accountID, contractID, methodName, keyPair, id, resultsChan, errorChan)
            log.Printf("Goroutine %d completed counter contract", id)
        }(i)
    }

    wg.Wait() // Wait for all goroutines to complete
    close(resultsChan)
    close(errorChan)

The function getting called:

func makeFunctionCall(
    cctx *cli.Context,
    rpc client.Client,
    accountID string,
    contractID string,
    methodName string,
    keyPair key.KeyPair,
    id int,
    resultsChan chan *ExperimentResult,
    errorChan chan *FunctionCallError,

) {
    sentAt := time.Now().UnixNano()

    // Send the transaction
    res, err := rpc.TransactionSendAwait(
        cctx.Context,
        accountID,
        contractID,
        []action.Action{
            action.NewFunctionCall(methodName, nil, types.DefaultFunctionCallGas, types.NEARToYocto(0)),
        },
        client.WithLatestBlock(),
        client.WithKeyPair(keyPair),
    )
    log.Printf("TXN hash: %s , id: %d", res.Transaction.Hash.String(), id)

The results:

2023/08/19 03:57:34 Goroutine 2 starting for counter contract
2023/08/19 03:57:34 Goroutine 1 starting for counter contract
2023/08/19 03:57:34 Goroutine 0 starting for counter contract
2023/08/19 03:57:39 TXN hash: 9wEZw5xZNNvTHMRQxh5J9yaFQpBcPvDBQtpszC41wns9 , id: 2
2023/08/19 03:57:39 TXN hash: 9wEZw5xZNNvTHMRQxh5J9yaFQpBcPvDBQtpszC41wns9 , id: 0
2023/08/19 03:57:39 TXN hash: 9wEZw5xZNNvTHMRQxh5J9yaFQpBcPvDBQtpszC41wns9 , id: 1

The txn hash should be different for each call to the TransactionSendAwait function.

Related Questions