Bird
Raised Fist0
Blockchain / Solidityprogramming~20 mins

Factory pattern in Blockchain / Solidity - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Factory Pattern Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Solidity factory contract?

Consider this Solidity factory contract that creates simple storage contracts. What will be the value of storedData in the newly created contract after deployment?

Blockchain / Solidity
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint public storedData;
    constructor(uint initVal) {
        storedData = initVal;
    }
}

contract StorageFactory {
    SimpleStorage[] public storages;

    function createStorage(uint _initVal) public {
        SimpleStorage s = new SimpleStorage(_initVal);
        storages.push(s);
    }

    function getLastStoredData() public view returns (uint) {
        return storages[storages.length - 1].storedData();
    }
}
AThe value passed to createStorage function
BThe default value of uint (which is 1)
C0
DIt will revert with an error
Attempts:
2 left
💡 Hint

Look at how the SimpleStorage contract is created and initialized.

🧠 Conceptual
intermediate
1:30remaining
Why use a factory pattern in blockchain smart contracts?

Which of the following is the main reason to use a factory pattern in blockchain smart contracts?

ATo reduce gas costs by storing all logic in one contract
BTo automatically upgrade all contracts without redeployment
CTo create multiple instances of a contract with different states easily
DTo prevent any contract from being created on the blockchain
Attempts:
2 left
💡 Hint

Think about how factories help manage many contracts.

🔧 Debug
advanced
2:00remaining
Identify the error in this factory contract code

What error will this Solidity factory contract produce when calling createStorage?

Blockchain / Solidity
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint public storedData;
    constructor(uint initVal) {
        storedData = initVal;
    }
}

contract StorageFactory {
    SimpleStorage[] public storages;

    function createStorage(uint _initVal) public {
        SimpleStorage s = SimpleStorage(_initVal);
        storages.push(s);
    }
}
ASyntaxError: Missing semicolon
BTypeError: Explicit constructor call is not allowed
CNo error, works fine
DRuntime error: Out of gas
Attempts:
2 left
💡 Hint

Check how the new contract instance is created.

📝 Syntax
advanced
1:30remaining
Which option correctly creates a new contract instance in a factory?

Given the contract Child with a constructor that takes a uint, which option correctly creates a new Child instance inside a factory contract?

Blockchain / Solidity
pragma solidity ^0.8.0;

contract Child {
    uint public value;
    constructor(uint _value) {
        value = _value;
    }
}

contract Factory {
    Child[] public children;

    function createChild(uint _val) public {
        // Which line is correct here?
    }
}
AChild c = new Child(_val); children.push(c);
BChild c = Child(_val); children.push(c);
CChild c = Child.new(_val); children.push(c);
DChild c = new Child; children.push(c);
Attempts:
2 left
💡 Hint

Remember the syntax for creating new contract instances in Solidity.

🚀 Application
expert
2:30remaining
How many child contracts are created after these calls?

Given the following factory contract, how many Child contracts exist after these calls?

Calls made in order:

  1. createChild(10)
  2. createChild(20)
  3. createChild(30)
  4. deleteChild(1)
Blockchain / Solidity
pragma solidity ^0.8.0;

contract Child {
    uint public value;
    constructor(uint _value) {
        value = _value;
    }
}

contract Factory {
    Child[] public children;

    function createChild(uint _val) public {
        Child c = new Child(_val);
        children.push(c);
    }

    function deleteChild(uint index) public {
        require(index < children.length, "Index out of range");
        delete children[index];
    }

    function getChildrenCount() public view returns (uint) {
        return children.length;
    }
}
A0
B2
C1
D3
Attempts:
2 left
💡 Hint

Deleting an element from an array in Solidity does not reduce its length.

Practice

(1/5)
1.

What is the main purpose of the Factory pattern in blockchain development?

easy
A. To create multiple similar contracts easily and manage their addresses
B. To encrypt data on the blockchain
C. To mine new blocks faster
D. To validate transactions off-chain

Solution

  1. Step 1: Understand the Factory pattern role

    The Factory pattern is used to create many similar contracts efficiently.
  2. Step 2: Identify its key feature

    It also stores the addresses of these created contracts for easy access later.
  3. Final Answer:

    To create multiple similar contracts easily and manage their addresses -> Option A
  4. Quick Check:

    Factory pattern = create and manage contracts [OK]
