Saturday, September 30, 2023
BitWolf
  • Cryptocurrency
  • Blockchain
  • Nft & Metaverse
  • Market
  • Bitcoin
  • Ethereum
  • More
    • Solana
    • Litecoin
    • Dogecoin
  • Live Prices
No Result
View All Result
No Result
View All Result
BitWolf

Solidity 0.6.x features: try/catch statement

bitwolf by bitwolf
September 8, 2023
in Ethereum
0 0
0
Home Ethereum



The try/catch syntax introduced in 0.6.0 is arguably the most important leap in error dealing with capabilities in Solidity, since purpose strings for revert and require had been launched in v0.4.22. Each attempt and catch have been reserved key phrases since v0.5.9 and now we will use them to deal with failures in exterior operate calls with out rolling again the whole transaction (state modifications within the referred to as operate are nonetheless rolled again, however the ones within the calling operate will not be).

We’re transferring one step away from the purist “all-or-nothing” strategy in a transaction lifecycle, which falls in need of sensible behaviour we frequently need.

Dealing with exterior name failures

The attempt/catch assertion permits you to react on failed exterior calls and contract creation calls, so you can not use it for inner operate calls. Observe that to wrap a public operate name inside the identical contract with attempt/catch, it may be made exterior by calling the operate with this..

The instance beneath demonstrates how attempt/catch is utilized in a manufacturing unit sample the place contract creation may fail. The next CharitySplitter contract requires a compulsory tackle property _owner in its constructor.

pragma solidity ^0.6.1;

contract CharitySplitter {
    tackle public proprietor;
    constructor (tackle _owner) public {
        require(_owner != tackle(0), "no-owner-provided");
        proprietor = _owner;
    }
}

There’s a manufacturing unit contract — CharitySplitterFactory which is used to create and handle situations of CharitySplitter. Within the manufacturing unit we will wrap the new CharitySplitter(charityOwner) in a attempt/catch as a failsafe for when that constructor may fail due to an empty charityOwner being handed.

pragma solidity ^0.6.1;
import "./CharitySplitter.sol";
contract CharitySplitterFactory {
    mapping (tackle => CharitySplitter) public charitySplitters;
    uint public errorCount;
    occasion ErrorHandled(string purpose);
    occasion ErrorNotHandled(bytes purpose);
    operate createCharitySplitter(tackle charityOwner) public {
        attempt new CharitySplitter(charityOwner)
            returns (CharitySplitter newCharitySplitter)
        {
            charitySplitters[msg.sender] = newCharitySplitter;
        } catch {
            errorCount++;
        }
    }
}

Observe that with attempt/catch, solely exceptions occurring contained in the exterior name itself are caught. Errors contained in the expression will not be caught, for instance if the enter parameter for the new CharitySplitter is itself a part of an inner name, any errors it raises won’t be caught. Pattern demonstrating this behaviour is the modified createCharitySplitter operate. Right here the CharitySplitter constructor enter parameter is retrieved dynamically from one other operate — getCharityOwner. If that operate reverts, on this instance with “revert-required-for-testing”, that won’t be caught within the attempt/catch assertion.

operate createCharitySplitter(tackle _charityOwner) public {
    attempt new CharitySplitter(getCharityOwner(_charityOwner, false))
        returns (CharitySplitter newCharitySplitter)
    {
        charitySplitters[msg.sender] = newCharitySplitter;
    } catch (bytes reminiscence purpose) {
        ...
    }
}
operate getCharityOwner(tackle _charityOwner, bool _toPass)
        inner returns (tackle) {
    require(_toPass, "revert-required-for-testing");
    return _charityOwner;
}

Retrieving the error message

We are able to additional prolong the attempt/catch logic within the createCharitySplitter operate to retrieve the error message if one was emitted by a failing revert or require and emit it in an occasion. There are two methods to realize this:

1. Utilizing catch Error(string reminiscence purpose)

operate createCharitySplitter(tackle _charityOwner) public {
    attempt new CharitySplitter(_charityOwner) returns (CharitySplitter newCharitySplitter)
    {
        charitySplitters[msg.sender] = newCharitySplitter;
    }
    catch Error(string reminiscence purpose)
    {
        errorCount++;
        CharitySplitter newCharitySplitter = new
            CharitySplitter(msg.sender);
        charitySplitters[msg.sender] = newCharitySplitter;
        // Emitting the error in occasion
        emit ErrorHandled(purpose);
    }
    catch
    {
        errorCount++;
    }
}

Which emits the next occasion on a failed constructor require error:

CharitySplitterFactory.ErrorHandled(
    purpose: 'no-owner-provided' (kind: string)
)

2. Utilizing catch (bytes reminiscence purpose)

