diff --git a/chainio/clients/avsregistry/reader.go b/chainio/clients/avsregistry/reader.go index 5aafeae1..dc26f8d5 100644 --- a/chainio/clients/avsregistry/reader.go +++ b/chainio/clients/avsregistry/reader.go @@ -2,7 +2,6 @@ package avsregistry import ( "context" - "errors" "math" "math/big" @@ -10,6 +9,7 @@ import ( "github.com/Layr-Labs/eigensdk-go/crypto/bls" "github.com/Layr-Labs/eigensdk-go/logging" "github.com/Layr-Labs/eigensdk-go/types" + "github.com/Layr-Labs/eigensdk-go/utils" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" @@ -123,26 +123,26 @@ func BuildAvsRegistryChainReader( ) (*AvsRegistryChainReader, error) { contractRegistryCoordinator, err := regcoord.NewContractRegistryCoordinator(registryCoordinatorAddr, ethClient) if err != nil { - return nil, types.WrapError(errors.New("Failed to create contractRegistryCoordinator"), err) + return nil, utils.WrapError("Failed to create contractRegistryCoordinator", err) } blsApkRegistryAddr, err := contractRegistryCoordinator.BlsApkRegistry(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to get blsApkRegistryAddr"), err) + return nil, utils.WrapError("Failed to get blsApkRegistryAddr", err) } stakeRegistryAddr, err := contractRegistryCoordinator.StakeRegistry(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to get stakeRegistryAddr"), err) + return nil, utils.WrapError("Failed to get stakeRegistryAddr", err) } contractStakeRegistry, err := stakeregistry.NewContractStakeRegistry(stakeRegistryAddr, ethClient) if err != nil { - return nil, types.WrapError(errors.New("Failed to create contractStakeRegistry"), err) + return nil, utils.WrapError("Failed to create contractStakeRegistry", err) } contractOperatorStateRetriever, err := opstateretriever.NewContractOperatorStateRetriever( operatorStateRetrieverAddr, ethClient, ) if err != nil { - return nil, types.WrapError(errors.New("Failed to create contractOperatorStateRetriever"), err) + return nil, utils.WrapError("Failed to create contractOperatorStateRetriever", err) } return NewAvsRegistryChainReader( registryCoordinatorAddr, @@ -168,10 +168,10 @@ func (r *AvsRegistryChainReader) GetOperatorsStakeInQuorumsAtCurrentBlock( } curBlock, err := r.ethClient.BlockNumber(opts.Context) if err != nil { - return nil, types.WrapError(errors.New("Cannot get current block number"), err) + return nil, utils.WrapError("Cannot get current block number", err) } if curBlock > math.MaxUint32 { - return nil, types.WrapError(errors.New("Current block number is too large to be converted to uint32"), err) + return nil, utils.WrapError("Current block number is too large to be converted to uint32", err) } return r.GetOperatorsStakeInQuorumsAtBlock(opts, quorumNumbers, uint32(curBlock)) } @@ -189,7 +189,7 @@ func (r *AvsRegistryChainReader) GetOperatorsStakeInQuorumsAtBlock( quorumNumbers.UnderlyingType(), blockNumber) if err != nil { - return nil, types.WrapError(errors.New("Failed to get operators state"), err) + return nil, utils.WrapError("Failed to get operators state", err) } return operatorStakes, nil } @@ -203,10 +203,10 @@ func (r *AvsRegistryChainReader) GetOperatorAddrsInQuorumsAtCurrentBlock( } curBlock, err := r.ethClient.BlockNumber(opts.Context) if err != nil { - return nil, types.WrapError(errors.New("Failed to get current block number"), err) + return nil, utils.WrapError("Failed to get current block number", err) } if curBlock > math.MaxUint32 { - return nil, types.WrapError(errors.New("Current block number is too large to be converted to uint32"), err) + return nil, utils.WrapError("Current block number is too large to be converted to uint32", err) } operatorStakes, err := r.operatorStateRetriever.GetOperatorState( opts, @@ -215,7 +215,7 @@ func (r *AvsRegistryChainReader) GetOperatorAddrsInQuorumsAtCurrentBlock( uint32(curBlock), ) if err != nil { - return nil, types.WrapError(errors.New("Failed to get operators state"), err) + return nil, utils.WrapError("Failed to get operators state", err) } var quorumOperatorAddrs [][]common.Address for _, quorum := range operatorStakes { @@ -240,7 +240,7 @@ func (r *AvsRegistryChainReader) GetOperatorsStakeInQuorumsOfOperatorAtBlock( operatorId, blockNumber) if err != nil { - return nil, nil, types.WrapError(errors.New("Failed to get operators state"), err) + return nil, nil, utils.WrapError("Failed to get operators state", err) } quorums := types.BitmapToQuorumIds(quorumBitmap) return quorums, operatorStakes, nil @@ -257,10 +257,10 @@ func (r *AvsRegistryChainReader) GetOperatorsStakeInQuorumsOfOperatorAtCurrentBl } curBlock, err := r.ethClient.BlockNumber(opts.Context) if err != nil { - return nil, nil, types.WrapError(errors.New("Failed to get current block number"), err) + return nil, nil, utils.WrapError("Failed to get current block number", err) } if curBlock > math.MaxUint32 { - return nil, nil, types.WrapError(errors.New("Current block number is too large to be converted to uint32"), err) + return nil, nil, utils.WrapError("Current block number is too large to be converted to uint32", err) } opts.BlockNumber = big.NewInt(int64(curBlock)) return r.GetOperatorsStakeInQuorumsOfOperatorAtBlock(opts, operatorId, uint32(curBlock)) @@ -275,7 +275,7 @@ func (r *AvsRegistryChainReader) GetOperatorStakeInQuorumsOfOperatorAtCurrentBlo ) (map[types.QuorumNum]types.StakeAmount, error) { quorumBitmap, err := r.registryCoordinator.GetCurrentQuorumBitmap(opts, operatorId) if err != nil { - return nil, types.WrapError(errors.New("Failed to get operator quorums"), err) + return nil, utils.WrapError("Failed to get operator quorums", err) } quorums := types.BitmapToQuorumIds(quorumBitmap) quorumStakes := make(map[types.QuorumNum]types.StakeAmount) @@ -286,7 +286,7 @@ func (r *AvsRegistryChainReader) GetOperatorStakeInQuorumsOfOperatorAtCurrentBlo uint8(quorum), ) if err != nil { - return nil, types.WrapError(errors.New("Failed to get operator stake"), err) + return nil, utils.WrapError("Failed to get operator stake", err) } quorumStakes[quorum] = stake } @@ -311,7 +311,10 @@ func (r *AvsRegistryChainReader) GetCheckSignaturesIndices( nonSignerOperatorIdsBytes, ) if err != nil { - return opstateretriever.OperatorStateRetrieverCheckSignaturesIndices{}, types.WrapError(errors.New("Failed to get check signatures indices"), err) + return opstateretriever.OperatorStateRetrieverCheckSignaturesIndices{}, utils.WrapError( + "Failed to get check signatures indices", + err, + ) } return checkSignatureIndices, nil } @@ -325,7 +328,7 @@ func (r *AvsRegistryChainReader) GetOperatorId( operatorAddress, ) if err != nil { - return [32]byte{}, types.WrapError(errors.New("Failed to get operator id"), err) + return [32]byte{}, utils.WrapError("Failed to get operator id", err) } return operatorId, nil } @@ -339,7 +342,7 @@ func (r *AvsRegistryChainReader) GetOperatorFromId( operatorId, ) if err != nil { - return gethcommon.Address{}, types.WrapError(errors.New("Failed to get operator address"), err) + return gethcommon.Address{}, utils.WrapError("Failed to get operator address", err) } return operatorAddress, nil } @@ -350,7 +353,7 @@ func (r *AvsRegistryChainReader) IsOperatorRegistered( ) (bool, error) { operatorStatus, err := r.registryCoordinator.GetOperatorStatus(opts, operatorAddress) if err != nil { - return false, types.WrapError(errors.New("Failed to get operator status"), err) + return false, utils.WrapError("Failed to get operator status", err) } // 0 = NEVER_REGISTERED, 1 = REGISTERED, 2 = DEREGISTERED @@ -366,7 +369,7 @@ func (r *AvsRegistryChainReader) QueryExistingRegisteredOperatorPubKeys( blsApkRegistryAbi, err := apkreg.ContractBLSApkRegistryMetaData.GetAbi() if err != nil { - return nil, nil, types.WrapError(errors.New("Cannot get Abi"), err) + return nil, nil, utils.WrapError("Cannot get Abi", err) } if startBlock == nil { @@ -375,7 +378,7 @@ func (r *AvsRegistryChainReader) QueryExistingRegisteredOperatorPubKeys( if stopBlock == nil { curBlockNum, err := r.ethClient.BlockNumber(ctx) if err != nil { - return nil, nil, types.WrapError(errors.New("Cannot get current block number"), err) + return nil, nil, utils.WrapError("Cannot get current block number", err) } stopBlock = big.NewInt(int64(curBlockNum)) } @@ -400,9 +403,17 @@ func (r *AvsRegistryChainReader) QueryExistingRegisteredOperatorPubKeys( logs, err := r.ethClient.FilterLogs(ctx, query) if err != nil { - return nil, nil, types.WrapError(errors.New("Cannot filter logs"), err) + return nil, nil, utils.WrapError("Cannot filter logs", err) } - r.logger.Debug("avsRegistryChainReader.QueryExistingRegisteredOperatorPubKeys", "numTransactionLogs", len(logs), "fromBlock", i, "toBlock", toBlock) + r.logger.Debug( + "avsRegistryChainReader.QueryExistingRegisteredOperatorPubKeys", + "numTransactionLogs", + len(logs), + "fromBlock", + i, + "toBlock", + toBlock, + ) for _, vLog := range logs { @@ -412,7 +423,7 @@ func (r *AvsRegistryChainReader) QueryExistingRegisteredOperatorPubKeys( event, err := blsApkRegistryAbi.Unpack("NewPubkeyRegistration", vLog.Data) if err != nil { - return nil, nil, types.WrapError(errors.New("Cannot unpack event data"), err) + return nil, nil, utils.WrapError("Cannot unpack event data", err) } G1Pubkey := event[0].(struct { @@ -456,7 +467,7 @@ func (r *AvsRegistryChainReader) QueryExistingRegisteredOperatorSockets( if stopBlock == nil { curBlockNum, err := r.ethClient.BlockNumber(ctx) if err != nil { - return nil, types.WrapError(errors.New("Cannot get current block number"), err) + return nil, utils.WrapError("Cannot get current block number", err) } stopBlock = big.NewInt(int64(curBlockNum)) } @@ -478,7 +489,7 @@ func (r *AvsRegistryChainReader) QueryExistingRegisteredOperatorSockets( } socketUpdates, err := r.registryCoordinator.FilterOperatorSocketUpdate(filterOpts, nil) if err != nil { - return nil, types.WrapError(errors.New("Cannot filter operator socket updates"), err) + return nil, utils.WrapError("Cannot filter operator socket updates", err) } numSocketUpdates := 0 @@ -486,7 +497,15 @@ func (r *AvsRegistryChainReader) QueryExistingRegisteredOperatorSockets( operatorIdToSocketMap[socketUpdates.Event.OperatorId] = types.Socket(socketUpdates.Event.Socket) numSocketUpdates++ } - r.logger.Debug("avsRegistryChainReader.QueryExistingRegisteredOperatorSockets", "numTransactionLogs", numSocketUpdates, "fromBlock", i, "toBlock", toBlock) + r.logger.Debug( + "avsRegistryChainReader.QueryExistingRegisteredOperatorSockets", + "numTransactionLogs", + numSocketUpdates, + "fromBlock", + i, + "toBlock", + toBlock, + ) } return operatorIdToSocketMap, nil } diff --git a/chainio/clients/avsregistry/subscriber.go b/chainio/clients/avsregistry/subscriber.go index 12833ade..601ff9e5 100644 --- a/chainio/clients/avsregistry/subscriber.go +++ b/chainio/clients/avsregistry/subscriber.go @@ -1,8 +1,6 @@ package avsregistry import ( - "errors" - "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" @@ -11,7 +9,7 @@ import ( blsapkreg "github.com/Layr-Labs/eigensdk-go/contracts/bindings/BLSApkRegistry" regcoord "github.com/Layr-Labs/eigensdk-go/contracts/bindings/RegistryCoordinator" "github.com/Layr-Labs/eigensdk-go/logging" - "github.com/Layr-Labs/eigensdk-go/types" + "github.com/Layr-Labs/eigensdk-go/utils" ) type AvsRegistrySubscriber interface { @@ -47,15 +45,15 @@ func BuildAvsRegistryChainSubscriber( ) (*AvsRegistryChainSubscriber, error) { regCoord, err := regcoord.NewContractRegistryCoordinator(regCoordAddr, ethWsClient) if err != nil { - return nil, types.WrapError(errors.New("Failed to create RegistryCoordinator contract"), err) + return nil, utils.WrapError("Failed to create RegistryCoordinator contract", err) } blsApkRegAddr, err := regCoord.BlsApkRegistry(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to get BLSApkRegistry address from RegistryCoordinator"), err) + return nil, utils.WrapError("Failed to get BLSApkRegistry address from RegistryCoordinator", err) } blsApkReg, err := blsapkreg.NewContractBLSApkRegistry(blsApkRegAddr, ethWsClient) if err != nil { - return nil, types.WrapError(errors.New("Failed to create BLSApkRegistry contract"), err) + return nil, utils.WrapError("Failed to create BLSApkRegistry contract", err) } return NewAvsRegistryChainSubscriber(logger, regCoord, blsApkReg) } @@ -66,7 +64,7 @@ func (s *AvsRegistryChainSubscriber) SubscribeToNewPubkeyRegistrations() (chan * &bind.WatchOpts{}, newPubkeyRegistrationChan, nil, ) if err != nil { - return nil, nil, types.WrapError(errors.New("Failed to subscribe to NewPubkeyRegistration events"), err) + return nil, nil, utils.WrapError("Failed to subscribe to NewPubkeyRegistration events", err) } return newPubkeyRegistrationChan, sub, nil } @@ -77,7 +75,7 @@ func (s *AvsRegistryChainSubscriber) SubscribeToOperatorSocketUpdates() (chan *r &bind.WatchOpts{}, operatorSocketUpdateChan, nil, ) if err != nil { - return nil, nil, types.WrapError(errors.New("Failed to subscribe to OperatorSocketUpdate events"), err) + return nil, nil, utils.WrapError("Failed to subscribe to OperatorSocketUpdate events", err) } return operatorSocketUpdateChan, sub, nil } diff --git a/chainio/clients/avsregistry/writer.go b/chainio/clients/avsregistry/writer.go index b94d0e0c..88c47794 100644 --- a/chainio/clients/avsregistry/writer.go +++ b/chainio/clients/avsregistry/writer.go @@ -9,10 +9,11 @@ import ( "github.com/Layr-Labs/eigensdk-go/chainio/clients/elcontracts" "github.com/Layr-Labs/eigensdk-go/chainio/clients/eth" "github.com/Layr-Labs/eigensdk-go/chainio/txmgr" - "github.com/Layr-Labs/eigensdk-go/chainio/utils" + chainioutils "github.com/Layr-Labs/eigensdk-go/chainio/utils" "github.com/Layr-Labs/eigensdk-go/crypto/bls" "github.com/Layr-Labs/eigensdk-go/logging" "github.com/Layr-Labs/eigensdk-go/types" + "github.com/Layr-Labs/eigensdk-go/utils" "github.com/ethereum/go-ethereum/accounts/abi/bind" gethcommon "github.com/ethereum/go-ethereum/common" gethtypes "github.com/ethereum/go-ethereum/core/types" @@ -117,50 +118,50 @@ func BuildAvsRegistryChainWriter( ) (*AvsRegistryChainWriter, error) { registryCoordinator, err := regcoord.NewContractRegistryCoordinator(registryCoordinatorAddr, ethClient) if err != nil { - return nil, types.WrapError(errors.New("Failed to create RegistryCoordinator contract"), err) + return nil, utils.WrapError("Failed to create RegistryCoordinator contract", err) } operatorStateRetriever, err := opstateretriever.NewContractOperatorStateRetriever( operatorStateRetrieverAddr, ethClient, ) if err != nil { - return nil, types.WrapError(errors.New("Failed to create OperatorStateRetriever contract"), err) + return nil, utils.WrapError("Failed to create OperatorStateRetriever contract", err) } serviceManagerAddr, err := registryCoordinator.ServiceManager(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to get ServiceManager address"), err) + return nil, utils.WrapError("Failed to get ServiceManager address", err) } serviceManager, err := smbase.NewContractServiceManagerBase(serviceManagerAddr, ethClient) if err != nil { - return nil, types.WrapError(errors.New("Failed to create ServiceManager contract"), err) + return nil, utils.WrapError("Failed to create ServiceManager contract", err) } blsApkRegistryAddr, err := registryCoordinator.BlsApkRegistry(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to get BLSApkRegistry address"), err) + return nil, utils.WrapError("Failed to get BLSApkRegistry address", err) } blsApkRegistry, err := blsapkregistry.NewContractBLSApkRegistry(blsApkRegistryAddr, ethClient) if err != nil { - return nil, types.WrapError(errors.New("Failed to create BLSApkRegistry contract"), err) + return nil, utils.WrapError("Failed to create BLSApkRegistry contract", err) } stakeRegistryAddr, err := registryCoordinator.StakeRegistry(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to get StakeRegistry address"), err) + return nil, utils.WrapError("Failed to get StakeRegistry address", err) } stakeRegistry, err := stakeregistry.NewContractStakeRegistry(stakeRegistryAddr, ethClient) if err != nil { - return nil, types.WrapError(errors.New("Failed to create StakeRegistry contract"), err) + return nil, utils.WrapError("Failed to create StakeRegistry contract", err) } delegationManagerAddr, err := stakeRegistry.Delegation(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to get DelegationManager address"), err) + return nil, utils.WrapError("Failed to get DelegationManager address", err) } avsDirectoryAddr, err := serviceManager.AvsDirectory(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to get AvsDirectory address"), err) + return nil, utils.WrapError("Failed to get AvsDirectory address", err) } elReader, err := elcontracts.BuildELChainReader(delegationManagerAddr, avsDirectoryAddr, ethClient, logger) if err != nil { - return nil, types.WrapError(errors.New("Failed to create ELChainReader"), err) + return nil, utils.WrapError("Failed to create ELChainReader", err) } return NewAvsRegistryChainWriter( serviceManagerAddr, @@ -193,17 +194,27 @@ func (w *AvsRegistryChainWriter) RegisterOperatorInQuorumWithAVSRegistryCoordina socket string, ) (*gethtypes.Receipt, error) { operatorAddr := crypto.PubkeyToAddress(operatorEcdsaPrivateKey.PublicKey) - w.logger.Info("registering operator with the AVS's registry coordinator", "avs-service-manager", w.serviceManagerAddr, "operator", operatorAddr, "quorumNumbers", quorumNumbers, "socket", socket) + w.logger.Info( + "registering operator with the AVS's registry coordinator", + "avs-service-manager", + w.serviceManagerAddr, + "operator", + operatorAddr, + "quorumNumbers", + quorumNumbers, + "socket", + socket, + ) // params to register bls pubkey with bls apk registry g1HashedMsgToSign, err := w.registryCoordinator.PubkeyRegistrationMessageHash(&bind.CallOpts{}, operatorAddr) if err != nil { return nil, err } - signedMsg := utils.ConvertToBN254G1Point( - blsKeyPair.SignHashedToCurveMessage(utils.ConvertBn254GethToGnark(g1HashedMsgToSign)).G1Point, + signedMsg := chainioutils.ConvertToBN254G1Point( + blsKeyPair.SignHashedToCurveMessage(chainioutils.ConvertBn254GethToGnark(g1HashedMsgToSign)).G1Point, ) - G1pubkeyBN254 := utils.ConvertToBN254G1Point(blsKeyPair.GetPubKeyG1()) - G2pubkeyBN254 := utils.ConvertToBN254G2Point(blsKeyPair.GetPubKeyG2()) + G1pubkeyBN254 := chainioutils.ConvertToBN254G1Point(blsKeyPair.GetPubKeyG1()) + G2pubkeyBN254 := chainioutils.ConvertToBN254G2Point(blsKeyPair.GetPubKeyG2()) pubkeyRegParams := regcoord.IBLSApkRegistryPubkeyRegistrationParams{ PubkeyRegistrationSignature: signedMsg, PubkeyG1: G1pubkeyBN254, @@ -255,7 +266,17 @@ func (w *AvsRegistryChainWriter) RegisterOperatorInQuorumWithAVSRegistryCoordina if err != nil { return nil, errors.New("failed to send tx with err: " + err.Error()) } - w.logger.Info("successfully registered operator with AVS registry coordinator", "txHash", receipt.TxHash.String(), "avs-service-manager", w.serviceManagerAddr, "operator", operatorAddr, "quorumNumbers", quorumNumbers) + w.logger.Info( + "successfully registered operator with AVS registry coordinator", + "txHash", + receipt.TxHash.String(), + "avs-service-manager", + w.serviceManagerAddr, + "operator", + operatorAddr, + "quorumNumbers", + quorumNumbers, + ) return receipt, nil } @@ -269,7 +290,11 @@ func (w *AvsRegistryChainWriter) UpdateStakesOfEntireOperatorSetForQuorums( if err != nil { return nil, err } - tx, err := w.registryCoordinator.UpdateOperatorsForQuorum(noSendTxOpts, operatorsPerQuorum, quorumNumbers.UnderlyingType()) + tx, err := w.registryCoordinator.UpdateOperatorsForQuorum( + noSendTxOpts, + operatorsPerQuorum, + quorumNumbers.UnderlyingType(), + ) if err != nil { return nil, err } @@ -277,7 +302,13 @@ func (w *AvsRegistryChainWriter) UpdateStakesOfEntireOperatorSetForQuorums( if err != nil { return nil, errors.New("failed to send tx with err: " + err.Error()) } - w.logger.Info("successfully updated stakes for entire operator set", "txHash", receipt.TxHash.String(), "quorumNumbers", quorumNumbers) + w.logger.Info( + "successfully updated stakes for entire operator set", + "txHash", + receipt.TxHash.String(), + "quorumNumbers", + quorumNumbers, + ) return receipt, nil } @@ -299,9 +330,14 @@ func (w *AvsRegistryChainWriter) UpdateStakesOfOperatorSubsetForAllQuorums( if err != nil { return nil, errors.New("failed to send tx with err: " + err.Error()) } - w.logger.Info("successfully updated stakes of operator subset for all quorums", "txHash", receipt.TxHash.String(), "operators", operators) + w.logger.Info( + "successfully updated stakes of operator subset for all quorums", + "txHash", + receipt.TxHash.String(), + "operators", + operators, + ) return receipt, nil - } func (w *AvsRegistryChainWriter) DeregisterOperator( @@ -322,6 +358,11 @@ func (w *AvsRegistryChainWriter) DeregisterOperator( if err != nil { return nil, errors.New("failed to send tx with err: " + err.Error()) } - w.logger.Info("successfully deregistered operator with the AVS's registry coordinator", "txHash", receipt.TxHash.String()) + + w.logger.Info( + "successfully deregistered operator with the AVS's registry coordinator", + "txHash", + receipt.TxHash.String(), + ) return receipt, nil } diff --git a/chainio/clients/builder.go b/chainio/clients/builder.go index 10dd39fe..aa90bcae 100644 --- a/chainio/clients/builder.go +++ b/chainio/clients/builder.go @@ -3,7 +3,6 @@ package clients import ( "context" "crypto/ecdsa" - "errors" "time" "github.com/Layr-Labs/eigensdk-go/chainio/clients/avsregistry" @@ -15,7 +14,7 @@ import ( "github.com/Layr-Labs/eigensdk-go/logging" "github.com/Layr-Labs/eigensdk-go/metrics" "github.com/Layr-Labs/eigensdk-go/signerv2" - "github.com/Layr-Labs/eigensdk-go/types" + "github.com/Layr-Labs/eigensdk-go/utils" "github.com/ethereum/go-ethereum/accounts/abi/bind" gethcommon "github.com/ethereum/go-ethereum/common" "github.com/prometheus/client_golang/prometheus" @@ -61,12 +60,12 @@ func BuildAll( // creating two types of Eth clients: HTTP and WS ethHttpClient, err := eth.NewClient(config.EthHttpUrl) if err != nil { - return nil, types.WrapError(errors.New("Failed to create Eth Http client"), err) + return nil, utils.WrapError("Failed to create Eth Http client", err) } ethWsClient, err := eth.NewClient(config.EthWsUrl) if err != nil { - return nil, types.WrapError(errors.New("Failed to create Eth WS client"), err) + return nil, utils.WrapError("Failed to create Eth WS client", err) } rpcCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) @@ -82,7 +81,7 @@ func BuildAll( pkWallet, err := wallet.NewPrivateKeyWallet(ethHttpClient, signerV2, addr, logger) if err != nil { - return nil, types.WrapError(errors.New("Failed to create transaction sender"), err) + return nil, utils.WrapError("Failed to create transaction sender", err) } txMgr := txmgr.NewSimpleTxManager(pkWallet, ethHttpClient, logger, addr) // creating EL clients: Reader, Writer and Subscriber @@ -93,7 +92,7 @@ func BuildAll( eigenMetrics, ) if err != nil { - return nil, types.WrapError(errors.New("Failed to create EL Reader, Writer and Subscriber"), err) + return nil, utils.WrapError("Failed to create EL Reader, Writer and Subscriber", err) } // creating AVS clients: Reader and Writer @@ -105,7 +104,7 @@ func BuildAll( logger, ) if err != nil { - return nil, types.WrapError(errors.New("Failed to create AVS Registry Reader and Writer"), err) + return nil, utils.WrapError("Failed to create AVS Registry Reader and Writer", err) } return &Clients{ @@ -136,7 +135,7 @@ func (config *BuildAllConfig) buildElClients( logger, ) if err != nil { - return nil, nil, types.WrapError(errors.New("Failed to create AVSRegistryContractBindings"), err) + return nil, nil, utils.WrapError("Failed to create AVSRegistryContractBindings", err) } delegationManagerAddr, err := avsRegistryContractBindings.StakeRegistry.Delegation(&bind.CallOpts{}) @@ -155,7 +154,7 @@ func (config *BuildAllConfig) buildElClients( logger, ) if err != nil { - return nil, nil, types.WrapError(errors.New("Failed to create EigenlayerContractBindings"), err) + return nil, nil, utils.WrapError("Failed to create EigenlayerContractBindings", err) } // get the Reader for the EL contracts @@ -198,7 +197,7 @@ func (config *BuildAllConfig) buildAvsClients( logger, ) if err != nil { - return nil, nil, nil, types.WrapError(errors.New("Failed to create AVSRegistryContractBindings"), err) + return nil, nil, nil, utils.WrapError("Failed to create AVSRegistryContractBindings", err) } avsRegistryChainReader := avsregistry.NewAvsRegistryChainReader( @@ -223,7 +222,7 @@ func (config *BuildAllConfig) buildAvsClients( txMgr, ) if err != nil { - return nil, nil, nil, types.WrapError(errors.New("Failed to create AVSRegistryChainWriter"), err) + return nil, nil, nil, utils.WrapError("Failed to create AVSRegistryChainWriter", err) } // get the Subscriber for Avs Registry contracts @@ -234,7 +233,7 @@ func (config *BuildAllConfig) buildAvsClients( logger, ) if err != nil { - return nil, nil, nil, types.WrapError(errors.New("Failed to create ELChainSubscriber"), err) + return nil, nil, nil, utils.WrapError("Failed to create ELChainSubscriber", err) } return avsRegistryChainReader, avsRegistrySubscriber, avsRegistryChainWriter, nil diff --git a/chainio/clients/elcontracts/reader.go b/chainio/clients/elcontracts/reader.go index 80808535..4c3d9ccf 100644 --- a/chainio/clients/elcontracts/reader.go +++ b/chainio/clients/elcontracts/reader.go @@ -1,7 +1,6 @@ package elcontracts import ( - "errors" "math/big" "github.com/ethereum/go-ethereum/accounts/abi/bind" @@ -12,6 +11,7 @@ import ( chainioutils "github.com/Layr-Labs/eigensdk-go/chainio/utils" "github.com/Layr-Labs/eigensdk-go/logging" "github.com/Layr-Labs/eigensdk-go/types" + "github.com/Layr-Labs/eigensdk-go/utils" avsdirectory "github.com/Layr-Labs/eigensdk-go/contracts/bindings/AVSDirectory" delegationmanager "github.com/Layr-Labs/eigensdk-go/contracts/bindings/DelegationManager" @@ -151,11 +151,11 @@ func (r *ELChainReader) GetStrategyAndUnderlyingToken( ) (*strategy.ContractIStrategy, gethcommon.Address, error) { contractStrategy, err := strategy.NewContractIStrategy(strategyAddr, r.ethClient) if err != nil { - return nil, common.Address{}, types.WrapError(errors.New("Failed to fetch strategy contract"), err) + return nil, common.Address{}, utils.WrapError("Failed to fetch strategy contract", err) } underlyingTokenAddr, err := contractStrategy.UnderlyingToken(opts) if err != nil { - return nil, common.Address{}, types.WrapError(errors.New("Failed to fetch token contract"), err) + return nil, common.Address{}, utils.WrapError("Failed to fetch token contract", err) } return contractStrategy, underlyingTokenAddr, nil } @@ -167,15 +167,15 @@ func (r *ELChainReader) GetStrategyAndUnderlyingERC20Token( ) (*strategy.ContractIStrategy, erc20.ContractIERC20Methods, gethcommon.Address, error) { contractStrategy, err := strategy.NewContractIStrategy(strategyAddr, r.ethClient) if err != nil { - return nil, nil, common.Address{}, types.WrapError(errors.New("Failed to fetch strategy contract"), err) + return nil, nil, common.Address{}, utils.WrapError("Failed to fetch strategy contract", err) } underlyingTokenAddr, err := contractStrategy.UnderlyingToken(opts) if err != nil { - return nil, nil, common.Address{}, types.WrapError(errors.New("Failed to fetch token contract"), err) + return nil, nil, common.Address{}, utils.WrapError("Failed to fetch token contract", err) } contractUnderlyingToken, err := erc20.NewContractIERC20(underlyingTokenAddr, r.ethClient) if err != nil { - return nil, nil, common.Address{}, types.WrapError(errors.New("Failed to fetch token contract"), err) + return nil, nil, common.Address{}, utils.WrapError("Failed to fetch token contract", err) } return contractStrategy, contractUnderlyingToken, underlyingTokenAddr, nil } diff --git a/chainio/clients/elcontracts/writer.go b/chainio/clients/elcontracts/writer.go index 4fc15e10..b06165c2 100644 --- a/chainio/clients/elcontracts/writer.go +++ b/chainio/clients/elcontracts/writer.go @@ -161,7 +161,13 @@ func (w *ELChainWriter) UpdateOperatorDetails( if err != nil { return nil, errors.New("failed to send tx with err: " + err.Error()) } - w.logger.Info("successfully updated operator metadata URI", "txHash", receipt.TxHash.String(), "operator", operator.Address) + w.logger.Info( + "successfully updated operator metadata URI", + "txHash", + receipt.TxHash.String(), + "operator", + operator.Address, + ) tx, err = w.delegationManager.UpdateOperatorMetadataURI(noSendTxOpts, operator.MetadataUrl) if err != nil { @@ -171,7 +177,13 @@ func (w *ELChainWriter) UpdateOperatorDetails( if err != nil { return nil, errors.New("failed to send tx with err: " + err.Error()) } - w.logger.Info("successfully updated operator details", "txHash", receipt.TxHash.String(), "operator", operator.Address) + w.logger.Info( + "successfully updated operator details", + "txHash", + receipt.TxHash.String(), + "operator", + operator.Address, + ) return receipt, nil } diff --git a/chainio/clients/fireblocks/client.go b/chainio/clients/fireblocks/client.go index fc96e840..daa19bd0 100644 --- a/chainio/clients/fireblocks/client.go +++ b/chainio/clients/fireblocks/client.go @@ -44,7 +44,8 @@ type Client interface { CancelTransaction(ctx context.Context, txID string) (bool, error) // ListContracts makes a ListContracts request to the Fireblocks API // It returns a list of whitelisted contracts and their assets for the account. - // This call is used to get the contract ID for a whitelisted contract, which is needed as destination account ID by NewContractCallRequest in a ContractCall + // This call is used to get the contract ID for a whitelisted contract, which is needed as destination account ID by + // NewContractCallRequest in a ContractCall // ref: https://developers.fireblocks.com/reference/get_contracts ListContracts(ctx context.Context) ([]WhitelistedContract, error) // ListVaultAccounts makes a ListVaultAccounts request to the Fireblocks API @@ -72,7 +73,13 @@ type ErrorResponse struct { Code int `json:"code"` } -func NewClient(apiKey string, secretKey []byte, baseURL string, timeout time.Duration, logger logging.Logger) (Client, error) { +func NewClient( + apiKey string, + secretKey []byte, + baseURL string, + timeout time.Duration, + logger logging.Logger, +) (Client, error) { c := http.Client{Timeout: timeout} privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(secretKey) if err != nil { @@ -90,7 +97,8 @@ func NewClient(apiKey string, secretKey []byte, baseURL string, timeout time.Dur } // signJwt signs a JWT token for the Fireblocks API -// mostly copied from the Fireblocks example: https://github.com/fireblocks/developers-hub/blob/main/authentication_examples/go/test.go +// mostly copied from the Fireblocks example: +// https://github.com/fireblocks/developers-hub/blob/main/authentication_examples/go/test.go func (f *client) signJwt(path string, bodyJson interface{}, durationSeconds int64) (string, error) { nonce := uuid.New().String() now := time.Now().Unix() @@ -124,7 +132,8 @@ func (f *client) signJwt(path string, bodyJson interface{}, durationSeconds int6 } // makeRequest makes a request to the Fireblocks API -// mostly copied from the Fireblocks example: https://github.com/fireblocks/developers-hub/blob/main/authentication_examples/go/test.go +// mostly copied from the Fireblocks example: +// https://github.com/fireblocks/developers-hub/blob/main/authentication_examples/go/test.go func (f *client) makeRequest(ctx context.Context, method, path string, body interface{}) ([]byte, error) { // remove query parameters from path and join with baseURL pathURI, err := url.Parse(path) @@ -187,7 +196,12 @@ func (f *client) makeRequest(ctx context.Context, method, path string, body inte if err != nil { return nil, fmt.Errorf("error parsing error response: %w", err) } - return nil, fmt.Errorf("error response (%d) from Fireblocks with code %d: %s", resp.StatusCode, errResp.Code, errResp.Message) + return nil, fmt.Errorf( + "error response (%d) from Fireblocks with code %d: %s", + resp.StatusCode, + errResp.Code, + errResp.Message, + ) } return respBody, nil diff --git a/chainio/clients/fireblocks/contract_call.go b/chainio/clients/fireblocks/contract_call.go index 8d958013..975d6e99 100644 --- a/chainio/clients/fireblocks/contract_call.go +++ b/chainio/clients/fireblocks/contract_call.go @@ -42,14 +42,16 @@ type ContractCallRequest struct { Amount string `json:"amount,omitempty"` ExtraParameters extraParams `json:"extraParameters"` // In case a transaction is stuck, specify the hash of the stuck transaction to replace it - // by this transaction with a higher fee, or to replace it with this transaction with a zero fee and drop it from the blockchain. + // by this transaction with a higher fee, or to replace it with this transaction with a zero fee and drop it from + // the blockchain. ReplaceTxByHash string `json:"replaceTxByHash,omitempty"` // GasPrice and GasLimit are the gas price and gas limit for the transaction. // If GasPrice is specified (non-1559), MaxFee and PriorityFee are not required. GasPrice string `json:"gasPrice,omitempty"` GasLimit string `json:"gasLimit,omitempty"` // MaxFee and PriorityFee are the maximum and priority fees for the transaction. - // If the transaction is stuck, the Fireblocks platform will replace the transaction with a new one with a higher fee. + // If the transaction is stuck, the Fireblocks platform will replace the transaction with a new one with a higher + // fee. // These fields are required if FeeLevel is not specified. MaxFee string `json:"maxFee,omitempty"` PriorityFee string `json:"priorityFee,omitempty"` diff --git a/chainio/clients/wallet/fireblocks_wallet.go b/chainio/clients/wallet/fireblocks_wallet.go index d37606b0..cd3ccc51 100644 --- a/chainio/clients/wallet/fireblocks_wallet.go +++ b/chainio/clients/wallet/fireblocks_wallet.go @@ -22,9 +22,11 @@ var _ Wallet = (*fireblocksWallet)(nil) var ( // ErrNotYetBroadcasted indicates that the transaction has not been broadcasted yet. - // This can happen if the transaction is still being processed by Fireblocks and has not been broadcasted to the blockchain yet. + // This can happen if the transaction is still being processed by Fireblocks and has not been broadcasted to the + // blockchain yet. ErrNotYetBroadcasted = errors.New("transaction not yet broadcasted") - // ErrReceiptNotYetAvailable indicates that the transaction has been broadcasted but has not been confirmed onchain yet. + // ErrReceiptNotYetAvailable indicates that the transaction has been broadcasted but has not been confirmed onchain + // yet. ErrReceiptNotYetAvailable = errors.New("transaction receipt not yet available") ErrTransactionFailed = errors.New("transaction failed") ) @@ -51,7 +53,12 @@ type fireblocksWallet struct { whitelistedContracts map[common.Address]*fireblocks.WhitelistedContract } -func NewFireblocksWallet(fireblocksClient fireblocks.Client, ethClient eth.Client, vaultAccountName string, logger logging.Logger) (Wallet, error) { +func NewFireblocksWallet( + fireblocksClient fireblocks.Client, + ethClient eth.Client, + vaultAccountName string, + logger logging.Logger, +) (Wallet, error) { chainID, err := ethClient.ChainID(context.Background()) if err != nil { return nil, fmt.Errorf("error getting chain ID: %w", err) @@ -89,7 +96,10 @@ func (t *fireblocksWallet) getAccount(ctx context.Context) (*fireblocks.VaultAcc return t.account, nil } -func (t *fireblocksWallet) getWhitelistedContract(ctx context.Context, address common.Address) (*fireblocks.WhitelistedContract, error) { +func (t *fireblocksWallet) getWhitelistedContract( + ctx context.Context, + address common.Address, +) (*fireblocks.WhitelistedContract, error) { assetID, ok := fireblocks.AssetIDByChain[t.chainID.Uint64()] if !ok { return nil, fmt.Errorf("unsupported chain %d", t.chainID.Uint64()) @@ -249,7 +259,12 @@ func (t *fireblocksWallet) GetTransactionReceipt(ctx context.Context, txID TxID) return nil, fmt.Errorf("%w: the Fireblocks transaction %s is in status %s", ErrNotYetBroadcasted, txID, fireblockTx.Status) } - return nil, fmt.Errorf("%w: the Fireblocks transaction %s is in status %s", ErrReceiptNotYetAvailable, txID, fireblockTx.Status) + return nil, fmt.Errorf( + "%w: the Fireblocks transaction %s is in status %s", + ErrReceiptNotYetAvailable, + txID, + fireblockTx.Status, + ) } func (f *fireblocksWallet) SenderAddress(ctx context.Context) (common.Address, error) { @@ -257,7 +272,11 @@ func (f *fireblocksWallet) SenderAddress(ctx context.Context) (common.Address, e if err != nil { return common.Address{}, fmt.Errorf("error getting account: %w", err) } - addresses, err := f.fireblocksClient.GetAssetAddresses(ctx, account.ID, fireblocks.AssetIDByChain[f.chainID.Uint64()]) + addresses, err := f.fireblocksClient.GetAssetAddresses( + ctx, + account.ID, + fireblocks.AssetIDByChain[f.chainID.Uint64()], + ) if err != nil { return common.Address{}, fmt.Errorf("error getting asset addresses: %w", err) } diff --git a/chainio/clients/wallet/fireblocks_wallet_test.go b/chainio/clients/wallet/fireblocks_wallet_test.go index a13c59ae..43dc2e22 100644 --- a/chainio/clients/wallet/fireblocks_wallet_test.go +++ b/chainio/clients/wallet/fireblocks_wallet_test.go @@ -400,12 +400,14 @@ func TestSenderAddress(t *testing.T) { }, }, nil) expectedSenderAddr := "0x0000000000000000000000000000000000000000" - fireblocksClient.EXPECT().GetAssetAddresses(gomock.Any(), "vaultAccountID", assetID).Return([]fireblocks.AssetAddress{ - { - AssetID: assetID, - Address: expectedSenderAddr, - }, - }, nil) + fireblocksClient.EXPECT(). + GetAssetAddresses(gomock.Any(), "vaultAccountID", assetID). + Return([]fireblocks.AssetAddress{ + { + AssetID: assetID, + Address: expectedSenderAddr, + }, + }, nil) addr, err := w.SenderAddress(context.Background()) assert.Nil(t, err) diff --git a/chainio/clients/wallet/privatekey_wallet.go b/chainio/clients/wallet/privatekey_wallet.go index b37947f7..33ae3728 100644 --- a/chainio/clients/wallet/privatekey_wallet.go +++ b/chainio/clients/wallet/privatekey_wallet.go @@ -8,7 +8,7 @@ import ( "github.com/Layr-Labs/eigensdk-go/chainio/clients/eth" "github.com/Layr-Labs/eigensdk-go/logging" "github.com/Layr-Labs/eigensdk-go/signerv2" - sdktypes "github.com/Layr-Labs/eigensdk-go/types" + "github.com/Layr-Labs/eigensdk-go/utils" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" @@ -27,7 +27,12 @@ type privateKeyWallet struct { contracts map[common.Address]*bind.BoundContract } -func NewPrivateKeyWallet(ethClient eth.Client, signer signerv2.SignerFn, signerAddress common.Address, logger logging.Logger) (Wallet, error) { +func NewPrivateKeyWallet( + ethClient eth.Client, + signer signerv2.SignerFn, + signerAddress common.Address, + logger logging.Logger, +) (Wallet, error) { return &privateKeyWallet{ ethClient: ethClient, address: signerAddress, @@ -68,7 +73,7 @@ func (t *privateKeyWallet) SendTransaction(ctx context.Context, tx *types.Transa sendingTx, err := contract.RawTransact(opts, tx.Data()) if err != nil { - return "", sdktypes.WrapError(fmt.Errorf("send: tx %v failed.", tx.Hash().String()), err) + return "", utils.WrapError(fmt.Errorf("send: tx %v failed.", tx.Hash().String()), err) } return sendingTx.Hash().Hex(), nil diff --git a/chainio/utils/bindings.go b/chainio/utils/bindings.go index 5254c8cd..6097aaee 100644 --- a/chainio/utils/bindings.go +++ b/chainio/utils/bindings.go @@ -3,10 +3,8 @@ package utils import ( - "errors" - "github.com/Layr-Labs/eigensdk-go/logging" - "github.com/Layr-Labs/eigensdk-go/types" + "github.com/Layr-Labs/eigensdk-go/utils" "github.com/ethereum/go-ethereum/accounts/abi/bind" gethcommon "github.com/ethereum/go-ethereum/common" @@ -44,30 +42,30 @@ func NewEigenlayerContractBindings( ) (*EigenlayerContractBindings, error) { contractDelegationManager, err := delegationmanager.NewContractDelegationManager(delegationManagerAddr, ethclient) if err != nil { - return nil, types.WrapError(errors.New("Failed to create DelegationManager contract"), err) + return nil, utils.WrapError("Failed to create DelegationManager contract", err) } slasherAddr, err := contractDelegationManager.Slasher(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch Slasher address"), err) + return nil, utils.WrapError("Failed to fetch Slasher address", err) } contractSlasher, err := slasher.NewContractISlasher(slasherAddr, ethclient) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch Slasher contract"), err) + return nil, utils.WrapError("Failed to fetch Slasher contract", err) } strategyManagerAddr, err := contractDelegationManager.StrategyManager(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch StrategyManager address"), err) + return nil, utils.WrapError("Failed to fetch StrategyManager address", err) } contractStrategyManager, err := strategymanager.NewContractStrategyManager(strategyManagerAddr, ethclient) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch StrategyManager contract"), err) + return nil, utils.WrapError("Failed to fetch StrategyManager contract", err) } avsDirectory, err := avsdirectory.NewContractAVSDirectory(avsDirectoryAddr, ethclient) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch AVSDirectory contract"), err) + return nil, utils.WrapError("Failed to fetch AVSDirectory contract", err) } return &EigenlayerContractBindings{ @@ -112,52 +110,52 @@ func NewAVSRegistryContractBindings( ethclient, ) if err != nil { - return nil, types.WrapError(errors.New("Failed to create BLSRegistryCoordinator contract"), err) + return nil, utils.WrapError("Failed to create BLSRegistryCoordinator contract", err) } serviceManagerAddr, err := contractBlsRegistryCoordinator.ServiceManager(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch ServiceManager address"), err) + return nil, utils.WrapError("Failed to fetch ServiceManager address", err) } contractServiceManager, err := servicemanager.NewContractServiceManagerBase( serviceManagerAddr, ethclient, ) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch ServiceManager contract"), err) + return nil, utils.WrapError("Failed to fetch ServiceManager contract", err) } stakeregistryAddr, err := contractBlsRegistryCoordinator.StakeRegistry(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch StakeRegistry address"), err) + return nil, utils.WrapError("Failed to fetch StakeRegistry address", err) } contractStakeRegistry, err := stakeregistry.NewContractStakeRegistry( stakeregistryAddr, ethclient, ) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch StakeRegistry contract"), err) + return nil, utils.WrapError("Failed to fetch StakeRegistry contract", err) } blsApkRegistryAddr, err := contractBlsRegistryCoordinator.BlsApkRegistry(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch BLSPubkeyRegistry address"), err) + return nil, utils.WrapError("Failed to fetch BLSPubkeyRegistry address", err) } contractBlsApkRegistry, err := blsapkregistry.NewContractBLSApkRegistry( blsApkRegistryAddr, ethclient, ) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch BLSPubkeyRegistry contract"), err) + return nil, utils.WrapError("Failed to fetch BLSPubkeyRegistry contract", err) } indexRegistryAddr, err := contractBlsRegistryCoordinator.IndexRegistry(&bind.CallOpts{}) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch IndexRegistry address"), err) + return nil, utils.WrapError("Failed to fetch IndexRegistry address", err) } contractIndexRegistry, err := indexregistry.NewContractIndexRegistry(indexRegistryAddr, ethclient) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch IndexRegistry contract"), err) + return nil, utils.WrapError("Failed to fetch IndexRegistry contract", err) } contractOperatorStateRetriever, err := opstateretriever.NewContractOperatorStateRetriever( @@ -165,7 +163,7 @@ func NewAVSRegistryContractBindings( ethclient, ) if err != nil { - return nil, types.WrapError(errors.New("Failed to fetch OperatorStateRetriever contract"), err) + return nil, utils.WrapError("Failed to fetch OperatorStateRetriever contract", err) } return &AvsRegistryContractBindings{ diff --git a/metrics/collectors/economic/economic.go b/metrics/collectors/economic/economic.go index f9331291..9e374bd6 100644 --- a/metrics/collectors/economic/economic.go +++ b/metrics/collectors/economic/economic.go @@ -9,6 +9,7 @@ import ( "github.com/Layr-Labs/eigensdk-go/chainio/clients/elcontracts" "github.com/Layr-Labs/eigensdk-go/logging" "github.com/Layr-Labs/eigensdk-go/types" + "github.com/Layr-Labs/eigensdk-go/utils" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/prometheus/client_golang/prometheus" @@ -114,7 +115,7 @@ func (ec *Collector) initOperatorId() error { if ec.operatorId == [32]byte{} { operatorId, err := ec.avsRegistryReader.GetOperatorId(&bind.CallOpts{}, ec.operatorAddr) if err != nil { - return types.WrapError(errors.New("Failed to get operator id"), err) + return utils.WrapError("Failed to get operator id", err) } if operatorId == [32]byte{} { return errors.New("operator not registered") diff --git a/metrics/eigenmetrics.go b/metrics/eigenmetrics.go index f372a0b7..39592fcc 100644 --- a/metrics/eigenmetrics.go +++ b/metrics/eigenmetrics.go @@ -3,11 +3,11 @@ package metrics import ( "context" - "errors" "net/http" "github.com/Layr-Labs/eigensdk-go/logging" "github.com/Layr-Labs/eigensdk-go/types" + "github.com/Layr-Labs/eigensdk-go/utils" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" @@ -87,7 +87,7 @@ func (m *EigenMetrics) Start(ctx context.Context, reg prometheus.Gatherer) <-cha )) err := http.ListenAndServe(m.ipPortAddress, nil) if err != nil { - errC <- types.WrapError(errors.New("Prometheus server failed"), err) + errC <- utils.WrapError("Prometheus server failed", err) } else { errC <- nil } diff --git a/services/avsregistry/avsregistry_chaincaller.go b/services/avsregistry/avsregistry_chaincaller.go index 304d8375..5be8f31d 100644 --- a/services/avsregistry/avsregistry_chaincaller.go +++ b/services/avsregistry/avsregistry_chaincaller.go @@ -2,7 +2,6 @@ package avsregistry import ( "context" - "errors" "fmt" "math/big" @@ -11,6 +10,7 @@ import ( "github.com/Layr-Labs/eigensdk-go/logging" opinfoservice "github.com/Layr-Labs/eigensdk-go/services/operatorsinfo" "github.com/Layr-Labs/eigensdk-go/types" + "github.com/Layr-Labs/eigensdk-go/utils" "github.com/ethereum/go-ethereum/accounts/abi/bind" ) @@ -37,7 +37,7 @@ func (ar *AvsRegistryServiceChainCaller) GetOperatorsAvsStateAtBlock(ctx context // Get operator state for each quorum by querying BLSOperatorStateRetriever (this call is why this service implementation is called ChainCaller) operatorsStakesInQuorums, err := ar.AvsRegistryReader.GetOperatorsStakeInQuorumsAtBlock(&bind.CallOpts{Context: ctx}, quorumNumbers, blockNumber) if err != nil { - return nil, types.WrapError(errors.New("Failed to get operator state"), err) + return nil, utils.WrapError("Failed to get operator state", err) } numquorums := len(quorumNumbers) if len(operatorsStakesInQuorums) != numquorums { @@ -48,7 +48,7 @@ func (ar *AvsRegistryServiceChainCaller) GetOperatorsAvsStateAtBlock(ctx context for _, operator := range operatorsStakesInQuorums[quorumIdx] { info, err := ar.getOperatorInfo(ctx, operator.OperatorId) if err != nil { - return nil, types.WrapError(errors.New("Failed to get operatorInfo for operator while building operatorsAvsState"), err) + return nil, utils.WrapError("Failed to find pubkeys for operator while building operatorsAvsState", err) } if operatorAvsState, ok := operatorsAvsState[operator.OperatorId]; ok { operatorAvsState.StakePerQuorum[quorumNum] = operator.Stake @@ -72,7 +72,7 @@ func (ar *AvsRegistryServiceChainCaller) GetOperatorsAvsStateAtBlock(ctx context func (ar *AvsRegistryServiceChainCaller) GetQuorumsAvsStateAtBlock(ctx context.Context, quorumNumbers types.QuorumNums, blockNumber types.BlockNum) (map[types.QuorumNum]types.QuorumAvsState, error) { operatorsAvsState, err := ar.GetOperatorsAvsStateAtBlock(ctx, quorumNumbers, blockNumber) if err != nil { - return nil, types.WrapError(errors.New("Failed to get quorum state"), err) + return nil, utils.WrapError("Failed to get quorum state", err) } quorumsAvsState := make(map[types.QuorumNum]types.QuorumAvsState) for _, quorumNum := range quorumNumbers { @@ -98,7 +98,7 @@ func (ar *AvsRegistryServiceChainCaller) GetQuorumsAvsStateAtBlock(ctx context.C func (ar *AvsRegistryServiceChainCaller) getOperatorInfo(ctx context.Context, operatorId types.OperatorId) (types.OperatorInfo, error) { operatorAddr, err := ar.AvsRegistryReader.GetOperatorFromId(&bind.CallOpts{Context: ctx}, operatorId) if err != nil { - return types.OperatorInfo{}, types.WrapError(errors.New("Failed to get operator address from pubkey hash"), err) + return types.OperatorInfo{}, utils.WrapError("Failed to get operator address from pubkey hash", err) } info, ok := ar.operatorInfoService.GetOperatorInfo(ctx, operatorAddr) if !ok { diff --git a/services/bls_aggregation/blsagg.go b/services/bls_aggregation/blsagg.go index 4de050e6..d470da18 100644 --- a/services/bls_aggregation/blsagg.go +++ b/services/bls_aggregation/blsagg.go @@ -13,6 +13,7 @@ import ( "github.com/Layr-Labs/eigensdk-go/logging" "github.com/Layr-Labs/eigensdk-go/services/avsregistry" "github.com/Layr-Labs/eigensdk-go/types" + "github.com/Layr-Labs/eigensdk-go/utils" "github.com/ethereum/go-ethereum/accounts/abi/bind" ) @@ -311,7 +312,7 @@ func (a *BlsAggregatorService) singleTaskAggregatorGoroutineFunc( indices, err := a.avsRegistryService.GetCheckSignaturesIndices(&bind.CallOpts{}, taskCreatedBlock, quorumNumbers, nonSignersOperatorIds) if err != nil { a.aggregatedResponsesC <- BlsAggregationServiceResponse{ - Err: types.WrapError(errors.New("Failed to get check signatures indices"), err), + Err: utils.WrapError(errors.New("Failed to get check signatures indices"), err), } return } diff --git a/signer/basic_signer.go b/signer/basic_signer.go index 52b58648..778c214c 100644 --- a/signer/basic_signer.go +++ b/signer/basic_signer.go @@ -3,13 +3,11 @@ package signer import ( "context" "crypto/ecdsa" - "errors" "fmt" "math/big" sdkethclient "github.com/Layr-Labs/eigensdk-go/chainio/clients/eth" "github.com/Layr-Labs/eigensdk-go/logging" - "github.com/Layr-Labs/eigensdk-go/types" "github.com/Layr-Labs/eigensdk-go/utils" "github.com/ethereum/go-ethereum" @@ -40,7 +38,7 @@ func NewBasicSigner( accountAddress, err := utils.EcdsaPrivateKeyToAddress(privateKey) if err != nil { - return nil, types.WrapError(errors.New("Cannot get account address"), err) + return nil, utils.WrapError("Cannot get account address", err) } return &BasicSigner{ @@ -60,11 +58,11 @@ func NewBasicSigner( func (s *BasicSigner) GetNoSendTransactOpts() (*bind.TransactOpts, error) { chainIDBigInt, err := s.ethClient.ChainID(context.Background()) if err != nil { - return nil, types.WrapError(errors.New("Cannot get chainId"), err) + return nil, utils.WrapError("Cannot get chainId", err) } opts, err := bind.NewKeyedTransactorWithChainID(s.privateKey, chainIDBigInt) if err != nil { - return nil, types.WrapError(errors.New("Cannot create NoSendTransactOpts"), err) + return nil, utils.WrapError("Cannot create NoSendTransactOpts", err) } opts.NoSend = true return opts, nil @@ -123,7 +121,7 @@ func (s *BasicSigner) EstimateGasPriceAndLimitAndSendTx( opts, err := bind.NewKeyedTransactorWithChainID(s.privateKey, tx.ChainId()) if err != nil { - return nil, types.WrapError(errors.New("Cannot create transactOpts"), err) + return nil, utils.WrapError("Cannot create transactOpts", err) } opts.Context = ctx opts.Nonce = new(big.Int).SetUint64(tx.Nonce()) @@ -142,7 +140,7 @@ func (s *BasicSigner) EstimateGasPriceAndLimitAndSendTx( tx, err = contract.RawTransact(opts, tx.Data()) if err != nil { - return nil, types.WrapError(fmt.Errorf("Failed to send transaction with tag: %v", tag), err) + return nil, utils.WrapError(fmt.Errorf("Failed to send transaction with tag: %v", tag), err) } receipt, err := s.EnsureTransactionEvaled( @@ -159,10 +157,16 @@ func (s *BasicSigner) EstimateGasPriceAndLimitAndSendTx( func (s *BasicSigner) EnsureTransactionEvaled(tx *gethtypes.Transaction, tag string) (*gethtypes.Receipt, error) { receipt, err := bind.WaitMined(context.Background(), s.ethClient, tx) if err != nil { - return nil, types.WrapError(fmt.Errorf("Failed to wait for transaction to mine with tag: %v", tag), err) + return nil, utils.WrapError(fmt.Errorf("Failed to wait for transaction to mine with tag: %v", tag), err) } if receipt.Status != 1 { - return nil, fmt.Errorf("Transaction failed (tag: %v, txHash: %v, status: %v, gasUsed: %v)", tag, tx.Hash().Hex(), receipt.Status, receipt.GasUsed) + return nil, fmt.Errorf( + "Transaction failed (tag: %v, txHash: %v, status: %v, gasUsed: %v)", + tag, + tx.Hash().Hex(), + receipt.Status, + receipt.GasUsed, + ) } s.logger.Debug("successfully submitted transaction", "txHash", receipt.TxHash.Hex(), diff --git a/types/errors.go b/types/errors.go index 01d347a6..271b0c5e 100644 --- a/types/errors.go +++ b/types/errors.go @@ -23,20 +23,3 @@ var ( ErrUnmarshalOperatorMetadata = errors.New("unable to unmarshal operator metadata") ErrReadingMetadataUrlResponse = errors.New("error reading metadata url body") ) - -func WrapError(mainErr error, subErr error) error { - // Some times the wrap will wrap a nil error - if mainErr == nil && subErr == nil { - return nil - } - - if mainErr == nil && subErr != nil { - return fmt.Errorf("sub error: %w", subErr) - } - - if mainErr != nil && subErr == nil { - return fmt.Errorf("%w: unknown sub error", mainErr) - } - - return fmt.Errorf("%w: %w", mainErr, subErr) -} diff --git a/types/operator.go b/types/operator.go index e31663a7..7f0c4eb0 100644 --- a/types/operator.go +++ b/types/operator.go @@ -3,13 +3,14 @@ package types import ( "encoding/json" "fmt" + "log/slog" + "math/big" + "github.com/Layr-Labs/eigensdk-go/crypto/bls" "github.com/Layr-Labs/eigensdk-go/utils" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/crypto" - "log/slog" - "math/big" apkreg "github.com/Layr-Labs/eigensdk-go/contracts/bindings/BLSApkRegistry" ) @@ -47,12 +48,12 @@ func (o Operator) Validate() error { err := utils.CheckIfUrlIsValid(o.MetadataUrl) if err != nil { - return WrapError(ErrInvalidMetadataUrl, err) + return utils.WrapError(ErrInvalidMetadataUrl, err) } body, err := utils.ReadPublicURL(o.MetadataUrl) if err != nil { - return WrapError(ErrReadingMetadataUrlResponse, err) + return utils.WrapError(ErrReadingMetadataUrlResponse, err) } operatorMetadata := OperatorMetadata{} diff --git a/types/operator_metadata.go b/types/operator_metadata.go index afa317a9..b80a5881 100644 --- a/types/operator_metadata.go +++ b/types/operator_metadata.go @@ -33,12 +33,12 @@ type OperatorMetadata struct { func (om *OperatorMetadata) Validate() error { err := utils.ValidateText(om.Name) if err != nil { - return WrapError(ErrInvalidName, err) + return utils.WrapError(ErrInvalidName, err) } err = utils.ValidateText(om.Description) if err != nil { - return WrapError(ErrInvalidDescription, err) + return utils.WrapError(ErrInvalidDescription, err) } if len(om.Logo) == 0 { @@ -52,14 +52,14 @@ func (om *OperatorMetadata) Validate() error { if len(om.Website) != 0 { err = utils.CheckIfUrlIsValid(om.Website) if err != nil { - return WrapError(ErrInvalidWebsiteUrl, err) + return utils.WrapError(ErrInvalidWebsiteUrl, err) } } if len(om.Twitter) != 0 { err := utils.CheckIfValidTwitterURL(om.Twitter) if err != nil { - return WrapError(ErrInvalidTwitterUrl, err) + return utils.WrapError(ErrInvalidTwitterUrl, err) } } diff --git a/types/operator_metadata_test.go b/types/operator_metadata_test.go index 7abb2463..23af3967 100644 --- a/types/operator_metadata_test.go +++ b/types/operator_metadata_test.go @@ -1,9 +1,10 @@ package types import ( - "github.com/Layr-Labs/eigensdk-go/utils" "testing" + "github.com/Layr-Labs/eigensdk-go/utils" + "github.com/stretchr/testify/assert" ) @@ -52,7 +53,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "https://twitter.com/test", Website: "https://test.com", }, - expectedError: WrapError(ErrInvalidName, utils.ErrEmptyText), + expectedError: utils.WrapError(ErrInvalidName, utils.ErrEmptyText), }, { name: "Invalid metadata - name has js script", @@ -63,7 +64,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "https://twitter.com/test", Website: "https://test.com", }, - expectedError: WrapError(ErrInvalidName, utils.ErrInvalidText), + expectedError: utils.WrapError(ErrInvalidName, utils.ErrInvalidText), }, { name: "Invalid metadata - no description", @@ -74,7 +75,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "https://twitter.com/test", Website: "https://test.com", }, - expectedError: WrapError(ErrInvalidDescription, utils.ErrEmptyText), + expectedError: utils.WrapError(ErrInvalidDescription, utils.ErrEmptyText), }, { name: "Invalid metadata - wrong image format", @@ -107,7 +108,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "https://twitter.com/test", Website: "https://test.com", }, - expectedError: WrapError(ErrInvalidName, utils.ErrTextTooLong), + expectedError: utils.WrapError(ErrInvalidName, utils.ErrTextTooLong), }, { name: "Invalid metadata - description > 200 characters", @@ -118,7 +119,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "https://twitter.com/test", Website: "https://test.com", }, - expectedError: WrapError(ErrInvalidDescription, utils.ErrTextTooLong), + expectedError: utils.WrapError(ErrInvalidDescription, utils.ErrTextTooLong), }, { name: "Invalid metadata - no logo", @@ -140,7 +141,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "ftp://twitter.com/test", Website: "https://test.com", }, - expectedError: WrapError(ErrInvalidTwitterUrl, utils.ErrInvalidTwitterUrlRegex), + expectedError: utils.WrapError(ErrInvalidTwitterUrl, utils.ErrInvalidTwitterUrlRegex), }, { name: "Invalid metadata - invalid logo no extension", @@ -162,7 +163,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "https://twitter.com/test", Website: "https", }, - expectedError: WrapError(ErrInvalidWebsiteUrl, utils.ErrInvalidUrl), + expectedError: utils.WrapError(ErrInvalidWebsiteUrl, utils.ErrInvalidUrl), }, { name: "Invalid metadata - invalid website url #2", @@ -173,7 +174,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "https://twitter.com/test", Website: "https:/test.com", }, - expectedError: WrapError(ErrInvalidWebsiteUrl, utils.ErrInvalidUrl), + expectedError: utils.WrapError(ErrInvalidWebsiteUrl, utils.ErrInvalidUrl), }, { name: "Invalid metadata - invalid website url #3", @@ -184,7 +185,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "https://twitter.com/test", Website: "ps://test.com", }, - expectedError: WrapError(ErrInvalidWebsiteUrl, utils.ErrInvalidUrl), + expectedError: utils.WrapError(ErrInvalidWebsiteUrl, utils.ErrInvalidUrl), }, { name: "Invalid metadata - invalid twitter url #1", @@ -195,7 +196,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "http", Website: "https://test.com", }, - expectedError: WrapError(ErrInvalidTwitterUrl, utils.ErrInvalidUrl), + expectedError: utils.WrapError(ErrInvalidTwitterUrl, utils.ErrInvalidUrl), }, { name: "Invalid metadata - invalid twitter url #2", @@ -206,7 +207,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "ht://twitter.com/test", Website: "https://test.com", }, - expectedError: WrapError(ErrInvalidTwitterUrl, utils.ErrInvalidTwitterUrlRegex), + expectedError: utils.WrapError(ErrInvalidTwitterUrl, utils.ErrInvalidTwitterUrlRegex), }, { name: "Invalid metadata - invalid twitter url #3", @@ -217,7 +218,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "https:/twitt", Website: "https://test.com", }, - expectedError: WrapError(ErrInvalidTwitterUrl, utils.ErrInvalidUrl), + expectedError: utils.WrapError(ErrInvalidTwitterUrl, utils.ErrInvalidUrl), }, { name: "Invalid metadata - invalid twitter url #4 - not twitter url", @@ -228,7 +229,7 @@ func TestOperatorMetadata(t *testing.T) { Twitter: "https://facebook.com/test", Website: "https://test.com", }, - expectedError: WrapError(ErrInvalidTwitterUrl, utils.ErrInvalidTwitterUrlRegex), + expectedError: utils.WrapError(ErrInvalidTwitterUrl, utils.ErrInvalidTwitterUrlRegex), }, } diff --git a/types/operator_test.go b/types/operator_test.go index 12fb71a2..3dbde0d7 100644 --- a/types/operator_test.go +++ b/types/operator_test.go @@ -50,7 +50,7 @@ func TestOperatorValidate(t *testing.T) { MetadataUrl: "", }, wantErr: true, - expectedErr: WrapError(ErrInvalidMetadataUrl, utils.ErrEmptyUrl), + expectedErr: utils.WrapError(ErrInvalidMetadataUrl, utils.ErrEmptyUrl), }, { name: "failed operator validation - localhost metadata url", @@ -62,7 +62,7 @@ func TestOperatorValidate(t *testing.T) { MetadataUrl: "http://localhost:8080/metadata.json", }, wantErr: true, - expectedErr: WrapError(ErrInvalidMetadataUrl, utils.ErrUrlPointingToLocalServer), + expectedErr: utils.WrapError(ErrInvalidMetadataUrl, utils.ErrUrlPointingToLocalServer), }, { name: "failed operator validation - 127.0.0.1 metadata url", @@ -74,7 +74,7 @@ func TestOperatorValidate(t *testing.T) { MetadataUrl: "http://127.0.0.1:8080/metadata.json", }, wantErr: true, - expectedErr: WrapError(ErrInvalidMetadataUrl, utils.ErrUrlPointingToLocalServer), + expectedErr: utils.WrapError(ErrInvalidMetadataUrl, utils.ErrUrlPointingToLocalServer), }, { name: "failed operator validation - bad metadata", @@ -85,8 +85,11 @@ func TestOperatorValidate(t *testing.T) { StakerOptOutWindowBlocks: 100, MetadataUrl: "https://example.com/metadata.json", }, - wantErr: true, - expectedErr: WrapError(ErrReadingMetadataUrlResponse, errors.New("error fetching url: 404 Not Found")), + wantErr: true, + expectedErr: utils.WrapError( + ErrReadingMetadataUrlResponse, + errors.New("error fetching url: 404 Not Found"), + ), }, { name: "failed operator validation - wrong operator address", diff --git a/utils/errors.go b/utils/errors.go index 6aefd07a..61d37cde 100644 --- a/utils/errors.go +++ b/utils/errors.go @@ -23,3 +23,34 @@ var ( "invalid twitter url, it should be of the format https://twitter.com/ or https://x.com/", ) ) + +func TypedErr(e interface{}) error { + switch t := e.(type) { + case error: + return t + case string: + return errors.New(t) + default: + return nil + } +} + +func WrapError(mainErr interface{}, subErr interface{}) error { + var main, sub error + main = TypedErr(mainErr) + sub = TypedErr(subErr) + // Some times the wrap will wrap a nil error + if main == nil && sub == nil { + return nil + } + + if main == nil && sub != nil { + return sub + } + + if main != nil && sub == nil { + return main + } + + return fmt.Errorf("%w: %w", main, sub) +} diff --git a/utils/utils.go b/utils/utils.go index 23577b85..11a15480 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -8,11 +8,12 @@ import ( "strings" "time" + "log" + "math/big" + gethcommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "gopkg.in/yaml.v3" - "log" - "math/big" "fmt" "io" @@ -239,6 +240,7 @@ func ValidateText(text string) error { return nil } + func ValidateRawGithubUrl(url string) error { // Basic validation err := CheckBasicURLValidation(url)