Hint: Factory pattern creates and tracks contracts easily [OK]
Common Mistakes:
  • Confusing factory with encryption or mining
  • Thinking factory validates transactions
  • Assuming factory works off-chain
2.

Which of the following is the correct Solidity syntax to deploy a new contract inside a factory contract?

function create() public returns (address) {
    address newContract = new ?();
    return newContract;
}
easy
A. ContractName
B. contractname
C. new ContractName()
D. ContractName()

Solution

  1. Step 1: Recall Solidity contract creation syntax

    To create a new contract instance, use new ContractName().
  2. Step 2: Match syntax with code snippet

    The placeholder new ?() expects the contract name without 'new' repeated.
  3. Final Answer:

    ContractName -> Option A
  4. Quick Check:

    Use 'new ContractName()' but only 'ContractName' inside parentheses [OK]
Hint: Use contract name only inside new keyword parentheses [OK]
Common Mistakes:
  • Writing 'new' twice
  • Using lowercase contract names
  • Omitting parentheses
3.

Consider this Solidity factory contract snippet:

contract Simple {
    uint public value;
    constructor(uint _value) {
        value = _value;
    }
}

contract Factory {
    Simple[] public simples;
    function createSimple(uint _val) public {
        Simple s = new Simple(_val);
        simples.push(s);
    }
    function getValue(uint index) public view returns (uint) {
        return simples[index].value();
    }
}

What will getValue(0) return after calling createSimple(42) once?

medium
A. Address of the contract
B. 0
C. 42
D. Compilation error

Solution

  1. Step 1: Understand contract creation and storage

    Calling createSimple(42) creates a new Simple contract with value = 42 and stores it in simples array.
  2. Step 2: Check what getValue(0) returns

    It returns the value of the first Simple contract, which is 42.
  3. Final Answer:

    42 -> Option C
  4. Quick Check:

    Created contract value = 42 [OK]
Hint: Created contract stores value; getValue returns it [OK]
Common Mistakes:
  • Confusing contract address with stored value
  • Assuming default zero value
  • Thinking it returns array length
4.

Identify the error in this factory contract code snippet:

contract Product {
    uint public id;
    constructor(uint _id) {
        id = _id;
    }
}

contract ProductFactory {
    Product[] public products;
    function createProduct(uint _id) public {
        Product p = Product(_id);
        products.push(p);
    }
}
medium
A. Array products should be a mapping
B. Missing new keyword when creating Product
C. Constructor should not have parameters
D. Function createProduct must be view

Solution

  1. Step 1: Check contract instantiation syntax

    In Solidity, to create a new contract instance, you must use the new keyword.
  2. Step 2: Identify the missing keyword

    The line Product p = Product(_id); misses new, it should be Product p = new Product(_id);.
  3. Final Answer:

    Missing new keyword when creating Product -> Option B
  4. Quick Check:

    Contract creation requires 'new' keyword [OK]
Hint: Always use 'new' to create contracts in Solidity [OK]
Common Mistakes:
  • Forgetting 'new' keyword
  • Changing array to mapping unnecessarily
  • Marking create function as view incorrectly
5.

You want to build a factory contract that creates multiple token contracts with different initial supplies and keeps track of them. Which approach best applies the factory pattern to save gas and organize your project?

hard
A. Use a single token contract and change its supply dynamically for each user
B. Deploy all token contracts manually and hardcode their addresses in the factory
C. Create token contracts but do not store their addresses anywhere
D. Create each token contract separately and store their addresses in an array inside the factory

Solution

  1. Step 1: Understand factory pattern benefits

    The factory pattern helps create many similar contracts and keeps track of them efficiently.
  2. Step 2: Evaluate options for managing multiple tokens

    Creating each token contract inside the factory and storing their addresses allows easy management and gas savings.
  3. Step 3: Reject other options

    Hardcoding addresses is inflexible, using one contract for all tokens breaks isolation, and not storing addresses loses track.
  4. Final Answer:

    Create each token contract separately and store their addresses in an array inside the factory -> Option D
  5. Quick Check:

    Factory creates and tracks contracts for organization [OK]
Hint: Factory creates and stores contracts for easy management [OK]
Common Mistakes:
  • Hardcoding addresses reduces flexibility
  • Using one contract for all tokens causes conflicts
  • Not storing addresses loses track of contracts