<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pedro Torres on Medium]]></title>
        <description><![CDATA[Stories by Pedro Torres on Medium]]></description>
        <link>https://medium.com/@pedrolisboa_10855?source=rss-190cca8c97c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eHaSvHF5vzL3gTeSMLI-Vw.jpeg</url>
            <title>Stories by Pedro Torres on Medium</title>
            <link>https://medium.com/@pedrolisboa_10855?source=rss-190cca8c97c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:07:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pedrolisboa_10855/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Events in Solidity: Tracking Key Data on the Blockchain (Article 7 of 16 in the Solidity Series)]]></title>
            <link>https://medium.com/@pedrolisboa_10855/events-in-solidity-tracking-key-data-on-the-blockchain-article-7-of-16-in-the-solidity-series-4c3157f89281?source=rss-190cca8c97c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c3157f89281</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Pedro Torres]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 19:42:21 GMT</pubDate>
            <atom:updated>2025-01-05T19:42:21.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*s0AjAsSngShGcT8wh6PG6w.png" /></figure><h3>Introduction</h3><p>In Solidity, events serve as an essential mechanism for tracking and recording key data on the blockchain. They enable decentralized applications (dApps) to efficiently communicate with off-chain systems, providing a structured and low-cost way to capture and query historical blockchain data. In this seventh article of our 16-article Solidity series, we delve into how to utilize events in smart contracts and their critical role in blockchain applications. Let’s explore the concept, its practical applications, and the steps to create, compile, execute, and test contracts that leverage events.</p><h3>What Are Events in Solidity?</h3><p>Events in Solidity are interfaces between the smart contract and the EVM (Ethereum Virtual Machine) log system. When emitted, they generate logs stored on the blockchain, which can be accessed by off-chain systems, such as a frontend or indexing service, to track important information like state changes or transaction details.</p><h3>Syntax and Use Cases</h3><p>Declaring an event in Solidity follows a simple syntax:</p><pre>// Declare the event<br>event Transfer(address indexed from, address indexed to, uint256 value);<br><br>// Emit the event<br>emit Transfer(msg.sender, recipient, amount);</pre><p>Key points:</p><ul><li><strong>Indexed Parameters</strong>: The indexed keyword allows up to three parameters to be stored in the blockchain’s index, enabling efficient querying and filtering.</li><li><strong>Non-Indexed Parameters</strong>: Parameters without indexed are stored in the event but cannot be searched efficiently.</li></ul><h3>Practical Example: Token Transfer Logs</h3><p>Below is an example demonstrating the use of events to log token transfers in an ERC-20-like contract:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract Token {<br>    string public name = &quot;ExampleToken&quot;;<br>    string public symbol = &quot;EXT&quot;;<br>    uint8 public decimals = 18;<br>    uint256 public totalSupply;<br>    mapping(address =&gt; uint256) public balanceOf;<br>    event Transfer(address indexed from, address indexed to, uint256 value);<br>    constructor(uint256 _initialSupply) {<br>        totalSupply = _initialSupply * 10 ** uint256(decimals);<br>        balanceOf[msg.sender] = totalSupply;<br>    }<br>    function transfer(address _to, uint256 _value) public returns (bool success) {<br>        require(balanceOf[msg.sender] &gt;= _value, &quot;Insufficient balance&quot;);<br>        balanceOf[msg.sender] -= _value;<br>        balanceOf[_to] += _value;<br>        emit Transfer(msg.sender, _to, _value);<br>        return true;<br>    }<br>}</pre><h3>Compiling the Code</h3><ol><li>Save the above contract in a file named Token.sol.</li><li>Use a Solidity compiler, such as Remix or solc, to compile the code:</li></ol><pre>solc --optimize --bin --abi Token.sol -o build/</pre><ol><li>Verify that the compilation produces the Token contract bytecode and ABI in the build/ directory.</li></ol><h3>Deploying and Testing the Contract</h3><h4>Deploy</h4><p>Use Remix, Hardhat, or Truffle to deploy the contract. With Hardhat, you can deploy using:</p><pre>const { ethers } = require(&quot;hardhat&quot;);<br><br>async function main() {<br>    const Token = await ethers.getContractFactory(&quot;Token&quot;);<br>    const token = await Token.deploy(1000000); // Deploy with initial supply<br>    console.log(&quot;Token deployed to:&quot;, token.address);<br>}<br>main().catch((error) =&gt; {<br>    console.error(error);<br>    process.exitCode = 1;<br>});</pre><h4>Emit Events</h4><p>Call the transfer function to emit the Transfer event:</p><pre>await token.transfer(&quot;0xRecipientAddress&quot;, 500);</pre><h4>Listen to Events</h4><p>Use a library like ethers.js to listen to the emitted event:</p><pre>contract.on(&quot;Transfer&quot;, (from, to, value, event) =&gt; {<br>    console.log(`${from} transferred ${value} tokens to ${to}`);<br>});</pre><h3>Benefits of Using Events</h3><ol><li><strong>Efficient Data Tracking</strong>: Events enable lightweight and efficient tracking of blockchain activities.</li><li><strong>Cost-Effective</strong>: Emitting events incurs lower gas costs compared to writing data directly to the blockchain.</li><li><strong>Querying and Filtering</strong>: Indexed parameters facilitate quick access to specific logs without the need to process all stored data.</li></ol><h3>Limitations</h3><ol><li><strong>Immutability</strong>: Events cannot be modified or deleted once emitted.</li><li><strong>No Guarantee of Delivery</strong>: Events are not part of the state and may not be reliably delivered to off-chain listeners.</li><li><strong>Limited Indexing</strong>: Only up to three parameters can be indexed, which may be restrictive for complex use cases.</li></ol><h3>Best Practices</h3><ol><li><strong>Minimize Event Usage</strong>: Emit events only for significant state changes or important data.</li><li><strong>Use Indexed Parameters Wisely</strong>: Prioritize frequently queried parameters for indexing.</li><li><strong>Test Thoroughly</strong>: Ensure emitted events provide accurate and complete information.</li></ol><h3>Conclusion</h3><p>Events in Solidity play a pivotal role in the ecosystem of blockchain development. They provide a bridge between on-chain and off-chain systems, enabling developers to efficiently track and analyze key data without incurring significant gas costs. By following the examples and best practices outlined in this article, you can effectively incorporate events into your Solidity contracts to enhance functionality and usability.</p><p>In the next article, we will explore advanced state management techniques in Solidity. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c3157f89281" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Security in Solidity: Protecting Your Smart Contract (Article 6 of 16 in the Solidity Series)]]></title>
            <link>https://medium.com/@pedrolisboa_10855/security-in-solidity-protecting-your-smart-contract-article-6-of-16-in-the-solidity-series-4a5c997bfc58?source=rss-190cca8c97c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a5c997bfc58</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Pedro Torres]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 19:00:33 GMT</pubDate>
            <atom:updated>2025-01-03T19:00:33.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*sp3Z7H8GA0mJ-GzxvjFXtA.png" /></figure><h3>Introduction</h3><p>In this sixth installment of our 16-article series on Solidity, we delve into the critical topic of smart contract security. Protecting your contract from vulnerabilities like reentrancy, integer overflow/underflow, and frontrunning is paramount for ensuring reliability and user trust.</p><h3>Common Vulnerabilities in Solidity and How to Mitigate Them</h3><h3>1. Reentrancy</h3><p>Reentrancy occurs when a malicious contract repeatedly calls a vulnerable function before the first invocation completes. This can drain funds or disrupt functionality.</p><h4>Example of a Vulnerable Contract:</h4><pre>pragma solidity ^0.8.0;<br><br>contract Vulnerable {<br>    mapping(address =&gt; uint) public balances;<br>    function deposit() public payable {<br>        balances[msg.sender] += msg.value;<br>    }<br>    function withdraw(uint _amount) public {<br>        require(balances[msg.sender] &gt;= _amount, &quot;Insufficient balance&quot;);<br>        payable(msg.sender).call{value: _amount}(&quot;&quot;);<br>        balances[msg.sender] -= _amount;<br>    }<br>}</pre><h4>Mitigation:</h4><ul><li><strong>Use the Checks-Effects-Interactions pattern</strong>: Perform all state changes (checks and effects) before making external calls (interactions).</li></ul><pre>function withdraw(uint _amount) public {<br>    require(balances[msg.sender] &gt;= _amount, &quot;Insufficient balance&quot;);<br>    balances[msg.sender] -= _amount;<br>    payable(msg.sender).transfer(_amount);<br>}</pre><ul><li><strong>Leverage Reentrancy Guards:</strong> Use OpenZeppelin’s ReentrancyGuard modifier.</li></ul><pre>import &quot;@openzeppelin/contracts/security/ReentrancyGuard.sol&quot;;<br>contract Secure is ReentrancyGuard {<br>    function withdraw(uint _amount) public nonReentrant {<br>        // Secure implementation<br>    }<br>}</pre><h3>2. Integer Overflow/Underflow</h3><p>Before Solidity 0.8.0, integers could overflow or underflow silently, leading to potential exploits.</p><h4>Example of a Vulnerable Contract:</h4><pre>pragma solidity ^0.7.0;<br>contract Overflow {<br>    uint8 public value = 255;<br>    function increment() public {<br>        value += 1; // Overflows to 0<br>    }<br>}</pre><h4>Mitigation:</h4><ul><li><strong>Use Solidity 0.8.0 or later:</strong> Built-in overflow/underflow protection is enabled by default.</li><li><strong>Explicitly use SafeMath:</strong> In older versions, leverage OpenZeppelin’s SafeMath library.</li></ul><pre>import &quot;@openzeppelin/contracts/utils/math/SafeMath.sol&quot;;<br>contract Safe {<br>    using SafeMath for uint8;<br>    uint8 public value = 255;<br>    function increment() public {<br>        value = value.add(1);<br>    }<br>}</pre><h3>3. Frontrunning</h3><p>Frontrunning involves exploiting the public nature of the blockchain by submitting a transaction with a higher gas fee to get it executed before another.</p><h4>Example of a Vulnerable Function:</h4><pre>pragma solidity ^0.8.0;<br>contract Auction {<br>    uint public highestBid;<br>    function bid() public payable {<br>        require(msg.value &gt; highestBid, &quot;Bid not high enough&quot;);<br>        highestBid = msg.value;<br>    }<br>}</pre><h4>Mitigation:</h4><ul><li><strong>Commit-Reveal Scheme:</strong> Use a two-step process where bidders commit their bids using a hash, then reveal them later.</li></ul><pre>pragma solidity ^0.8.0;<br>contract SecureAuction {<br>    struct Bid {<br>        bytes32 blindedBid;<br>        uint deposit;<br>    }<br>    mapping(address =&gt; Bid) public bids;<br>    function commitBid(bytes32 _blindedBid) public payable {<br>        bids[msg.sender] = Bid({<br>            blindedBid: _blindedBid,<br>            deposit: msg.value<br>        });<br>    }<br>    function revealBid(uint _value, bytes32 _salt) public {<br>        require(keccak256(abi.encodePacked(_value, _salt)) == bids[msg.sender].blindedBid, &quot;Invalid bid&quot;);<br>    }<br>}</pre><h3>Compiling, Deploying, and Testing Solidity Code</h3><h3>Compilation</h3><p>Use the Solidity compiler (solc) or tools like Remix IDE to compile your code:</p><pre>solc --bin --abi ContractName.sol -o output/</pre><h3>Deployment</h3><p>Leverage tools like Hardhat or Truffle for deployment. Example with Hardhat:</p><pre>const hre = require(&quot;hardhat&quot;);<br>async function main() {<br>    const Contract = await hre.ethers.getContractFactory(&quot;SecureAuction&quot;);<br>    const contract = await Contract.deploy();<br>    console.log(&quot;Contract deployed to:&quot;, contract.address);<br>}<br>main().catch((error) =&gt; {<br>    console.error(error);<br>    process.exitCode = 1;<br>});</pre><h3>Testing</h3><p>Write tests using frameworks like Hardhat or Truffle with Mocha/Chai:</p><pre>const { expect } = require(&quot;chai&quot;);<br>describe(&quot;SecureAuction&quot;, function () {<br>    it(&quot;Should store blinded bids correctly&quot;, async function () {<br>        const SecureAuction = await ethers.getContractFactory(&quot;SecureAuction&quot;);<br>        const auction = await SecureAuction.deploy();<br>        await auction.commitBid(ethers.utils.keccak256(&quot;0x1234&quot;), { value: 100 });<br>        const bid = await auction.bids(owner.address);<br>        expect(bid.blindedBid).to.equal(ethers.utils.keccak256(&quot;0x1234&quot;));<br>    });<br>});</pre><h3>Conclusion</h3><p>Security is a continuous process, especially in the decentralized world of blockchain. By understanding and mitigating vulnerabilities such as reentrancy, overflow/underflow, and frontrunning, you can build robust and reliable smart contracts. Always test thoroughly and stay updated with best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a5c997bfc58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns in Solidity: Practical Examples and Applications (Article 5 of 16 in the Solidity…]]></title>
            <link>https://medium.com/@pedrolisboa_10855/design-patterns-in-solidity-practical-examples-and-applications-article-5-of-16-in-the-solidity-a3188da2f828?source=rss-190cca8c97c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3188da2f828</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Pedro Torres]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 17:56:11 GMT</pubDate>
            <atom:updated>2025-01-02T17:56:11.152Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns in Solidity: Practical Examples and Applications (Article 5 of 16 in the Solidity Series)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*-_GbH9kygZhjU4MPT867Ew.png" /></figure><p>Smart contract development often benefits from structured design patterns to enhance modularity, reusability, and security. This article explores three critical design patterns in Solidity: Factory, Proxy, and Singleton. Through practical examples, we will examine how these patterns can be implemented, compiled, executed, and tested effectively.</p><h3>Factory Pattern</h3><p>The Factory Pattern is used to create multiple instances of similar contracts dynamically. This is particularly useful when deploying multiple contracts with a shared structure but varying initial parameters.</p><h3>Implementation</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract Product {<br>    string public name;<br>    constructor(string memory _name) {<br>        name = _name;<br>    }<br>}<br>contract Factory {<br>    Product[] public products;<br>    function createProduct(string memory _name) public {<br>        Product newProduct = new Product(_name);<br>        products.push(newProduct);<br>    }<br>    function getProducts() public view returns (Product[] memory) {<br>        return products;<br>    }<br>}</pre><h3>Compiling, Executing, and Testing</h3><ol><li><strong>Compile</strong>: Use the Solidity compiler (solc) or tools like Remix IDE.</li><li><strong>Deploy Factory Contract</strong>: Deploy the Factory contract on a test blockchain such as Ganache or a testnet like Ropsten.</li><li><strong>Test</strong>:</li></ol><ul><li>Call createProduct with different names.</li><li>Verify that getProducts returns all deployed Product contracts.</li></ul><h3>Proxy Pattern</h3><p>The Proxy Pattern enables upgrading smart contracts without changing their address, maintaining state consistency across upgrades.</p><h3>Implementation</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract Proxy {<br>    address public implementation;<br>    constructor(address _implementation) {<br>        implementation = _implementation;<br>    }<br>    function updateImplementation(address _newImplementation) public {<br>        implementation = _newImplementation;<br>    }<br>    fallback() external payable {<br>        address impl = implementation;<br>        require(impl != address(0), &quot;Implementation address is not set&quot;);<br>        assembly {<br>            let ptr := mload(0x40)<br>            calldatacopy(ptr, 0, calldatasize())<br>            let result := delegatecall(gas(), impl, ptr, calldatasize(), 0, 0)<br>            returndatacopy(ptr, 0, returndatasize())<br>            switch result<br>            case 0 { revert(ptr, returndatasize()) }<br>            default { return(ptr, returndatasize()) }<br>        }<br>    }<br>}</pre><h3>Compiling, Executing, and Testing</h3><ol><li><strong>Compile</strong>: Use Remix or Hardhat to compile the Proxy contract.</li><li><strong>Deploy Implementation Contract</strong>: Deploy an initial implementation contract.</li><li><strong>Deploy Proxy Contract</strong>: Use the implementation contract’s address in the constructor.</li><li><strong>Upgrade</strong>:</li></ol><ul><li>Deploy a new implementation.</li><li>Call updateImplementation with the new contract’s address.</li></ul><p>5. <strong>Test</strong>:</p><ul><li>Verify that calls to the proxy reflect the updated implementation’s logic.</li></ul><h3>Singleton Pattern</h3><p>The Singleton Pattern ensures that only one instance of a contract exists, preventing accidental redeployments and state conflicts.</p><h3>Implementation</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br>contract Singleton {<br>    address private owner;<br>    bool private initialized;<br>    constructor() {<br>        require(!initialized, &quot;Contract instance already exists&quot;);<br>        owner = msg.sender;<br>        initialized = true;<br>    }<br>}</pre><h3>Compiling, Executing, and Testing</h3><ol><li><strong>Compile</strong>: Use solc or Hardhat.</li><li><strong>Deploy Singleton Contract</strong>: Deploy the contract normally.</li><li><strong>Test</strong>:</li></ol><ul><li>Attempt redeployment.</li><li>Ensure redeployment fails as expected.</li></ul><h3>Conclusion</h3><p>Design patterns such as Factory, Proxy, and Singleton are invaluable tools for Solidity developers. They enhance modularity, enable contract upgrades, and enforce critical constraints. By mastering these patterns, you’ll improve both the quality and maintainability of your smart contracts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3188da2f828" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Gas in Solidity Smart Contracts: Strategies for Reducing Execution Costs (Article 4 of…]]></title>
            <link>https://medium.com/@pedrolisboa_10855/optimizing-gas-in-solidity-smart-contracts-strategies-for-reducing-execution-costs-article-4-of-24b7ab6fed7d?source=rss-190cca8c97c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/24b7ab6fed7d</guid>
            <category><![CDATA[gas-optimization]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Pedro Torres]]></dc:creator>
            <pubDate>Wed, 25 Dec 2024 23:39:51 GMT</pubDate>
            <atom:updated>2024-12-25T23:39:51.205Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizing Gas in Solidity Smart Contracts: Strategies for Reducing Execution Costs (Article 4 of 16 in the Solidity Series)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*LgQqDdpdmPWwDjg8t90tpQ.png" /></figure><p>In Solidity, optimizing gas consumption is crucial for reducing transaction costs on the blockchain. Efficient code design directly impacts execution costs, making it essential for developers to adopt strategies that minimize gas usage. This article explores practical techniques to optimize gas consumption in Solidity, complete with examples and guidance on compiling, executing, and testing smart contracts.</p><h3>1. Understanding Gas Optimization</h3><p>Gas in Ethereum represents computational effort required to execute operations on the blockchain. Each opcode in the Ethereum Virtual Machine (EVM) has a specific gas cost, and optimizing smart contracts involves reducing the number and complexity of these operations.</p><h3>2. Strategies for Optimizing Gas</h3><h4>a. Use Fixed-Size Data Types</h4><p>Avoid using dynamic arrays or types like string unless necessary. Fixed-size data types consume less gas.</p><pre>// Less Efficient<br>string public name;<br><br>// More Efficient<br>bytes32 public name;</pre><h4>b. Avoid Storage When Possible</h4><p>Storage operations are significantly more expensive than memory operations. Minimize writing to storage.</p><pre>// Less Efficient<br>uint256 public value;<br><br>function updateValue(uint256 newValue) public {<br>    value = newValue; // Expensive<br>}<br>// More Efficient<br>function updateValue(uint256 newValue) public {<br>    uint256 temp = newValue; // Cheaper<br>}</pre><h4>c. Batch Operations</h4><p>Perform multiple state updates in a single transaction when possible to save gas.</p><pre>// Example: Batch transferring tokens<br>function batchTransfer(address[] memory recipients, uint256 amount) public {<br>    for (uint256 i = 0; i &lt; recipients.length; i++) {<br>        transfer(recipients[i], amount);<br>    }<br>}</pre><h4>d. Use External Functions Over Public Functions</h4><p>External functions save gas by passing calldata directly instead of copying it to memory.</p><pre>// Less Efficient<br>function process(uint256[] memory data) public {<br>    // Code<br>}<br><br>// More Efficient<br>function process(uint256[] calldata data) external {<br>    // Code<br>}</pre><h4>e. Optimize Loops</h4><p>Avoid unbounded loops and large iterations; instead, structure data to minimize looping.</p><h3>3. Compiling, Deploying, and Testing the Contract</h3><h4>a. Compiling the Contract</h4><p>Use the Solidity compiler (solc) to compile the contract. Ensure you set the optimizer flag for better performance:</p><pre>solc --optimize --bin --abi ContractName.sol -o ./build</pre><h4>b. Deploying the Contract</h4><p>Deploy the compiled contract using a tool like ethers.js or web3.js:</p><pre>const ethers = require(&quot;ethers&quot;);<br>const contractABI = [/* ABI array */];<br>const bytecode = &quot;0x...&quot;; // Bytecode from compilation<br><br>async function deployContract() {<br>    const provider = new ethers.providers.JsonRpcProvider(&quot;http://localhost:8545&quot;);<br>    const wallet = new ethers.Wallet(&quot;PRIVATE_KEY&quot;, provider);<br>    const factory = new ethers.ContractFactory(contractABI, bytecode, wallet);<br>    const contract = await factory.deploy();<br>    console.log(&quot;Contract deployed at:&quot;, contract.address);<br>}<br>deployContract();</pre><h4>c. Testing the Contract</h4><p>Use a testing framework like Hardhat or Truffle to write unit tests:</p><pre>const { expect } = require(&quot;chai&quot;);<br><br>describe(&quot;Gas Optimized Contract&quot;, function () {<br>    it(&quot;Should perform operations efficiently&quot;, async function () {<br>        const contract = await Contract.deploy();<br>        await contract.deployed();<br>        const tx = await contract.someFunction();<br>        const receipt = await tx.wait();<br>        console.log(&quot;Gas Used:&quot;, receipt.gasUsed.toString());<br>    });<br>});</pre><h3>Conclusion</h3><p>By implementing the strategies outlined above, you can reduce the gas costs of your Solidity smart contracts, resulting in more efficient and cost-effective blockchain applications. Always remember to measure and test your contract’s gas usage regularly, especially after updates or optimizations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24b7ab6fed7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Contract Architecture: Best Practices for Beginners (Article 3 of 16 in the Solidity Series)]]></title>
            <link>https://medium.com/@pedrolisboa_10855/smart-contract-architecture-best-practices-for-beginners-article-3-of-16-in-the-solidity-series-85c8577888b9?source=rss-190cca8c97c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/85c8577888b9</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Pedro Torres]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 14:17:57 GMT</pubDate>
            <atom:updated>2024-12-22T14:17:57.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*8inaVvdBHbFp7AZ4YVgXcA.png" /></figure><p>Designing efficient and secure smart contracts requires an understanding of fundamental principles such as modularity, security, and organization. This article, the third in our 16-part Solidity series, explores best practices for structuring and managing smart contracts. Through practical examples, we’ll demonstrate how to write modular code, implement security measures, and organize contracts effectively, covering steps to compile, execute, and test the code.</p><h4>Modular Smart Contract Design</h4><p>Modular design involves breaking your contract into smaller, reusable components, each handling specific responsibilities. Benefits include easier debugging, scalability, and reduced risk of vulnerabilities.</p><p><strong>Example: Modular Contract for Token Management</strong></p><pre>// Token.sol <br>pragma solidity ^0.8.0;<br><br>contract Token {<br>    mapping(address =&gt; uint256) public balances;<br>    function transfer(address recipient, uint256 amount) external {<br>        require(balances[msg.sender] &gt;= amount, &quot;Insufficient balance&quot;);<br>        balances[msg.sender] -= amount;<br>        balances[recipient] += amount;<br>    }<br>}<br>// TokenMintable.sol<br>pragma solidity ^0.8.0;<br>import &quot;./Token.sol&quot;;<br>contract TokenMintable is Token {<br>    address public owner;<br>    constructor() {<br>        owner = msg.sender;<br>    }<br>    function mint(address to, uint256 amount) external {<br>        require(msg.sender == owner, &quot;Only owner can mint&quot;);<br>        balances[to] += amount;<br>    }<br>}</pre><p><strong>Explanation</strong>:<br>The Token contract handles basic token operations, while TokenMintable extends it to include minting capabilities. This approach separates concerns, making it easier to manage and extend functionality.</p><h4>Security Best Practices</h4><p>Smart contracts are immutable, so bugs or vulnerabilities can lead to permanent losses. Prioritize the following:</p><ol><li><strong>Access Control</strong><br>Use require statements to restrict sensitive functions.</li><li><strong>Avoid Overflows and Underflows</strong><br>Utilize Solidity’s built-in SafeMath or arithmetic operators in Solidity 0.8.x.</li><li><strong>Validate Inputs</strong><br>Ensure input validation to prevent malicious data entries.</li></ol><p><strong>Example: Secured Deposit Contract</strong></p><pre>pragma solidity ^0.8.0;<br><br>contract SecureDeposit {<br>    address public owner;<br>    mapping(address =&gt; uint256) public deposits;<br>    constructor() {<br>        owner = msg.sender;<br>    }<br>    function deposit() external payable {<br>        require(msg.value &gt; 0, &quot;Must send ETH&quot;);<br>        deposits[msg.sender] += msg.value;<br>    }<br>    function withdraw(uint256 amount) external {<br>        require(deposits[msg.sender] &gt;= amount, &quot;Insufficient balance&quot;);<br>        deposits[msg.sender] -= amount;<br>        payable(msg.sender).transfer(amount);<br>    }<br>    function emergencyWithdraw() external {<br>        require(msg.sender == owner, &quot;Unauthorized&quot;);<br>        payable(owner).transfer(address(this).balance);<br>    }<br>}</pre><h4>Organizing Your Contracts</h4><ol><li><strong>Directory Structure</strong><br>Organize contracts into folders based on functionality, e.g., contracts/tokens, contracts/access.</li><li><strong>Use Libraries</strong><br>Libraries store reusable code that multiple contracts can share.</li></ol><p><strong>Example: Using Libraries for Math Operations</strong></p><pre>pragma solidity ^0.8.0;<br><br>library MathLib {<br>    function add(uint256 a, uint256 b) internal pure returns (uint256) {<br>        return a + b;<br>    }<br>}<br>contract Calculator {<br>    using MathLib for uint256;<br>    function addNumbers(uint256 a, uint256 b) external pure returns (uint256) {<br>        return a.add(b);<br>    }<br>}</pre><h4>Compiling, Executing, and Testing</h4><ol><li><strong>Compiling</strong><br>Use the Solidity compiler (solc) or integrated environments like Remix or Hardhat. Example with solc:</li></ol><pre>solc --optimize --bin --abi Token.sol -o build/</pre><p>2.<strong> Executing</strong><br>Deploy contracts using Remix or frameworks like Hardhat:</p><pre>npx hardhat run scripts/deploy.js</pre><p>3. <strong>Testing</strong><br>Use tools like Mocha and Chai with Hardhat for testing. Example test:</p><pre>const { expect } = require(&quot;chai&quot;);<br><br>describe(&quot;Token Contract&quot;, function () {<br>    it(&quot;Should transfer tokens successfully&quot;, async function () {<br>        const [owner, addr1] = await ethers.getSigners();<br>        const Token = await ethers.getContractFactory(&quot;Token&quot;);<br>        const token = await Token.deploy();<br>        await token.deployed();<br><br>        await token.transfer(addr1.address, 100);<br>        expect(await token.balances(addr1.address)).to.equal(100);<br>    });<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85c8577888b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Solidity — Creating Your First Smart Contract (Article 2 of 16: Blockchain…]]></title>
            <link>https://medium.com/@pedrolisboa_10855/getting-started-with-solidity-creating-your-first-smart-contract-article-2-of-16-blockchain-f9bd92469605?source=rss-190cca8c97c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9bd92469605</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Pedro Torres]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 18:25:13 GMT</pubDate>
            <atom:updated>2024-12-20T18:25:13.511Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started with Solidity — Creating Your First Smart Contract (Article 2 of 16: Blockchain Development Series)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*kcREywrkuROIyEefC94Qrw.png" /></figure><p>This is the second article in a series of 16 about Solidity, focusing on practical steps to create, compile, and deploy a basic smart contract on the blockchain. By the end of this guide, you’ll have a fully functional contract and understand how to test it effectively.</p><h3>Setting Up Your Development Environment</h3><ol><li><strong>Install Node.js and npm</strong><br>Solidity development tools like Hardhat rely on Node.js. Download and install <a href="https://nodejs.org/">Node.js</a>.</li><li><strong>Install Hardhat</strong><br>Hardhat is a powerful Ethereum development framework. Install it with:</li></ol><pre>npm install --save-dev hardhat</pre><p>Initialize a project:</p><pre>npx hardhat</pre><p>Choose “Create a basic sample project” and follow the prompts.</p><p>3. <strong>Install additional dependencies</strong>:</p><pre>npm install --save-dev @nomiclabs/hardhat-ethers ethers</pre><h3>Creating Your First Smart Contract</h3><h4>Contract Code</h4><p>Here’s a simple HelloWorld contract that stores and retrieves a message.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract HelloWorld {<br>    string private message;<br><br>    // Event for tracking message changes<br>    event MessageUpdated(string oldMessage, string newMessage);<br><br>    // Constructor to initialize the message<br>    constructor(string memory initialMessage) {<br>        message = initialMessage;<br>    }<br><br>    // Function to set a new message<br>    function setMessage(string memory newMessage) public {<br>        string memory oldMessage = message;<br>        message = newMessage;<br>        emit MessageUpdated(oldMessage, newMessage);<br>    }<br><br>    // Function to get the current message<br>    function getMessage() public view returns (string memory) {<br>        return message;<br>    }<br>}</pre><h3>Compiling the Contract</h3><ol><li><strong>Set the Solidity Compiler Version</strong><br>Open the hardhat.config.js file and specify the compiler version:</li></ol><pre>module.exports = {<br>    solidity: &quot;0.8.0&quot;,<br>};</pre><p><strong>2. Compile the Contract</strong><br>Run the following command:</p><pre>npx hardhat compile</pre><p>This generates artifacts in the artifacts folder, including the ABI and bytecode.</p><h3>Deploying the Contract on a Local Blockchain</h3><ol><li><strong>Create a Deployment Script</strong><br>Inside the scripts/ directory, create deploy.js:</li></ol><pre>async function main() {<br>    const [deployer] = await ethers.getSigners();<br>    console.log(&quot;Deploying contracts with the account:&quot;, deployer.address);<br><br>    const HelloWorld = await ethers.getContractFactory(&quot;HelloWorld&quot;);<br>    const helloWorld = await HelloWorld.deploy(&quot;Hello, Blockchain!&quot;);<br><br>    console.log(&quot;HelloWorld deployed to:&quot;, helloWorld.address);<br>}<br><br>main()<br>    .then(() =&gt; process.exit(0))<br>    .catch((error) =&gt; {<br>        console.error(error);<br>        process.exit(1);<br>    });</pre><p>2. <strong>Run the Deployment Script</strong><br>Use Hardhat’s local blockchain:</p><pre>npx hardhat node</pre><p>Deploy the contract:</p><pre>npx hardhat run scripts/deploy.js --network localhost</pre><h3>Testing the Smart Contract</h3><ol><li><strong>Write Tests</strong><br>Create a file test/HelloWorld.js:</li></ol><pre>const { expect } = require(&quot;chai&quot;);<br><br>describe(&quot;HelloWorld&quot;, function () {<br>    it(&quot;Should return the initial message&quot;, async function () {<br>        const HelloWorld = await ethers.getContractFactory(&quot;HelloWorld&quot;);<br>        const helloWorld = await HelloWorld.deploy(&quot;Hello, Test!&quot;);<br>        await helloWorld.deployed();<br><br>        expect(await helloWorld.getMessage()).to.equal(&quot;Hello, Test!&quot;);<br>    });<br><br>    it(&quot;Should update the message&quot;, async function () {<br>        const HelloWorld = await ethers.getContractFactory(&quot;HelloWorld&quot;);<br>        const helloWorld = await HelloWorld.deploy(&quot;Hello, Test!&quot;);<br>        await helloWorld.deployed();<br><br>        await helloWorld.setMessage(&quot;Updated Message&quot;);<br>        expect(await helloWorld.getMessage()).to.equal(&quot;Updated Message&quot;);<br>    });<br>});</pre><p>2. <strong>Run the Tests</strong><br>Execute:</p><pre>npx hardhat test</pre><p>The output will confirm that all tests pass successfully.</p><h3>Interacting with the Blockchain Using Hardhat Console</h3><p>Use the interactive Hardhat console for direct interaction with your contract:</p><pre>npx hardhat console --network localhost</pre><p>Sample commands:</p><pre>const HelloWorld = await ethers.getContractFactory(&quot;HelloWorld&quot;);<br>const helloWorld = await HelloWorld.deploy(&quot;Hello, Interactive!&quot;);<br>await helloWorld.deployed();<br><br>await helloWorld.getMessage(); // &quot;Hello, Interactive!&quot;<br>await helloWorld.setMessage(&quot;New Message&quot;);<br>await helloWorld.getMessage(); // &quot;New Message&quot;</pre><h3>Conclusion</h3><p>In this article, we covered the essentials for creating, compiling, deploying, and testing a basic Solidity smart contract. The HelloWorld contract is a starting point, offering a practical foundation for more complex applications. Stay tuned for the next article in this series, where we’ll explore more advanced features and best practices for Solidity development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9bd92469605" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Solidity and Why Learn It? (Article 1 of 16: Blockchain Development Series)]]></title>
            <link>https://medium.com/@pedrolisboa_10855/what-is-solidity-and-why-learn-it-article-1-of-16-blockchain-development-series-77f6205f4df9?source=rss-190cca8c97c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/77f6205f4df9</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[decentralizedapplication]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Pedro Torres]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 12:16:34 GMT</pubDate>
            <atom:updated>2024-12-19T12:16:34.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*OUN3ooE4cNso2Skh" /></figure><p>As blockchain technology continues to evolve, the demand for smart contracts has skyrocketed, with <strong>Solidity</strong> emerging as a leading programming language in this domain. Designed specifically for creating smart contracts on platforms like Ethereum, Solidity plays a pivotal role in decentralized application (dApp) development. This article explores what Solidity is, its applications, and how to get started with it, while also highlighting why understanding foundational concepts like white papers is crucial for developers.</p><h3>What is Solidity?</h3><p>Solidity is a high-level, object-oriented programming language tailored for writing smart contracts that execute on blockchain virtual machines, such as the Ethereum Virtual Machine (EVM). It draws inspiration from languages like JavaScript, Python, and C++, making it relatively accessible for developers already familiar with modern programming paradigms.</p><h3>The Role of White Papers in Blockchain and Solidity</h3><p>To fully grasp Solidity’s purpose, it’s essential to understand the foundation of Ethereum, as described in its <strong>white paper</strong>, authored by Vitalik Buterin in 2013. A <strong>white paper</strong> is a technical document that defines a blockchain project’s goals, architecture, and use cases. Ethereum’s white paper introduced the revolutionary concept of a programmable blockchain capable of executing smart contracts and running decentralized applications.</p><p>Key concepts from the Ethereum White Paper that influenced Solidity:</p><ul><li>The <strong>Ethereum Virtual Machine (EVM)</strong>, which serves as the runtime environment for smart contracts.</li><li>The need for a <strong>Turing-complete programming language</strong> to enable flexible and secure contract execution.</li><li>A commitment to <strong>decentralization</strong>, <strong>transparency</strong>, and <strong>security</strong> in application development.</li></ul><p>Understanding these principles helps developers appreciate Solidity’s design and its role in the broader blockchain ecosystem. For deeper insights, you can explore the Ethereum White Paper.</p><h3>Why Learn Solidity?</h3><p>Solidity is at the heart of Ethereum’s capabilities, making it a critical skill for anyone interested in blockchain development. Here’s why it’s worth learning:</p><ol><li><strong>Broad Adoption</strong>: As Ethereum is the leading smart contract platform, Solidity’s relevance extends across countless projects.</li><li><strong>Diverse Applications</strong>: From creating fungible and non-fungible tokens to complex DeFi protocols, Solidity underpins blockchain innovation.</li><li><strong>Career Opportunities</strong>: With the rising demand for decentralized solutions, Solidity developers are highly sought after.</li><li><strong>Rich Ecosystem</strong>: Tools like Remix IDE, Truffle, and Hardhat simplify the development process.</li></ol><h3>Applications of Solidity</h3><ul><li><strong>Token Creation</strong>: Build ERC-20 (fungible) and ERC-721 (non-fungible) tokens.</li><li><strong>DeFi Protocols</strong>: Develop decentralized exchanges, lending platforms, and yield farming systems.</li><li><strong>Blockchain Games</strong>: Power in-game assets and economies with blockchain technology.</li><li><strong>Governance Systems</strong>: Enable decentralized organizations to execute transparent decision-making.</li></ul><h3>Writing and Testing Smart Contracts</h3><h4>Example: Simple Token (ERC-20)</h4><p>Below is a basic Solidity contract for an ERC-20 token:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>import &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract MyToken is ERC20 {<br>    constructor(uint256 initialSupply) ERC20(&quot;MyToken&quot;, &quot;MTK&quot;) {<br>        _mint(msg.sender, initialSupply);<br>    }<br>}</pre><p>This contract creates a token named “MyToken” with the symbol “MTK.” When deployed, it allows the creator to specify the initial token supply.</p><h3>Tools for Development and Testing</h3><h4>Recommended IDE: Remix IDE</h4><p><strong>Remix IDE</strong> is a web-based environment for writing, testing, and deploying Solidity contracts.</p><p><strong>Steps to Use Remix:</strong></p><ol><li>Open Remix in your browser.</li><li>Create a new .sol file (e.g., MyToken.sol).</li><li>Write or paste your contract code.</li><li>Compile the contract using the built-in compiler.</li><li>Deploy the contract to a test environment or Ethereum network.</li></ol><h4>Advanced Tools:</h4><ul><li><strong>Hardhat</strong>: A framework for testing, debugging, and deploying smart contracts.</li><li><strong>Truffle</strong>: Comprehensive tooling for dApp development.</li></ul><h3>Testing Smart Contracts</h3><p>Testing ensures contracts function as expected. Using <strong>Hardhat</strong>, you can create automated tests like this:</p><pre>const { expect } = require(&quot;chai&quot;);<br><br>describe(&quot;MyToken&quot;, function () {<br>    it(&quot;Should initialize with the correct supply&quot;, async function () {<br>        const [owner] = await ethers.getSigners();<br>        const MyToken = await ethers.getContractFactory(&quot;MyToken&quot;);<br>        const token = await MyToken.deploy(1000);<br>        await token.deployed();<br><br>        expect(await token.totalSupply()).to.equal(1000);<br>        expect(await token.balanceOf(owner.address)).to.equal(1000);<br>    });<br>});</pre><h3>Getting Started: Compiling, Deploying, and Testing</h3><p>To begin working with Solidity:</p><ol><li><strong>Write the Code</strong>: Use Remix or your preferred IDE.</li><li><strong>Compile the Contract</strong>: Ensure there are no syntax errors and that the bytecode is ready for deployment.</li><li><strong>Deploy</strong>: Choose a testnet like Goerli or Rinkeby for experimenting.</li><li><strong>Test</strong>: Use automated tools like Hardhat or Truffle to validate functionality.</li></ol><h3>Conclusion</h3><p>Solidity is the cornerstone of smart contract development, enabling developers to build decentralized applications that redefine industries. By understanding the theoretical foundations through documents like the Ethereum White Paper and leveraging practical tools like Remix and Hardhat, developers can confidently contribute to the blockchain ecosystem.</p><p>Whether you’re looking to create tokens, build DeFi platforms, or explore the future of governance systems, learning Solidity is a step toward becoming a key player in the decentralized future. Why not start today?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77f6205f4df9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuration and Secrets Management with .NET and Azure Key Vault]]></title>
            <link>https://medium.com/@pedrolisboa_10855/configuration-and-secrets-management-with-net-and-azure-key-vault-715b6af43640?source=rss-190cca8c97c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/715b6af43640</guid>
            <category><![CDATA[secure-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[azure-keyvault]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[cloud-security]]></category>
            <dc:creator><![CDATA[Pedro Torres]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 11:39:19 GMT</pubDate>
            <atom:updated>2024-11-27T11:39:19.105Z</atom:updated>
            <content:encoded><![CDATA[<h3>Configuration and Secrets Management with .NET and Azure Key Vault</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*UWay0dlEAJdpDacs" /></figure><p>Managing configurations and secrets effectively is critical to ensuring security, scalability, and maintainability in modern applications. In this article, we’ll explore how to manage configurations and secrets using <strong>.NET</strong> and <strong>Azure Key Vault</strong>, Microsoft’s robust solution for securely storing and accessing secrets, keys, and certificates. We’ll discuss best practices and provide practical examples in <strong>C#</strong>.</p><h3>Why Use Azure Key Vault?</h3><p><strong>Azure Key Vault</strong> is a managed service designed to safeguard sensitive information such as:</p><ul><li><strong>Encryption keys</strong> to secure data.</li><li><strong>Certificates</strong> for authentication.</li><li><strong>Secrets</strong> like connection strings, API tokens, and other credentials.</li></ul><p>Key benefits of Azure Key Vault include:</p><ol><li><strong>Centralization and security</strong>: Store all secrets in a single, secure location.</li><li><strong>Simplified management</strong>: Use <strong>Azure Active Directory (AAD)</strong> for access control.</li><li><strong>Automation</strong>: Automatically rotate secrets and certificates.</li></ol><h3>Setting Up Azure Key Vault</h3><p>Before integrating Azure Key Vault into your application, follow these steps:</p><p><strong>Create a Key Vault</strong>:</p><ul><li>In the Azure portal, click <em>“Create a resource”</em> &gt; <em>“Key Vault”</em>.</li><li>Configure the name, resource group, and location.</li></ul><p><strong>Add secrets</strong>:</p><ul><li>Navigate to your Key Vault.</li><li>Click <em>“Secrets”</em> &gt; <em>“New secret”</em>.</li><li>Provide a name (e.g., DatabaseConnectionString) and value.</li></ul><p><strong>Set up permissions</strong>:</p><ul><li>Use <strong>Managed Identities</strong> to allow your application to access secrets without manually managing credentials.</li></ul><h3>Integration with .NET</h3><p>To access Azure Key Vault in a .NET application, follow these steps:</p><h4>1. Add Required NuGet Packages</h4><p>Install the following packages in your project:</p><pre>dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets<br>dotnet add package Azure.Identity</pre><h4>2. Configure Access to Key Vault</h4><p>Set up Key Vault in your Program.cs or Startup.cs file:</p><pre>using Azure.Identity;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// Add Azure Key Vault to configuration<br>builder.Configuration.AddAzureKeyVault(<br>    new Uri(&quot;https://&lt;YOUR-KEY-VAULT&gt;.vault.azure.net/&quot;),<br>    new DefaultAzureCredential()<br>);<br><br>var app = builder.Build();<br><br>app.MapGet(&quot;/&quot;, (IConfiguration config) =&gt;<br>{<br>    var secret = config[&quot;DatabaseConnectionString&quot;];<br>    return Results.Text($&quot;Retrieved secret: {secret}&quot;);<br>});<br><br>app.Run();</pre><p><strong>Key Details</strong>:</p><ul><li>Replace &lt;YOUR-KEY-VAULT&gt; with your Key Vault’s name.</li><li>The DefaultAzureCredential class handles credentials automatically based on the runtime environment (local, pipeline, or Azure).</li></ul><h4>3. Use Secrets in Your Application</h4><p>Once configured, secrets from Key Vault can be accessed directly via IConfiguration:</p><pre>string connectionString = configuration[&quot;DatabaseConnectionString&quot;];</pre><h3>Enhancing Security</h3><ol><li><strong>Use Managed Identities</strong>: Managed Identities eliminate the need to store credentials for accessing Azure Key Vault.</li><li><strong>Restrict permissions</strong>: Apply the principle of least privilege. Grant only the necessary permissions in Azure Key Vault.</li><li><strong>Rotate secrets regularly</strong>: Set up alerts or automation to ensure secrets are rotated periodically.</li></ol><h3>Complete Example: Database Connection</h3><p>Below is an example of using Key Vault to retrieve a connection string and use it to access a database:</p><pre>using Azure.Identity;<br>using Microsoft.Data.SqlClient;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// Configure Azure Key Vault<br>builder.Configuration.AddAzureKeyVault(<br>    new Uri(&quot;https://&lt;YOUR-KEY-VAULT&gt;.vault.azure.net/&quot;),<br>    new DefaultAzureCredential()<br>);<br><br>var app = builder.Build();<br><br>app.MapGet(&quot;/db-check&quot;, async (IConfiguration config) =&gt;<br>{<br>    string connectionString = config[&quot;DatabaseConnectionString&quot;];<br>    <br>    try<br>    {<br>        using var connection = new SqlConnection(connectionString);<br>        await connection.OpenAsync();<br>        return Results.Text(&quot;Database connection successful!&quot;);<br>    }<br>    catch (Exception ex)<br>    {<br>        return Results.Text($&quot;Database connection failed: {ex.Message}&quot;);<br>    }<br>});<br><br>app.Run();</pre><p><strong>Explanation</strong>:</p><ul><li>The DatabaseConnectionString secret is retrieved from Azure Key Vault.</li><li>The connection string is used to open a connection to the database and verify its availability.</li></ul><h3>Best Practices and Considerations</h3><p><strong>Environment-specific secrets</strong>:</p><ul><li>Use separate Key Vaults for different environments (e.g., Development, Staging, Production).</li></ul><p><strong>Logging and monitoring</strong>:</p><ul><li>Use <strong>Azure Monitor</strong> and <strong>Application Insights</strong> to track Key Vault access and errors.</li></ul><p><strong>Cost management</strong>:</p><ul><li>Regularly review Key Vault usage to optimize costs.</li></ul><h3>Conclusion</h3><p>Integrating <strong>Azure Key Vault</strong> with your .NET application provides a secure and efficient way to manage configurations and secrets. By following best practices such as using Managed Identities, restricting permissions, and automating secret rotation, you can enhance the security and maintainability of your applications.</p><p>Azure Key Vault seamlessly integrates with .NET, making it an excellent choice for developers aiming to build secure and scalable solutions. Try it in your next project and experience its benefits firsthand!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=715b6af43640" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Reflection and Expression Trees in C#]]></title>
            <link>https://medium.com/@pedrolisboa_10855/how-to-use-reflection-and-expression-trees-in-c-a40364e9d953?source=rss-190cca8c97c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a40364e9d953</guid>
            <category><![CDATA[expression-tree]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[reflections]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pedro Torres]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 12:34:29 GMT</pubDate>
            <atom:updated>2024-11-19T12:34:29.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*5wDU6eI67Kz5qi4r" /></figure><p><strong>Reflection</strong> and <strong>Expression Trees</strong> are advanced features in C# that allow developers to create dynamic and flexible applications. In this article, we will explore their use cases, provide practical examples, and discuss best practices to avoid performance and security pitfalls.</p><h3>What is Reflection in C#?</h3><p>Reflection enables you to inspect and interact with metadata about types at runtime. It is especially useful for building dynamic applications that need to discover class structures, methods, properties, or even instantiate objects without prior knowledge at compile time.</p><h4>Example: Dynamically Accessing Class Properties</h4><pre>using System;<br>using System.Reflection;<br><br>public class Person<br>{<br>    public string Name { get; set; }<br>    public int Age { get; set; }<br>}<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        var person = new Person { Name = &quot;John&quot;, Age = 30 };<br><br>        // Get the type of the class<br>        Type type = person.GetType();<br><br>        // List properties<br>        foreach (PropertyInfo property in type.GetProperties())<br>        {<br>            Console.WriteLine($&quot;{property.Name}: {property.GetValue(person)}&quot;);<br>        }<br><br>        // Modify a property value<br>        PropertyInfo nameProperty = type.GetProperty(&quot;Name&quot;);<br>        nameProperty.SetValue(person, &quot;Jane&quot;);<br><br>        Console.WriteLine($&quot;Updated Name: {person.Name}&quot;);<br>    }<br>}</pre><p>This example demonstrates how to access and modify object properties using Reflection.</p><h4>When to Use Reflection?</h4><p>Reflection is particularly useful in scenarios such as:</p><ul><li><strong>Serialization and deserialization of objects</strong>.</li><li><strong>Dependency injection frameworks</strong>.</li><li><strong>Validation libraries</strong>.</li><li><strong>Dynamic testing</strong>.</li></ul><p>However, it is important to note that Reflection can be slower than traditional code due to runtime operations.</p><h3>What Are Expression Trees in C#?</h3><p>Expression Trees represent code as a data structure in the form of a tree. They are mainly used for dynamic query generation, LINQ manipulation, and metaprogramming.</p><h4>Example: Creating Dynamic Expressions</h4><p>The following example demonstrates how to dynamically create a function that adds two numbers.</p><pre>using System;<br>using System.Linq.Expressions;<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        // Parameters<br>        ParameterExpression param1 = Expression.Parameter(typeof(int), &quot;a&quot;);<br>        ParameterExpression param2 = Expression.Parameter(typeof(int), &quot;b&quot;);<br><br>        // Expression body: a + b<br>        BinaryExpression body = Expression.Add(param1, param2);<br><br>        // Lambda: (a, b) =&gt; a + b<br>        var addLambda = Expression.Lambda&lt;Func&lt;int, int, int&gt;&gt;(body, param1, param2);<br><br>        // Compile the expression into a usable function<br>        var addFunc = addLambda.Compile();<br><br>        // Use the function<br>        int result = addFunc(5, 10);<br>        Console.WriteLine($&quot;Sum result: {result}&quot;);<br>    }<br>}</pre><p>In this example:</p><ul><li>We create an expression tree representing (a, b) =&gt; a + b.</li><li>The expression is compiled into a delegate.</li><li>The compiled delegate is executed dynamically.</li></ul><h4>When to Use Expression Trees?</h4><p>Expression Trees are commonly used in:</p><ul><li><strong>Dynamic LINQ query construction</strong>.</li><li><strong>Business rule validation</strong>.</li><li><strong>Dynamic code compilation</strong>.</li></ul><p>They are more performant than Reflection in scenarios where operations are repeated multiple times since compiled expressions are optimized.</p><h3>Combining Reflection and Expression Trees</h3><p>A powerful approach is to combine Reflection and Expression Trees to create dynamic yet optimized code.</p><h4>Example: Dynamic Property Access with Expression Trees</h4><p>Imagine you need to dynamically access a property but want to avoid the overhead of pure Reflection. Here’s a solution:</p><pre>using System;<br>using System.Linq.Expressions;<br>using System.Reflection;<br><br>public class Product<br>{<br>    public string Name { get; set; }<br>    public decimal Price { get; set; }<br>}<br><br>class Program<br>{<br>    static void Main()<br>    {<br>        var product = new Product { Name = &quot;Chair&quot;, Price = 199.99m };<br><br>        // Generate a dynamic getter for the &quot;Name&quot; property<br>        var getter = CreateGetter&lt;Product, string&gt;(&quot;Name&quot;);<br>        Console.WriteLine($&quot;Product Name: {getter(product)}&quot;);<br><br>        // Generate a dynamic setter for the &quot;Price&quot; property<br>        var setter = CreateSetter&lt;Product, decimal&gt;(&quot;Price&quot;);<br>        setter(product, 249.99m);<br>        Console.WriteLine($&quot;Updated Price: {product.Price}&quot;);<br>    }<br><br>    static Func&lt;T, TProperty&gt; CreateGetter&lt;T, TProperty&gt;(string propertyName)<br>    {<br>        var param = Expression.Parameter(typeof(T), &quot;x&quot;);<br>        var property = Expression.Property(param, propertyName);<br>        var lambda = Expression.Lambda&lt;Func&lt;T, TProperty&gt;&gt;(property, param);<br>        return lambda.Compile();<br>    }<br><br>    static Action&lt;T, TProperty&gt; CreateSetter&lt;T, TProperty&gt;(string propertyName)<br>    {<br>        var objParam = Expression.Parameter(typeof(T), &quot;x&quot;);<br>        var valueParam = Expression.Parameter(typeof(TProperty), &quot;value&quot;);<br>        var property = Expression.Property(objParam, propertyName);<br>        var assign = Expression.Assign(property, valueParam);<br>        var lambda = Expression.Lambda&lt;Action&lt;T, TProperty&gt;&gt;(assign, objParam, valueParam);<br>        return lambda.Compile();<br>    }<br>}</pre><p>This example creates dynamic <strong>getters</strong> and <strong>setters</strong> using a combination of Reflection and compiled Expression Trees, balancing flexibility and efficiency.</p><h3>Best Practices</h3><ol><li><strong>Minimize Reflection in Loops:</strong> Whenever possible, use Expression Trees for repetitive tasks.</li><li><strong>Cache Compiled Expressions:</strong> Avoid recompiling frequently used expressions.</li><li><strong>Validate Inputs:</strong> Ensure that Reflection is used safely to avoid vulnerabilities.</li><li><strong>Leverage Existing Libraries:</strong> Tools like AutoMapper and LINQKit can simplify dynamic operations.</li></ol><h3>Conclusion</h3><p>Reflection and Expression Trees are powerful tools in C#. While they require careful handling to balance performance and security, they enable developers to build dynamic, adaptable solutions. By strategically combining their capabilities, you can unlock the full potential of your code to meet real-world demands.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a40364e9d953" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Application Development with SignalR and .NET]]></title>
            <link>https://medium.com/@pedrolisboa_10855/real-time-application-development-with-signalr-and-net-60a69e0e9130?source=rss-190cca8c97c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/60a69e0e9130</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[realtimeapps]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[signalr]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Pedro Torres]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 12:34:01 GMT</pubDate>
            <atom:updated>2024-11-12T12:34:01.818Z</atom:updated>
            <content:encoded><![CDATA[<h3>Real-Time Application Development with SignalR and .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*N7cEdGgMCYR_CKMk" /></figure><h3>Introduction</h3><p>Today’s applications often require real-time communication with users, whether it’s to send instant notifications, provide live chat, or update dashboards dynamically. <strong>SignalR</strong> is a .NET library that simplifies the development of real-time applications by supporting bidirectional communication between the server and client.</p><p>In this guide, we’ll explore SignalR, cover its primary use cases, and walk through a practical example in C# to create a real-time application.</p><h3>What is SignalR?</h3><p><strong>SignalR</strong> is a .NET library that facilitates real-time communication by enabling servers to push data to clients as soon as an update is available, without clients needing to request it. SignalR is built on WebSockets and, for fallback, uses other technologies like Server-Sent Events and Long Polling to ensure compatibility across different platforms.</p><h4>How it Works</h4><p>SignalR uses <strong>hubs</strong> to manage communication between the server and clients. A <strong>Hub</strong> is a class where you define methods that can be called by both clients and the server, simplifying complex interactions in real-time applications.</p><h3>Key Use Cases</h3><ul><li><strong>Real-Time Chat</strong>: Perfect for instant messaging in chat applications.</li><li><strong>Instant Notifications</strong>: Useful for applications that need to update users with real-time information, such as e-commerce or gaming.</li><li><strong>Dynamic Dashboards</strong>: For applications displaying constantly updated data, like system monitoring or business metrics dashboards.</li></ul><h3>Setting Up SignalR in .NET</h3><h4>Step 1: Create a Project</h4><ol><li>Open Visual Studio and create a new <strong>ASP.NET Core Web Application</strong>.</li><li>Select either <strong>API</strong> or <strong>Web Application</strong> as the project type.</li><li>In the .csproj file, ensure <strong>Microsoft.AspNetCore.SignalR</strong> is listed; if not, add it via NuGet.</li></ol><h4>Step 2: Configuring SignalR</h4><ol><li>In <strong>Startup.cs</strong>, add SignalR configuration in ConfigureServices:</li></ol><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddControllersWithViews();<br>    services.AddSignalR(); // Adds SignalR to the application’s services<br>}</pre><p>2. Then, add SignalR mapping in Configure:</p><pre>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br>    if (env.IsDevelopment())<br>    {<br>        app.UseDeveloperExceptionPage();<br>    }<br><br>    app.UseRouting();<br><br>    app.UseEndpoints(endpoints =&gt;<br>    {<br>        endpoints.MapControllers();<br>        endpoints.MapHub&lt;ChatHub&gt;(&quot;/chatHub&quot;); // Map the ChatHub to the &quot;/chatHub&quot; route<br>    });<br>}</pre><h4>Step 3: Creating the Hub</h4><p>Let’s create a <strong>Hub</strong> to manage chat functionality.</p><ol><li>In the project, add a folder named <strong>Hubs</strong>.</li><li>Inside <strong>Hubs</strong>, create a new class called <strong>ChatHub.cs</strong>:</li></ol><pre>using Microsoft.AspNetCore.SignalR;<br>using System.Threading.Tasks;<br><br>public class ChatHub : Hub<br>{<br>    public async Task SendMessage(string user, string message)<br>    {<br>        await Clients.All.SendAsync(&quot;ReceiveMessage&quot;, user, message);<br>    }<br>}</pre><p>Here, the SendMessage method allows the client to send a message to the server, which then relays it to all connected clients using Clients.All.SendAsync.</p><h3>Practical Example: Implementing the Client with JavaScript</h3><p>Now, let’s create a simple HTML and JavaScript interface to connect to the Hub and send/receive messages.</p><ol><li>In the project, add a file named <strong>index.html</strong> with the following content:</li></ol><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Real-Time Chat with SignalR&lt;/title&gt;<br>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.0/signalr.min.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h2&gt;Chat&lt;/h2&gt;<br>    &lt;input type=&quot;text&quot; id=&quot;userInput&quot; placeholder=&quot;Your name...&quot; /&gt;<br>    &lt;input type=&quot;text&quot; id=&quot;messageInput&quot; placeholder=&quot;Type a message...&quot; /&gt;<br>    &lt;button onclick=&quot;sendMessage()&quot;&gt;Send&lt;/button&gt;<br><br>    &lt;ul id=&quot;messagesList&quot;&gt;&lt;/ul&gt;<br><br>    &lt;script&gt;<br>        // Connect to the Hub<br>        const connection = new signalR.HubConnectionBuilder()<br>            .withUrl(&quot;/chatHub&quot;)<br>            .build();<br><br>        // Display received messages<br>        connection.on(&quot;ReceiveMessage&quot;, (user, message) =&gt; {<br>            const li = document.createElement(&quot;li&quot;);<br>            li.textContent = `${user}: ${message}`;<br>            document.getElementById(&quot;messagesList&quot;).appendChild(li);<br>        });<br><br>        connection.start().catch(err =&gt; console.error(err.toString()));<br><br>        // Send message to server<br>        function sendMessage() {<br>            const user = document.getElementById(&quot;userInput&quot;).value;<br>            const message = document.getElementById(&quot;messageInput&quot;).value;<br>            connection.invoke(&quot;SendMessage&quot;, user, message).catch(err =&gt; console.error(err.toString()));<br>        }<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>This code connects to the Hub and defines a function to send messages, as well as to display received messages in real-time.</p><h3>Additional Use Cases</h3><h4>Notifications</h4><p>For a notification system, you can create a method in the Hub, like SendNotification, and call the method to send specific notifications to all clients or to specific groups of clients.</p><pre>public async Task SendNotification(string notification)<br>{<br>    await Clients.All.SendAsync(&quot;ReceiveNotification&quot;, notification);<br>}</pre><h4>Dynamic Dashboard</h4><p>A dashboard that needs to display real-time data, like sales or system monitoring, can use similar methods. You can define methods that update clients with new data received.</p><pre>public async Task UpdateDashboardData(string data)<br>{<br>    await Clients.All.SendAsync(&quot;ReceiveDashboardData&quot;, data);<br>}</pre><h3>Conclusion</h3><p>SignalR simplifies building real-time applications, enabling rapid, dynamic interactions. This guide covered the essential steps for creating a chat application, and the same concept can be applied to other use cases like notifications and dashboards.</p><p>With SignalR, your system gains the ability to adapt quickly to changes, making it ideal for many modern scenarios.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60a69e0e9130" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>