operate createCharitySplitter(tackle charityOwner) public {
    attempt new CharitySplitter(charityOwner)
        returns (CharitySplitter newCharitySplitter)
    {
        charitySplitters[msg.sender] = newCharitySplitter;
    }
    catch (bytes reminiscence purpose) {
        errorCount++;
        emit ErrorNotHandled(purpose);
    }
}

Which emits the next occasion on a failed constructor require error:

CharitySplitterFactory.ErrorNotHandled(
  purpose: hex'08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000116e6f2d6f776e65722d70726f7669646564000000000000000000000000000000' (kind: bytes)

The above two strategies for retrieving the error string produce an identical outcome. The distinction is that the second technique doesn’t ABI-decode the error string. The benefit of the second technique is that it’s also executed if ABI decoding the error string fails or if no purpose was offered.

Future plans

There are plans to launch assist for error varieties which means we can declare errors in an identical strategy to occasions permitting us to catch completely different kind of errors, for instance:

catch CustomErrorA(uint data1) { … }
catch CustomErrorB(uint[] reminiscence data2) { … }
catch {}



Source link

Tags: 06xFeaturesSoliditystatementtrycatch
ShareTweetShare
BuyBitcoinsWithUsdEur
bitwolf

bitwolf

Next Post
Why 2024 Will Be The Highest Returning Year This Cycle

Why 2024 Will Be The Highest Returning Year This Cycle

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Trending
  • Comments
  • Latest
Bitcoin Holds Above $17K Despite DCG Uncertainty – CoinDesk

Bitcoin Holds Above $17K Despite DCG Uncertainty – CoinDesk

January 10, 2023
Bitcoin community not happy with Peter Zeihan’s criticisms on Joe Rogan podcast

Bitcoin community not happy with Peter Zeihan’s criticisms on Joe Rogan podcast

January 10, 2023
MULN Stock: Mullen Is the New Dogecoin… Without Any of the Fun

MULN Stock: Mullen Is the New Dogecoin… Without Any of the Fun

January 22, 2023
Why Polygon could play a key role in mass blockchain adoption despite MATIC’s…

Why Polygon could play a key role in mass blockchain adoption despite MATIC’s…

January 10, 2023
Cointelegraph Markets Pro delivers alerts for 113% gains from 5 trades in the face of 10% BTC drop

Cointelegraph Markets Pro delivers alerts for 113% gains from 5 trades in the face of 10% BTC drop

50
Why is Cardano price up today?

Why is Cardano price up today?

46
Heavyweight champ Oleksandr Usyk seeks to tokenize boxers’ careers

Heavyweight champ Oleksandr Usyk seeks to tokenize boxers’ careers

36
‘Withdrawals are coming!’ — Ethereum devs confirm epoch for Shapella fork

‘Withdrawals are coming!’ — Ethereum devs confirm epoch for Shapella fork

36
Analyst Predicts 130% Rally To $18

Analyst Predicts 130% Rally To $18

September 30, 2023
Bitcoin Long-Term Metrics Point to a Different Scenario Than 2019 Fakeout: Top Analyst

Bitcoin Long-Term Metrics Point to a Different Scenario Than 2019 Fakeout: Top Analyst

September 29, 2023
Ethereum Network Fees Hit 2023 Low: What It Could Mean For ETH Price

Is The Ethereum Winter Over? L2 Exploding, ETH Futures ETF Launches

September 29, 2023
Invesco Galaxy applies for spot Ether ETF

Invesco Galaxy applies for spot Ether ETF

September 29, 2023

Recent News

Analyst Predicts 130% Rally To $18

Analyst Predicts 130% Rally To $18

September 30, 2023
Bitcoin Long-Term Metrics Point to a Different Scenario Than 2019 Fakeout: Top Analyst

Bitcoin Long-Term Metrics Point to a Different Scenario Than 2019 Fakeout: Top Analyst

September 29, 2023
Ethereum Network Fees Hit 2023 Low: What It Could Mean For ETH Price

Is The Ethereum Winter Over? L2 Exploding, ETH Futures ETF Launches

September 29, 2023

Categories

  • Bitcoin
  • Blockchain
  • Cryptocurrency
  • Dogecoin
  • Ethereum
  • Litecoin
  • Market & Analysis
  • Nft & Metaverse
  • Solana
  • Uncategorized

Tags

Big Binance Bitcoin Blockchain Blog BTC bullish Bulls Coin Coinbase crypto Cryptocurrency Data Digital DOGE Dogecoin ETH Ethereum Exchange eyes Foundation FTX Heres Investors Key launch launches Litecoin LTC market network News NFT NFTs price rally Report SEC Solana token Top Trading Web3 Week XRP

© 2022 BitWolf All Rights Reserved

No Result
View All Result
  • Cryptocurrency
  • Blockchain
  • Nft & Metaverse
  • Market
  • Bitcoin
  • Ethereum
  • More
    • Solana
    • Litecoin
    • Dogecoin
  • Live Prices

© 2022 BitWolf All Rights Reserved

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
Translate »