<?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 Eman Herawy on Medium]]></title>
        <description><![CDATA[Stories by Eman Herawy on Medium]]></description>
        <link>https://medium.com/@emanherawy?source=rss-65e6393574a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*W6c44h6N1WbzqGRXtoOyIg.jpeg</url>
            <title>Stories by Eman Herawy on Medium</title>
            <link>https://medium.com/@emanherawy?source=rss-65e6393574a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 16 May 2026 05:20:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emanherawy/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[From Building Workflows to Breaking Them]]></title>
            <link>https://medium.com/@emanherawy/from-building-workflows-to-breaking-them-99b2e30e7456?source=rss-65e6393574a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/99b2e30e7456</guid>
            <category><![CDATA[ecr]]></category>
            <category><![CDATA[chain-link]]></category>
            <dc:creator><![CDATA[Eman Herawy]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 02:38:18 GMT</pubDate>
            <atom:updated>2026-01-02T02:51:59.129Z</atom:updated>
            <content:encoded><![CDATA[<p>Potential vulnerabilities both developers and auditors should look for</p><blockquote><strong>Disclaimer:</strong> <em>These are personal opinions based on my current understanding of CRE while learning it. They may evolve as I gain more experience.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*QmBaR0tl3zchTWt0kvZ8VQ.png" /></figure><h3>Why I’m Writing This</h3><p>I live in two worlds: as a developer obsessed with hackathons (they’re how I feed my curiosity and force myself to learn fast) and as a security auditor, which changes how I look at systems. It pushes me to think more about how things break and what it actually takes to build something secure.</p><p><a href="https://medium.com/@emanherawy/building-with-chainlink-cre-lessons-from-developing-a-decentralized-x402-payment-facilitator-abac7ab716a2">In my first article</a>, I approached Chainlink CRE with a builder’s mindset, focusing on what’s possible and how to ship. This article is different.</p><p>Here, I’m approaching CRE as a security auditor. I’ll walk through:</p><ul><li>Potential mistakes developers are likely to make</li><li>Why those mistakes matter</li><li>What both builders and auditors should look for when reviewing CRE workflows</li></ul><p><strong>If you’re building with CRE</strong>, think of this as your early warning system: the things I’d flag in an audit before they cost you money or credibility.</p><p><strong>If you’re auditing CRE projects</strong>, treat this as your checklist for the gap between “it compiles” and “it’s actually secure.”</p><h3>Understanding the Foundation</h3><p>Before diving into what breaks, it’s important to understand what makes CRE different.</p><h3>Consensus Computing</h3><p>Consensus computing means that a decentralized network of nodes must agree on the result of executing code before that result is accepted.</p><blockquote><strong>CRE does not run on one machine. It runs on many, simultaneously.</strong></blockquote><p>When your workflow calls an API or reads from a blockchain, multiple independent nodes execute the same operation. Each node produces its own result. Those results are compared, and if enough nodes agree (quorum), the result is accepted. If they do not, the workflow fails.</p><p>This provides:</p><ul><li><strong>Tamper resistance:</strong> no single node can manipulate results</li><li><strong>High availability:</strong> the system continues operating despite node failures</li><li><strong>Trust minimization:</strong> no single operator must be trusted</li><li><strong>Verifiability:</strong> results are cryptographically verified</li></ul><p>This process happens automatically for every capability call. You do not write consensus logic yourself. It is built into the CRE runtime.</p><blockquote><strong>There is a critical caveat: consensus only works if every node executes identical logic.</strong></blockquote><h3>Determinism</h3><p>Determinism means that given the same inputs, the code produces the exact same outputs. Every time. Everywhere.</p><p>Your workflow does not run once. It runs in parallel on multiple nodes. For consensus to succeed:</p><ul><li>every node must execute the same steps</li><li>in the same order</li><li>with the same inputs</li><li>and produce the same intermediate results</li></ul><p>If any step differs, nodes cannot agree.</p><p><strong>The key connection:</strong></p><ul><li>Determinism enables consensus</li><li>Non-determinism breaks consensus</li></ul><p><strong>Determinism isn’t a feature. It’s a prerequisite.</strong> Consensus computing only works if the computation is deterministic. If nodes don’t execute exactly the same logic, they can’t agree, even if they’re honest.</p><h3>DON Mode vs. Node Mode: Understanding execution contexts</h3><p>The key difference between these modes is <strong>who is responsible for creating a single, trusted result</strong> from the work of many nodes.</p><p><strong>Runtime&lt;C&gt; (DON Mode) — The Default:</strong></p><p>This represents the DON’s (Decentralized Oracle Network) execution context. It’s passed to your main trigger callback.</p><p><strong>When to use:</strong> For operations that are already guaranteed to be Byzantine Fault Tolerant (BFT).</p><p>When you use the Runtime, you ask the network to execute something, and CRE handles the underlying complexity to ensure you get back one final, secure, and trustworthy result.</p><p>Common use cases:</p><ul><li>Writing transactions to a blockchain with the EVM client</li><li>Accessing secrets</li><li>Operations where CRE can automatically provide BFT guarantees</li></ul><p><strong>NodeRuntime&lt;C&gt; (Node Mode):</strong></p><p>This represents an individual node’s execution context.</p><p><strong>When to use:</strong> When a BFT guarantee cannot be provided automatically (e.g., calling a third-party API).</p><p>You tell each node to perform a task on its own, and each node returns its own individual answer. You are then responsible for telling the SDK how to combine them into a single, trusted result by providing a consensus and aggregation algorithm.</p><h3>Potential vulnerabilities and best practices</h3><h3>Determinism is easy to break</h3><p>When workflows run, all nodes must generate identical request IDs for capability calls. If code paths diverge, request IDs differ, quorum is not reached, and the workflow fails.</p><p>The failure pattern is simple:</p><pre>Code diverges → different request IDs → no quorum → workflow fails</pre><h4>Common sources of non-determinism</h4><h4>Object iteration</h4><p>JavaScript objects do not guarantee key order by specification. While modern engines preserve insertion order, relying on this behavior can cause subtle bugs across different runtimes or during JSON serialization.</p><p><strong>Wrong</strong>:</p><pre>const obj = { b: 2, a: 1 }<br>for (const key in obj) {<br>  console.log(key) // Order may vary<br>}</pre><p><strong>Correct</strong>:</p><pre>const obj = { b: 2, a: 1 }<br>for (const key of Object.keys(obj).sort()) {<br>  console.log(key, obj[key]) // Always alphabetical<br>}</pre><p>Maps and Sets preserve insertion order by specification, making them safe for deterministic iteration when order matters.</p><h4>Promise handling and the .result() pattern</h4><p>SDK capabilities use the .result() pattern instead of async/await. When working with multiple operations, the order you call .result() must be deterministic.</p><p>Never use:</p><pre>const fastest = await Promise.race([fetchFromAPI1(), fetchFromAPI2()])<br>const firstSuccess = await Promise.any([fetchFromAPI1(), fetchFromAPI2()])</pre><p>These methods introduce non-determinism because different nodes may “win” the race or succeed with different sources.</p><p>Instead, call .result() in a fixed, deterministic order:</p><pre>import { cre, type Runtime, type NodeRuntime, consensusMedianAggregation } from &quot;@chainlink/cre-sdk&quot;</pre><pre>// Fetch from API 1, then API 2, in a fixed order<br>const fetchPrice = (nodeRuntime: NodeRuntime&lt;Config&gt;): bigint =&gt; {<br>  const httpClient = new cre.capabilities.HTTPClient()</pre><pre>  // Try first API<br>  const response1 = httpClient<br>    .sendRequest(nodeRuntime, {<br>      url: &quot;https://api1.example.com/price&quot;,<br>    })<br>    .result()</pre><pre>  // If first API succeeds, use it; otherwise try second API<br>  if (response1.statusCode === 200) {<br>    return parsePriceFromResponse(response1)<br>  }</pre><pre>  // Try second API as fallback (deterministic order)<br>  const response2 = httpClient<br>    .sendRequest(nodeRuntime, {<br>      url: &quot;https://api2.example.com/price&quot;,<br>    })<br>    .result()</pre><pre>  return parsePriceFromResponse(response2)<br>}</pre><pre>// In your DON mode handler<br>const onTrigger = (runtime: Runtime&lt;Config&gt;): MyResult =&gt; {<br>  // Run the fetch logic in node mode with consensus<br>  const price = runtime.runInNodeMode(fetchPrice, consensusMedianAggregation&lt;bigint&gt;())().result()</pre><pre>  return { price }<br>}</pre><h4>Dates and times</h4><p>Never use JavaScript’s built-in time functions in DON mode. Nodes may have slightly different system clocks, causing divergence.</p><p>Wrong:</p><pre>const now = Date.now()<br>const timestamp = new Date()</pre><p>Correct:</p><pre>const now = runtime.now() // Same timestamp across all nodes</pre><p>runtime.now() returns DON Time, a consensus-derived timestamp that all nodes agree on.</p><h4>Working with LLMs</h4><p>LLMs generate different responses for the same prompt, even with temperature set to zero. This breaks consensus.</p><p>Instead, request structured output (JSON with specific fields) rather than free-form text, then use consensus aggregation on the structured fields. This allows nodes to agree on key data points even if exact text varies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2a8IN6oyxuUttowu2LbLyg.png" /></figure><h3>Randomness must be consensus-safe</h3><p>Standard randomness breaks determinism. If each node generates its own random value using Math.random(), consensus is impossible.</p><p>CRE provides deterministic randomness:</p><ul><li>In DON mode, runtime.random() produces identical sequences across nodes</li><li>In Node mode, nodeRuntime.random() produces per-node randomness suitable for later aggregation</li></ul><p><strong>Never use JavaScript’s built-in randomness. Always use the runtime-provided generator.</strong></p><blockquote>Local simulation does not catch this. Simulation runs with a single-node model. It validates SDK integration but cannot detect non-determinism or multi-node consensus failures. Passing simulation does not imply production safety.</blockquote><h3>Decentralized execution does not mean decentralized data</h3><p>Calling a centralized API from a decentralized workflow does not make the data decentralized.</p><p>If every node calls the same API, owned by the same provider, behind the same infrastructure, all nodes can receive the same manipulated data or no data at all if the service is down.</p><blockquote><strong>Consensus only ensures nodes agree on what they observed. It does not guarantee the observation itself is trustworthy.</strong></blockquote><h3>Using aggregation correctly</h3><p>When you run code in Node mode, each node executes independently and returns its own result. CRE does not decide how those results are combined. In runInNodeMode, that responsibility is entirely yours.</p><p>You can aggregate node results using CRE’s built-in aggregation functions or by writing a custom aggregation function. In both cases, aggregation only answers one question: <strong>do enough nodes agree?</strong> It does not validate correctness. Nodes can reach perfect consensus on a result that is logically wrong.</p><p>CRE’s built-in aggregation functions encode assumptions about the data. They are safe only if those assumptions match reality.</p><ul><li><strong>Median aggregation</strong> consensusMedianAggregation&lt;T&gt;() is suitable for numeric values where outliers should be filtered, such as prices or measurements.</li><li><strong>Identical aggregation</strong> consensusIdenticalAggregation&lt;T&gt;() should be used for values that must match exactly, like block hashes, transaction IDs, or addresses.</li><li><strong>Common prefix and suffix aggregation</strong> consensusCommonSuffixAggregation&lt;T&gt;() are useful for arrays where nodes may observe diverging sequences but still share a common beginning or end.</li><li>For structured data, ConsensusAggregationByFields&lt;T&gt;() allows each field to use an appropriate strategy, which is often safer than forcing a single aggregation rule onto the entire object.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_QdG64v63xo_sLR4g_1vw.png" /></figure><p>All built-in aggregation functions support .withDefault() to return a fallback value when consensus fails. <strong>Using a default is a design choice, not a best practice.</strong> In some workflows it&#39;s safer than failing hard. In others, it hides real problems. Custom aggregation functions carry the same risk if failure cases are not handled explicitly.</p><blockquote><strong>Auditor’s takeaway:</strong> Aggregation determines how nodes agree, not whether the result is correct. When reviewing workflows, the key question is whether the chosen aggregation strategy actually matches the data being aggregated.</blockquote><h3>Validate everything you receive</h3><p>A successful HTTP request does not guarantee valid data. If you do not validate responses, workflows may:</p><ul><li>process error payloads as valid data</li><li>operate on undefined or null values</li><li>aggregate malformed responses</li><li>write garbage onchain</li></ul><p>Always validate:</p><ul><li>HTTP status codes</li><li>response schema</li><li>value ranges</li><li>presence of required fields</li></ul><blockquote><strong>Agreement on bad data is still bad data.</strong></blockquote><h3>Finality when reading from EVM</h3><p>Reading from non-finalized blocks exposes your workflow to blockchain reorganizations (reorgs). Data that looks correct now might later be reversed. CRE provides three confidence levels for reading blockchain data:</p><ul><li><strong>LATEST</strong> : The most recent block, no finality guarantees. Useful for real-time dashboards or displays where speed matters more than certainty.</li><li><strong>SAFE</strong> : A block unlikely to be reorganized, but not fully finalized. Good for monitoring or alerting when you need reasonable confidence. <em>(Note: SAFE is not available for all chain reads.)</em></li><li><strong>FINALIZED</strong> : Blocks considered irreversible. Use for critical operations, financial transactions, or anything where incorrect data could cause significant harm.</li></ul><blockquote>⚠️ <strong>Warning:</strong> If you don’t explicitly specify a block number, CRE defaults to LATEST. This can silently introduce risk.</blockquote><h3>Critical operations after EVM write</h3><p>Chain write operations return a WriteReportReply when the transaction is included in a block, not when it reaches finality. If a block containing your transaction is reorganized:</p><ul><li>CRE’s Transaction Manager (TXM) automatically resubmits your transaction</li><li>Gas bumping is applied as needed to ensure the transaction is included</li></ul><blockquote>If you need absolute certainty that your write transaction reached finality, implement post-write verification by reading the blockchain state after a custom number of confirmations. Do not rely solely on <em>WriteReportReply</em> for finality confirmation.</blockquote><h4>Multiple duplicate report submissions reaching your API.</h4><p>When a workflow executes, all nodes in the DON attempt to send the report to your API. Each node generates its own unique cryptographic signature for the report. Because these signatures differ across nodes, traditional HTTP caching has limited effectiveness. The cache can’t match requests with different signatures.</p><p>To fix, use a two-layer defense strategy:</p><ol><li><strong>Client-side caching</strong> (limited but essential): Always include cacheSettings in your transformation function</li><li><strong>Server-side deduplication</strong> (required): Your API must implement deduplication using the hash of rawReport (keccak256(rawReport)) as the unique identifier</li></ol><h4>Unverified report data being processed by your API.</h4><p>Unlike onchain submissions where the KeystoneForwarder contract automatically verifies signatures, HTTP endpoints receive raw data without cryptographic verification.</p><p>To fix, your receiving API must verify cryptographic signatures against DON public keys before trusting any report data. This is your responsibility. There’s no automatic verification layer for HTTP submissions.</p><h3>Silent numeric bugs</h3><p>One class of silent bugs that might get overlooked is about wrong numeric results caused by differences in how languages handle numbers.</p><p>CRE workflows today are written in Go and TypeScript, but they frequently read from and write to Solidity contracts, which use very different numeric semantics. The way each language represents and manipulates numbers is not uniform:</p><ul><li><strong>Solidity</strong> uses fixed-width integers like uint256, which have strict bounds and defined overflow/underflow behavior on-chain (reverts in 0.8.0+, wraps in earlier versions).</li><li><strong>Go</strong> represents Solidity integers as *big.Int in generated bindings, which supports arbitrary precision but has different behaviors for operations and overflows compared to fixed-width EVM integers.</li><li><strong>TypeScript</strong> uses bigint for Solidity integer types in ABI encoding/decoding, but basic number types are floating-point and can silently lose precision.</li><li><strong>Future SDKs</strong> may introduce new numeric models or type systems (Rust, Python, etc.).</li></ul><p>These differences are inherent to the language runtimes, not bugs in CRE itself. If developers aren’t careful, math can silently:</p><ul><li>Overflow or wrap in ways that differ from on-chain expectations</li><li>Lose precision in off-chain logic before being encoded for the EVM</li><li>Behave inconsistently between what the workflow calculates and what the smart contract expects</li></ul><p>This doesn’t typically break consensus. Every node will compute the same value, but it can lead to agreements on the wrong value.</p><h3>Going low-Level without a clear reason</h3><p>CRE offers two ways to make HTTP requests in TypeScript workflows:</p><ul><li>http.SendRequest (recommended)</li><li>cre.RunInNodeMode (lower-level, manual)</li></ul><p>If your use case fits a standard request/response model, http.SendRequest should be your default choice. It handles deterministic request construction, consensus-friendly execution, and proper interaction with the DON, reducing the surface area for subtle bugs.</p><p>Using RunInNodeMode provides more flexibility, but it also shifts responsibility to you:</p><ul><li>ensuring requests are identical across nodes,</li><li>selecting and applying the correct aggregation strategy,</li><li>preventing duplicate side effects.</li></ul><h3>Forgetting cache settings for HTTP requests</h3><p>By default, every node in the DON executes the same HTTP request independently. For GET requests, this is usually harmless. For non-idempotent requests — such as POST, PUT, PATCH, or DELETE — it introduces real risk.</p><p>Without cache settings, the same request may be executed multiple times, even though consensus succeeds and the workflow completes successfully.</p><p>From CRE’s perspective, nothing is wrong. From the external system’s perspective, the same action just happened more than once.</p><p><strong>How CacheSettings Help</strong></p><p>cacheSettings enables a shared cache across the DON:</p><ul><li>one node executes the request,</li><li>other nodes reuse the cached response,</li><li>side effects occur once instead of many times.</li></ul><p>A typical configuration looks like:</p><pre>cache: {<br>  readFromCache: true,<br>  maxAgeMs: 60000<br>}</pre><p><strong>Important Caveats</strong></p><ul><li><strong>Caching is best-effort, not a guarantee.</strong> Duplicate execution can still occur due to network failures, routing changes, or nodes hitting different gateway instances.</li><li><strong>Choosing </strong><strong>maxAgeMs matters.<br>- </strong>For write operations, it should be slightly longer than the workflow execution time.<br>- For read operations, it should reflect acceptable staleness.<br>- To force fresh execution, set it to 0 or omit caching entirely.</li><li><strong>Caching also requires fully deterministic requests.</strong> The URL, headers, and body must be byte-for-byte identical across nodes. Non-deterministic values like Date.now() will break caching.</li><li><strong>For critical operations, caching should always be combined with API-level idempotency keys</strong>, since cache behavior alone cannot guarantee single execution.</li></ul><h3>Before you ship: Security Checklist</h3><ul><li>[ ] Ensure all object iterations use sorted keys</li><li>[ ] Ensure all time operations use runtime.now()</li><li>[ ] Ensure all randomness uses runtime.random()</li><li>[ ] Ensure critical chain reads use finalized blocks</li><li>[ ] Define aggregation strategies for all Node mode operations</li><li>[ ] Define .withDefault() or explicit failure handling for aggregation</li><li>[ ] Use bigint for all Solidity numeric values</li><li>[ ] Implement post-write verification for critical chain write transactions</li><li>[ ] Validate all HTTP responses (status, schema, ranges)</li><li>[ ] Use cache settings for all non-idempotent HTTP requests</li><li>[ ] Implement API-level idempotency or report hash deduplication</li><li>[ ] Verify cryptographic signatures for HTTP report submissions</li><li>[ ] Use http.SendRequest unless custom node logic is required</li><li>[ ] Document all centralized trust assumptions explicitly</li></ul><h3>Conclusion</h3><p>CRE’s security model is powerful because it is built on consensus. But consensus is unforgiving. It requires strict determinism and cannot detect when all nodes agree on incorrect data.</p><p>The vulnerabilities outlined in this article are the gaps between “it compiles” and “it’s secure.” The mistakes that turn promising workflows into production failures.</p><p><strong>For builders:</strong> Treat determinism as a hard requirement. Validate everything. Test with real multi-node deployments. Use the checklists above.</p><p><strong>For auditors:</strong> Start with determinism, verify data validation, check finality handling, and never trust simulation results alone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99b2e30e7456" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building with Chainlink CRE — Lessons from Developing a Decentralized x402 Payment Facilitator]]></title>
            <link>https://medium.com/@emanherawy/building-with-chainlink-cre-lessons-from-developing-a-decentralized-x402-payment-facilitator-abac7ab716a2?source=rss-65e6393574a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/abac7ab716a2</guid>
            <category><![CDATA[chainkink-cre]]></category>
            <category><![CDATA[x402]]></category>
            <category><![CDATA[devconnect]]></category>
            <category><![CDATA[ethglobal]]></category>
            <dc:creator><![CDATA[Eman Herawy]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 02:05:01 GMT</pubDate>
            <atom:updated>2025-12-08T10:20:51.610Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building with Chainlink CRE — Lessons from Developing a Decentralized x402 Payment Facilitator</h3><p><em>What I learned building three complex workflows at ETHGlobal Buenos Aires</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LZo0BcSd6eHVnM6p" /></figure><p>At ETHGlobal Buenos Aires during Devconnect, our team built <a href="https://ethglobal.com/showcase/wolfy-r87tb"><strong>Wolfy Wallet</strong></a> — a fork of Rabby Wallet with EIP-7702 support, hardware multisig, and most notably, a <strong>fully decentralized x402 payment facilitator built using Chainlink CRE</strong>.</p><p>We walked away with three awards:</p><p>🏆 Chainlink — Best Workflow with Chainlink CRE<br> 🏆 Octav — Best App Built Using Octav API<br> 🏆 Zircuit — Best Zircuit Integration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qytMDoObHvIJRk9u" /></figure><p>But beyond prizes, the real outcome was <strong>learning how CRE behaves when pushed to its limits</strong>. We built three sophisticated workflows — verification, settlement, and execution monitoring — and along the way discovered many quirks, pain points, and breakthroughs.</p><p>This article is a breakdown of what I learned building a decentralized x402 facilitator using CRE in production conditions.</p><h3>What is Chainlink CRE?</h3><p><a href="https://docs.chain.link/cre">Chainlink Runtime Environment (CRE)</a> is Chainlink’s all-in-one orchestration layer unlocking institutional-grade smart contracts — data-connected, compliance-ready, privacy-preserving, and interoperable across blockchains and existing systems.</p><p>Think of it as a way to write code that can:</p><ul><li>Read from multiple blockchains</li><li>Call external APIs securely</li><li>Do computations off-chain</li><li>Write results back on-chain</li><li>All while being decentralized and trustless</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iyHLiOwKPPG0QGxP" /></figure><p>The magic here is that <strong>everything runs across multiple independent nodes</strong> through something called a Decentralized Oracle Network (DON). When your code makes an API call or reads blockchain data, multiple nodes do it independently, then use Byzantine Fault Tolerant consensus to agree on the result. This means you get the same security guarantees as blockchain transactions, but for <em>everything</em> your code does — not just the on-chain parts.</p><p>The SDK currently supports TypeScript and Go, so you can develop your workflow in TypeScript or Go, and CRE compiles it to WebAssembly (WASM) that runs in a sandboxed environment across the DON.</p><h3>Why I Used CRE: The x402 Problem</h3><p>The x402 is basically HTTP 402 (Payment Required) but for crypto — it lets you gate access to services behind on-chain payments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CeevemOeBDBz7jH9" /></figure><p>Here’s the problem: <strong>x402 requires a “facilitator” </strong><em>if the server doesn’t want to do this job</em>— a trusted service that handles the payment flow between clients and servers. The facilitator has three key responsibilities:</p><ol><li><strong>Verify payments</strong>: Confirm that the client’s payment payload meets the server’s declared payment requirements</li><li><strong>Settle payments</strong>: Submit validated payments to the blockchain and monitor for confirmation</li><li><strong>Provide responses</strong>: Return verification and settlement results to the server, allowing the server to decide whether to fulfill the client’s request</li></ol><p>Currently, facilitators are either self-hosted (you run your own server) or hosted facilitator service (trust someone else’s server) e.g. Coinbase’s Facilitator. Both are centralized services.</p><p><strong>We wanted a fully decentralized facilitator.</strong> That’s where CRE came in.</p><h4>Our goal was simple:</h4><blockquote><em>No servers. No trust assumptions.<br> A fully decentralized facilitator.</em></blockquote><h3>What We Built</h3><p>I built <strong>two CRE workflow files</strong> with <strong>three total workflow handlers</strong> that together form a complete decentralized facilitator “ <a href="https://github.com/vm06007/metawolf/tree/master/d-facilitator">source code</a> “:</p><p><strong>The architecture</strong>: Two workflow files (d-verify and d-settlement) with three handlers total - one for verification, one for settlement submission, and one for monitoring execution events.</p><h3>1. Payment Verification Workflow (d-verify)</h3><p><strong>Trigger</strong>: HTTP trigger — receives payment verification requests from servers</p><p><strong>Capabilities Used</strong>:</p><ul><li>EVMCleintread- Multiple calls to verify EIP-712 signatures, check token balances, and validate nonces</li><li>http - Uses sendRequest to POST verification results back to the server</li></ul><p><strong>What it does</strong>: Validates all x402 payment requirements (protocol version, permit signatures, token balances, deadlines, nonces, amounts, recipient addresses)</p><p><strong>Outputs</strong>: HTTP POST callback (via sendRequest) to the server with verification result (pass/fail + details)</p><h3>2. Payment Settlement (d-settlement)</h3><p>This is actually <strong>two workflows in one file</strong> that work together:</p><h4>Workflow 2a: Settlement Submission (HTTP-triggered)</h4><p><strong>Trigger</strong>: HTTP trigger — receives settlement requests after verification succeeds</p><p><strong>Capabilities Used</strong>:</p><ul><li>EVMCleintread: Re-verify payment before settlement (security measure)</li><li>EVMCleintwrite: - Submit signed report to SettlementReceiver contract on-chain</li></ul><p><strong>What it does</strong>: Re-verifies the payment, prepares execution data, generates a signed report, and submits it on-chain to be executed</p><p><strong>Outputs</strong>: Returns JSON (but remember: HTTP triggers don’t actually return data to the caller — you just get an “ACCEPTED” status)</p><h4>Workflow 2b: Execution Monitoring (EVM log-triggered)</h4><p><strong>Trigger</strong>: EVM log trigger — monitors ExecutionSucceeded and ExecutionFailed events from ExecutionProxy contract</p><p><strong>Capabilities Used</strong>:</p><ul><li>http - Uses sendRequest to POST settlement results to the server&#39;s callback URL</li></ul><p><strong>What it does</strong>: Watches the blockchain for settlement execution results from the ExecutionProxy contract and decodes the event data</p><p><strong>Outputs</strong>: HTTP POST callback (via sendRequest) to the server with settlement result (pass/fail + details: success, transaction, network, errorReason, payer)</p><h3>The Hard Lessons</h3><p>Here’s what I learned the hard way building these workflows:</p><h3>1. HTTP Triggers Don’t Return Data (Big Limitation!)</h3><p>When you trigger a workflow via HTTP, you <strong>cannot return data like a normal API</strong>.</p><p>You get back a response like this:</p><p>json</p><pre>{<br>  &quot;success&quot;: true,<br>  &quot;response&quot;: {<br>    &quot;workflow_id&quot;: &quot;0x...&quot;,<br>    &quot;workflow_execution_id&quot;: &quot;0x...&quot;,<br>    &quot;status&quot;: &quot;ACCEPTED&quot;<br>  }<br>}</pre><p>That’s it. Just “we got your request.” Your actual workflow output lives in the CRE logs.</p><p><strong>The Problem</strong>: For x402, the facilitator needs to immediately tell services whether a payment is valid. But we can’t return that data in the HTTP response!</p><p><strong>My Workaround</strong>: I used Chainlink’s http capability to make HTTP sendRequest callbacks to the service with the verification result. Not perfect because:</p><ul><li>It’s not 100% compliant with x402 architecture</li><li>You can hit quota limits on HTTP calls</li><li>But it was the only solution available</li></ul><p><strong>I hope they provide a better solution for this soon.</strong></p><h3>2. External Calls Must Use Capabilities</h3><p>You <strong>cannot</strong> just import a library and make API calls or EVM calls directly (in our case, we were using the x402 library). If you try, you get this unhelpful error:</p><pre>panic: runtime error: invalid memory address or nil pointer dereference</pre><p><strong>Why</strong>: All external interactions (API calls, blockchain reads/writes) must go through CRE’s “capabilities” system. This is how the DON nodes coordinate to execute calls and reach consensus.</p><p><strong>The Learning Curve</strong>: You have to learn to think in capabilities:</p><ul><li>Want to call an API? → Use http capability</li><li>Want to read/write blockchain data? → Use EVMClient Read &amp; Write capabilities</li></ul><p>It’s a different mental model than normal backend development.</p><h3>3. Secrets Configuration Is Confusing</h3><p>When simulating locally, you need to set up secrets in a specific way:</p><p><strong>The Gotcha</strong>: The key name and value name in secrets.yaml <strong>cannot be the same</strong>.</p><p>Wrong:</p><p>yaml</p><pre>secretsNames:<br>  EVM_ADDRESS:<br>    - EVM_ADDRESS  # ❌ This breaks!</pre><p>Right:</p><p>yaml</p><pre>secretsNames:<br>  EVM_ADDRESS:<br>    - EVM_ADDRESS_ALL  # ✅ Different name</pre><p>Then in your .env:</p><p>bash</p><pre>EVM_ADDRESS_ALL=&quot;0x1234...&quot;</pre><p>This tripped me up for hours. The error messages don’t help you figure this out.</p><h3>4. Always Use Cache Settings</h3><p><strong>Critical lesson</strong>: Always include cacheSettings in HTTP requests for non-idempotent operations (POST, PUT, PATCH, DELETE) to prevent duplicate executions.</p><p><strong>The Problem</strong>: All nodes in the DON execute HTTP requests independently. For payment settlements or callbacks, this can cause duplicates.</p><p><strong>The Solution</strong>: cacheSettings creates a shared cache—first node executes the request, others reuse the cached response.</p><p>typescript</p><pre>cacheSettings: {<br>  readFromCache: true,     // Enable cache reading<br>  maxAgeMs: 60000,         // Accept cached responses up to 60 seconds old<br>}</pre><p><strong>Key points</strong>:</p><ul><li>Set maxAgeMs slightly longer than your workflow&#39;s execution time (e.g., 60000ms)</li><li>Caching is <strong>best-effort</strong>, not guaranteed to prevent all duplicates</li><li>Only works if all nodes construct identical requests (same URL, headers, body)</li></ul><p>In our x402 facilitator, we used this for all callback requests to minimize duplicate payment notifications.</p><h3>5. Simulation Requires — broadcast Flag</h3><p>When simulating locally, if you want to do any EVM calls (reads or writes), make sure to pass the --broadcast flag:</p><p>bash</p><pre>cre workflow simulate my-workflow --target staging-settings --broadcast</pre><p>Without it, CRE can’t execute real evm calls in simulation.</p><h3>6. You Need Whitelisting to Deploy</h3><p>Currently only whitelisted accounts can deploy to production CRE. You can simulate locally all you want, but to actually run on the DON, you need Early Access approval.</p><p>During the hackathon, the Chainlink team deployed our workflow for us, but before that we could only simulate, which was enough to validate the architecture.</p><h3>7. Concurrency Limits Are Real</h3><p>You can only run <strong>5 workflows concurrently</strong> across your entire account. This means if 10 payment verification requests come in at once, 5 will process and 5 will queue (and wait up to 10 minutes before being dropped). For a payment facilitator serving multiple users, this is tight. We should rethink about our desgin and plan accordingly.</p><h3>The Service Quotas You Need to Know</h3><p>CRE has strict limits. Here are the key ones that affected my workflows:</p><p><strong>Per-account limits:</strong></p><ul><li>Deploy 1 workflow per minute (burst: 1)</li><li>Maximum 5 concurrent workflow executions across all workflows</li><li>Workflow triggers: 5 per second (burst: 5)</li><li>Max binary size: 100 MB (20 MB compressed)</li></ul><p><strong>Per-workflow limits:</strong></p><ul><li>Triggers fire at 1 per 30 seconds (burst: 3)</li><li>Max 10 triggers per workflow</li><li>5-minute timeout with 100 MB memory</li><li>Maximum 5 concurrent instances per workflow</li><li>100 KB response size limit</li></ul><p><strong>Capability limits:</strong></p><ul><li>3 concurrent capability calls max</li><li>HTTP: 5 calls per execution, 10 KB response, 100 KB request</li><li>EVM read: 10 calls per execution, 100 blocks for log queries</li><li>EVM write: 5M gas quota, 1 KB report size, 10 target chains</li></ul><p><strong>Other limits:</strong></p><ul><li>Logging: 1 KB per line, 1,000 events per execution</li><li>EVM log triggers: max 5 per workflow, monitor up to 5 contract addresses</li></ul><p>These limits are tight when you’re building something production-grade. The 5-concurrent-execution limit especially means you need to think about queuing and retry logic in your application layer.</p><h3>What CRE is Great For</h3><p>IMO, despite the limitations, CRE is genuinely powerful for certain use cases:</p><p>✅ <strong>Cross-chain orchestration</strong>: Our workflows supported 7+ EVM chains (Ethereum, Base, Arbitrum, Optimism, Polygon, Avalanche, BSC) with one codebase “ more to come”</p><p>✅ <strong>Moving computational logic to a trustless decentralized off-chain network</strong>: Reduce on-chain costs by processing complex logic off-chain with the same security guarantees</p><p>✅ <strong>Complex workflows</strong>: Combining HTTP triggers, EVM reads, EVM writes, and log monitoring in one coherent flow</p><p>✅ <strong>Institutional-grade security</strong>: Every operation goes through BFT consensus — no single point of failure</p><h3>What CRE Currently Can’t Do (or Does Awkwardly)</h3><p>❌ <strong>Synchronous HTTP responses</strong>: Can’t return data directly from HTTP-triggered workflows</p><p>❌ <strong>High-frequency operations</strong>: IMO concurrency and rate limits make it unsuitable for high-throughput scenarios</p><p>❌ <strong>Easy debugging</strong>: Error messages need improvement; hard to debug WASM execution issues</p><p>⚠️ <strong>Cost at scale</strong>: Currently there is no cost estimation for your workflow to help you decide. It will definitely be way less than on-chain, but there’s no clarity yet on how much since you’ll be monthly billed</p><h3>Final Thoughts</h3><p>Building a fully decentralized x402 facilitator on CRE wasn’t easy.<br> But it proved a point:</p><blockquote><em>You </em>can<em> run real payment infrastructure<br> without servers, trusted hosts, or custodial intermediaries.</em></blockquote><p>CRE is still early. It has sharp edges.<br> But the architecture is groundbreaking — and worth betting on.</p><p>For everyone keep an eye on it. As the platform matures and adds features like confidential computing, the use cases will expand significantly.</p><p><strong>Resources:</strong></p><ul><li><a href="https://docs.chain.link/cre">CRE Documentation</a></li><li><a href="https://ethglobal.com/showcase/wolfy-r87tb">Our Wolfy Wallet Project</a></li><li><a href="https://x402.gitbook.io/x402">x402 Payment Standard</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abac7ab716a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why everyone in web3 should participate in Hackathon at least once !]]></title>
            <link>https://medium.com/coinmonks/why-everyone-in-web3-should-participate-in-hackathon-at-least-once-fec909275da2?source=rss-65e6393574a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/fec909275da2</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[hackathons]]></category>
            <dc:creator><![CDATA[Eman Herawy]]></dc:creator>
            <pubDate>Sat, 18 Oct 2025 03:57:01 GMT</pubDate>
            <atom:updated>2025-10-23T13:06:51.582Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Why everyone in web3 should participate in Hackathon at least once !</strong></h3><p>Tips and tricks from +10 hackathon winner</p><p>Last May, I co-hosted a community mixer in Cairo for Arabs in blockchain community, during the Chainlink Chromium Hackathon. In the intro talk, I shared some few tips, tricks, and personal insights on why I believe everyone should participate in hackathons. In this article, I’m documenting those thoughts and expanding on them in more detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W11KXiBfr2AMvcvPh8Jf8A.jpeg" /></figure><p><strong>Why You Should Join?!</strong></p><p>If you were there, you probably remember me saying:</p><blockquote>The reason I’m so excited to talk about hackathons is that, after coffee, hackathons are my second favorite thing.</blockquote><p>While that line usually gets a laugh, beyond my personal enthusiasm, there are solid reasons why I encourage you — dear reader — to get involved.</p><p>Hackathons offer learning opportunities you simply won’t find in a classroom or a typical work environment. You’re not just reading about concepts — you’re applying them under time pressure, solving real problems, and shipping actual products. That kind of hands-on experience accelerates your growth in a way no tutorial or lecture ever could.</p><p>They’re also incredible spaces for <strong>meeting like-minded developers, designers, and innovators</strong>. The people you collaborate with during those intense 24–72 hour sprints often become future co-founders, long-term collaborators, or close friends. Many companies quietly use hackathons as headhunting grounds, and a strong teammate or mentor can become your most valuable advocate. A referral from someone who’s seen you perform under pressure is worth far more than a cold LinkedIn message.</p><p>Participating in hackathons doesn’t just boost your skills — it boosts your visibility. Winning (or even just building something impressive) strengthens your CV, helps you stand out in internship and job applications, and gives you direct exposure to recruiters and sponsors who are actively looking for talent. These events are powerful platforms to <strong>showcase your abilities through tangible projects</strong>, grow your professional network, and even unlock funding or incubation opportunities for promising ideas.</p><p>They also keep you up to date with fast-moving technologies, help you build a strong professional reputation, and provide a creative space to explore new ideas outside your daily routine.</p><p>But hackathons aren’t the same. Some are <strong>ideation-focused</strong>, where the main objective is to generate creative concepts and innovative solutions, even if you don’t build a full product. Others emphasize <strong>technical execution</strong>, challenging participants to develop functional prototypes or demonstrate innovative uses of specific technologies. Then there are hackathons that adopt a <strong>startup mindset</strong>, seeking projects with real-world potential, good market fit and strong teams that they can fund, incubate, or support beyond the event. Recognizing the type of hackathon helps you align your team, skills, and strategy to stand out in exactly what the organizers are looking for.</p><p>In this article, the focus is on hackathons that emphasize <strong>technical execution</strong>. These are the events where you come up with an innovative idea and build a functional MVP to showcase your skills and creativity. This doesn’t mean you’re not solving a real problem, but the key difference is that factors like <strong>market research, team completeness, and product–market fit</strong> are not as heavily emphasized. The spotlight is on how well you can use the technology to bring your idea to life within a short time frame, rather than proving the business viability of the project.</p><p>Now I’m assuming you are interested in joining a hackathon and I believe the next questions that came to your mind are:</p><h4><strong>Where to Find Hackathons in Web3</strong></h4><p>First, it’s important to know that there are two main types of hackathons: <strong>online</strong> and <strong>in-person</strong>. Each has its own vibe, advantages, and challenges, and the “best” option really depends on your personal preferences.</p><p>If there were a grand prize for the best hackathon experience, I’d give it to <a href="https://ethglobal.com/"><strong>ETHGlobal</strong></a> — they host both in-person and online events, and their community is top-notch. But ETHGlobal isn’t the only place to look. Platforms like <strong>DoraHacks</strong>, <strong>Devfolio</strong>, and <strong>Devpost</strong> are also major hubs where most Web3 hackathons take place.</p><p>You’ll also come across some of the biggest annual events, such as <strong>ETHDenver</strong>, among many others. A great way to stay informed is by <strong>joining blockchain communities</strong>, where people often share upcoming hackathons, opportunities, and conferences.</p><p>If you haven’t already, consider joining <a href="https://t.me/@ArabsInBlockchain"><strong>our community</strong></a> to stay updated. At the time of writing, we’re promoting the <a href="https://www.hackquest.io/hackathons/Forte-Hacks?utm=MENA"><strong>Forte-Hacks</strong> <strong>—by Flow</strong></a> and if you’re in Cairo, join us <a href="https://luma.com/54f7ai3s"><strong>today for a hackathon mixer</strong></a>!</p><h4><strong>Which Hackathon to Join — How to Evaluate and Choose the Best</strong></h4><p>When deciding which hackathon to join, I usually focus on a few key factors to make sure I get the best possible hacking experience — because hacking should be fun!</p><p>The <strong>first thing I look at is the organizer</strong>. A well-organized hackathon sets the tone for everything. I check their reputation for <strong>support, safety, and trust</strong>. Trust is especially important — you need to be confident that the organizers and sponsors will actually deliver the prizes and rewards they promise.</p><p>Next, I look at the <strong>prize pool</strong>. Naturally, a larger prize pool is more attractive. <strong>Competing for $500K is far more motivating than competing for $10K.</strong></p><p>Finally, I consider the <strong>diversity of hacking ideas and technologies</strong>. The more diverse the tracks and challenges, the more room there is for <strong>innovation, learning, and creativity</strong>. A broad range of themes keeps things exciting and gives you the chance to explore new tools and ideas.</p><h4><strong>How to Join and form a team</strong></h4><p>The process of joining a hackathon depends on the <strong>specific rules and format</strong>, so it’s important to read the guidelines carefully for each event.</p><p>When it comes to <strong>team building</strong>, there are several ways to find teammates — or for others to find you. Most hackathons have <strong>team formation channels</strong> on Discord, where participants can introduce themselves and connect. You can also meet potential teammates at <strong>online or in-person mixers</strong> (like the one we’re hosting tomorrow!), or simply <strong>post on social media</strong> to let others know you’re looking for a team or a teammate.</p><p><strong>Don’t be afraid or shy</strong> to put yourself out there — posting that you’re looking for teammates or replying to others’ posts is completely normal and often leads to great collaborations. If you don’t already have friends joining the hackathon, don’t worry — <strong>hackathons are amazing spaces to meet new people and build long-term friendships.</strong></p><p>In fact, during my last hackathon, I met my teammate through a <strong>Discord team formation channel</strong>, and together we ended up as <strong>finalists at </strong><a href="https://ethglobal.com/showcase/ef-ethereumfigther-7hq6d"><strong>ETHGlobal Tippie</strong></a>. That’s the power of putting yourself out there.</p><h4><strong>How to Secure a Win</strong></h4><p>Now let’s talk about some <strong>tips and tricks to help you secure that win — and maybe even some prize money</strong>. But remember winning isn’t just about the money. It’s also about the <strong>recognition</strong> you earn for doing an amazing job, mastering the technology, and proving that you can <strong>build and ship a product within 24 hours</strong> (if it’s a 24-hour hackathon). And honestly, there’s <strong>nothing more lovely and exciting than hearing or reading “You are a winner!” after all your hard work</strong>. That moment makes everything worth it.</p><p>Here are some practical <strong>tips and common mistakes to avoid</strong> to increase your chances of winning:</p><ul><li><strong>Pick a simple but powerful idea:</strong> Focus on solving a real problem with a clear, executable concept. Overly ambitious ideas often end up half-finished.</li><li><strong>Avoid trying to build a massive dream project in 24 hours:</strong> Keep your scope realistic. It’s better to <strong>start small, iterate, and deliver a working MVP</strong> than to start big and never finish.</li><li><strong>Think smart, but don’t get stuck debating:</strong> Good ideas need discussion, but there’s a fine balance. Productive planning early on is essential, but <strong>endless arguing and overthinking waste precious time</strong>. Decide, commit, and move forward.</li><li><strong>Start fast:</strong> The first hours are critical. Don’t spend the entire first day in meetings — make decisions early and begin building to give yourself time to refine later.</li><li><strong>Build a balanced team:</strong> A strong mix of tech, design, and business skills sets you up for success. But it’s not just about skills — it’s about <strong>attitude and commitment</strong>. A reliable teammate who knows less but delivers consistently is often more valuable than someone highly skilled but unreliable.</li><li><strong>Stay focused:</strong> A scattered team rarely wins. Clear direction, discipline, and good communication keep the project on track.</li><li><strong>Avoid bad pitching:</strong> If you can’t communicate your idea well, no one will understand what you’ve built — even if it’s brilliant.</li><li><strong>Make the judges’ job easy:</strong> Don’t make them work to figure out what you built. Structure your <strong>demo, pitch, and documentation</strong> so the value and impact are obvious. A well-written <strong>README and submission</strong> that explains your project clearly and guides them through your work will make it much easier for judges to grasp everything quickly.</li><li><strong>Align your project with the hackathon theme:</strong> Show a clear connection between your solution and the challenge.</li><li><strong>Leverage existing tools:</strong> Use pre-built frameworks and libraries to save time — hackathons reward speed and creativity, not reinventing the wheel. <strong>Make smart use of AI tools and VibeCode</strong> to speed up development and focus on what really matters.</li><li><strong>Document as you go:</strong> This simplifies preparing your final presentation and demo.</li><li><strong>Talk to mentors early:</strong> Early feedback can save you from major mistakes later.</li><li><strong>Organize time and roles from the start:</strong> Clear planning avoids last-minute chaos and ensures everyone knows their responsibilities.</li><li><strong>Start gathering feedback as early as possible</strong>, especially on the <strong>problem you’re solving</strong>, your <strong>approach</strong>, and how you’re planning to build it. This kind of input is most valuable before you start coding heavily — it can help you catch blind spots, refine your scope, and avoid wasting hours on the wrong direction. Talk to mentors, judges, experienced builders, or even other participants. <strong>Pay close attention to their reactions</strong>. Interest, follow-up questions, or suggestions usually mean you’re on to something. Confusion or disengagement can signal that your problem statement or approach isn’t clear enough yet.</li><li><strong>keep pitching your idea to everyone you meet</strong> throughout the hackathon. Each quick pitch acts as practice — it helps you sharpen your idea and uncover different perspectives. People will often give you useful feedback on missing features, alternative tools, or stronger ways to frame the problem.</li></ul><p>By applying these tips and avoiding common pitfalls, you’ll <strong>significantly boost your chances of standing out</strong>, impressing the judges, and hearing those magic words: <em>“You are a winner!”</em></p><h4><strong>What If You Don’t Win</strong></h4><p>Let’s be honest: most hackathons won’t end with you holding a trophy. But here’s the truth — some of my most valuable experiences came from hackathons where I didn’t place. Here’s how to turn a “loss” into real growth:</p><ul><li><strong>Get feedback immediately</strong>: Approach judges and mentors while the event is still fresh. Ask specific questions: “What could have made our project stronger?” or “Was our technical approach solid?” This insight is invaluable for your next attempt.</li><li><strong>Your project still has value</strong>: Just because judges didn’t pick you doesn’t mean your idea is worthless. Continue building it, open-source it, or add it to your portfolio. A well-documented GitHub repo can impress recruiters more than a trophy. Many successful startups — including some unicorns — began as “losing” hackathon projects.</li><li><strong>Reflect objectively</strong>: Analyze what worked and what didn’t. Was it the idea? Execution? Pitch? Team dynamics? Write a quick post-mortem while it’s fresh in your mind.</li><li><strong>Showcase your work anyway</strong>: Post about your project on social media, write a blog post, or create a demo video. Frame it as “Here’s what I built in 24 hours at [Hackathon]” rather than focusing on placement. The tech community respects builders, win or lose.</li><li><strong>Leverage your network</strong>: The connections you made matter more than the prize. Stay in touch with teammates, other participants, and sponsors. Some of my closest collaborators and job opportunities came from hackathons where we didn’t win anything.</li><li><strong>Iterate if there’s potential</strong>: If your idea has legs, keep working on it post-hackathon. Refine it, get user feedback, and maybe even launch it properly.</li><li><strong>Use it as fuel, not discouragement</strong>: Every hackathon winner has lost multiple times. I certainly have. Each setback taught me something that contributed to future wins. The question isn’t whether you’ll face losses — it’s whether you’ll let them stop you or use them as stepping stones.</li></ul><p><strong>Remember</strong>: You just compressed weeks of learning into 24–48 hours and shipped something under intense pressure. That alone is an achievement. The goal isn’t just winning prizes — it’s becoming the kind of person who can build, ship, and present under pressure. That skill is worth more than any single prize pool.</p><h3><strong>Conclusion</strong></h3><p>Hackathons are more than just competitions — they’re intense learning experiences, career accelerators, and community-building moments rolled into one. Whether you’re a developer, designer, marketer, or simply curious about Web3, joining at least one hackathon can open doors you didn’t even know existed. You’ll build real projects, meet inspiring people, push your skills to new levels, and maybe even walk away with a prize — or a startup idea that changes your career path.</p><p>So don’t wait for the “perfect” moment or the “right” team. Pick a hackathon, show up, and give it your best. The worst that can happen is that you’ll learn something new. The best that can happen? You’ll surprise yourself with what you can achieve in just a few days.</p><p><strong>See you at the next hackathon </strong>👩‍💻🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fec909275da2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/why-everyone-in-web3-should-participate-in-hackathon-at-least-once-fec909275da2">Why everyone in web3 should participate in Hackathon at least once !</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[0xVillage: Unique Post-Devconnect Experience]]></title>
            <link>https://medium.com/@emanherawy/0xvillage-unique-post-devconnect-experience-89f12097ad6b?source=rss-65e6393574a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/89f12097ad6b</guid>
            <category><![CDATA[devconnect]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[retreats]]></category>
            <dc:creator><![CDATA[Eman Herawy]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 20:03:33 GMT</pubDate>
            <atom:updated>2023-12-06T20:10:35.235Z</atom:updated>
            <content:encoded><![CDATA[<h4>Where Dreams of Crypto community Meet Nature’s Embrace</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K9yjMYwy4I20iKlr.jpg" /></figure><p>From the heart of Istanbul, where the vibrant hum of Ethereum enthusiasts echoed through the city during <a href="https://devconnect.org/">Devconnect</a>, I went on a transformative journey that extended far beyond the conference walls to the Nesin Mathematics Village, a hidden gem in Western Turkey. My journey from the bustling Ethereum Devconnect in Istanbul to this unique retreat was not just a transition of locations; it was a transformation of experience.</p><h3>Devconnect: A Prelude to the Extraordinary</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQoPFqV6jCTI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQoPFqV6jCTI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQoPFqV6jCTI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/80a76a767322935b028a69d35840edde/href">https://medium.com/media/80a76a767322935b028a69d35840edde/href</a></iframe><p>Devconnect, held from November 13–19, was a spectacle of Ethereum innovation that drew over 3500 enthusiasts. As I immersed myself in the dynamic atmosphere at the Devconnect Cowork in the Istanbul Congress Center, little did I know that the real magic was yet to unfold in the tranquil haven of the Nesin Mathematics Village.</p><h3>Post-DevConnect: 0xVillage at Nesin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*b1laikm2SUx2zzYy.png" /></figure><p>From November 19–23, following Devconnect, I went to <a href="https://0xvillage.org/">0xVillage</a>, nestled in the Nesin Mathematics Village in Western Turkey. This unique program was a collaborative effort to bridge the worlds of Ethereum and the Turkish math community, fostering a long-lasting relationship. The primary aim was to create a space for researchers to delve into web3 without the distractions of marketing or business components.</p><h3>Intro to the Nesin Mathematics Village:</h3><p>The <a href="https://nesinkoyleri.org/en/main-page/">Nesin Mathematics Village</a> is a non-profit village dedicated to math, philosophy and the arts. It’s a picturesque place not far from the <a href="https://en.wikipedia.org/wiki/Ephesus">ancient city of Ephesus</a> and the <a href="https://en.wikipedia.org/wiki/Temple_of_Artemis">Temple of Artemis</a>, one of the Seven Wonders of the Ancient World. It is like Smurfs but with math. Classes run the entire year (check the <a href="https://nesinkoyleri.org/en/events/2023-nmk-undergraduate-and-graduate-summer-camp/">summer undergraduate/graduate program</a>). 0xVillage was an <a href="https://nesinkoyleri.org/en/organise-an-event/">independent event</a> in the Village. For a firsthand story of the Village, check out Ali Nesin’s <a href="https://www.youtube.com/watch?v=XI4RwMmLQHQ">Leelavati Prize Lecture</a>.</p><h3>The Essence of 0xvillage: Learning, Exploring, Connecting</h3><h4>1. Learning:</h4><p>The core of the program experience lies in its dedication to mathematics, art, and philosophy. Participants engage in research talks on crypto, expanding their knowledge base in a focused and uninterrupted environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yowqhYqaeodQBj-6btb32g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hsT6TNFDNMykqXu_de2UuA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uc6mjP1R5u8-UqA5p8AaSA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWAN83XBOVIDhrwqar8tCA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEv-yM7R4VbI5SyYpobcYg.jpeg" /></figure><h4>2. Exploring:</h4><p>The program is not just about learning; it’s about embracing the surrounding regions. We had the opportunity to explore the rich history of Ephesus, delve into local culture, and experience the warmth of Turkish hospitality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30FckRY1Ms85UEc1wEudaA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2T0rzelNz5VXoiT3qld-Vg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmxMU8chkZonSRl6boyY3w.jpeg" /></figure><h4>3. Connecting:</h4><p>One of the most enriching aspects of 0xVillage was the diverse representation from countries around the world — Belgium, Canada, Egypt, France, Germany, Honduras, India, Iran, Japan, Poland, Singapore, South Korea, Thailand, Tunisia, Turkey, and the USA. The gathering of minds fostered connections that transcended geographical boundaries, creating a global network of like-minded individuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFgsJFJCJSvxsfpbjNjfDQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*Dbs9hl0GDb9iXS41loBMrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNEFpVQMEgJhh_Y9OqoOuA.png" /></figure><h4>4. Enjoying Our Time:</h4><p>In the beautiful Nesin Mathematics Village, we didn’t just stick to the scheduled stuff; we really connected and relaxed. We found quiet spots to chat, and shared meals together. Nature was our chill-out zone — walks, thinking time, and getting creative in a laid-back way. Our time in Nesin became a cool mix of building tight bonds, just enjoying the moment as well as learning, making our experience there really special.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBQujdM8ZRc1fIUm52JDFA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9K-yhVu28iLv3aVmVCfgg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*0XvpzQ9fMAhTt5kG0WdD9A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*aP-30vF94gybUkoAwbqOnw.jpeg" /></figure><h4>5. Embracing Inclusivity and Cultural Exchange</h4><p>The program, led by <a href="https://yigitkilicoglu.com/">Yiğit Kılıçoğlu</a> and <a href="https://nourassili.com/">Nour Assil</a>, co-organizer, deserve special appreciation for their commitment to exclusivity. The Nesin Mathematics Village is a testament to the power of collaborative and cooperative philosophy, providing a space for individuals from all walks of life to come together and explore the intersections of crypto and culture.</p><h3>Action Items: A Call to Support and Expand the Experience</h3><p>As we reflect on this transformative experience, two crucial action items come to light:</p><h4>Support the village:</h4><p>Nesin Mathematics Village relies on support to continue its mission. Consider contributing to sustain this unique haven for learning and cultural exchange. <a href="https://nesinkoyleri.org/en/gallery/">Check the village gallery</a></p><h4>Expand the experience globally:</h4><p>Let’s replicate this enriching experience worldwide. Imagine 0xVillage events in different countries, each infused with its own unique color and flavor.</p><h3>Closing Thoughts: Valuing Humanity in Crypto Spaces</h3><p>In the dynamic world of cryptocurrency, let’s not forget the essence of humanity. We need a blend of learning, exploration, and cultural exchange, all immersed in the purity of nature. As we advocate for more inclusive initiatives, let’s bridge gaps and discover the beauty in diverse hearts worldwide. There’s a world full of wonders waiting to be explored — why not embark on this collective journey?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/0*0yiBLtMfCwK0KaQ-.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89f12097ad6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 smart contract vulnerabilities with code examples]]></title>
            <link>https://medium.com/coinmonks/10-smart-contract-vulnerabilities-with-code-examples-38562685fca2?source=rss-65e6393574a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/38562685fca2</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[audit]]></category>
            <dc:creator><![CDATA[Eman Herawy]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 00:14:49 GMT</pubDate>
            <atom:updated>2023-11-27T08:47:50.026Z</atom:updated>
            <content:encoded><![CDATA[<p>A Comprehensive Guide for Understanding and Mitigating Security Risks in Blockchain Smart Contracts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*UcDRto5caiNyU31P2jb5aA.png" /></figure><h3>Disclaimer</h3><p>This article, “10 smart contract vulnerabilities with code examples” was prepared as part of <a href="https://www.ekolance.io/smartcontractauditor">Ekolance’s smart contract audit training</a>. It is intended for educational purposes only.</p><h3>Introduction</h3><p>This article is a compilation of 10 smart contract vulnerabilities, with code examples and explanations. It’s an attempt to create a comprehensive list of known vulnerabilities and to provide a resource for smart contract auditors and developers.</p><h3>#1 Reentrancy</h3><h4>Description</h4><p>Reentrancy is a vulnerability that allows an attacker to re-enter a function multiple times before the first function call is finished. so whenever the contract makes external call to other addresses, this is a possibility for reentrancy attack.This can lead to unexpected behavior, including reordering of transactions, and can be used to drain funds from a contract. Rareskills did a fantastic job explaining the different types of vulnerabilities in<a href="https://www.rareskills.io/post/smart-contract-security"> this article</a>, as below:</p><ul><li>When Ether is transferred, the receiving contract’s fallback or receive function is called. This hands control over to the receiver.</li><li>Some token protocols alert the receiving smart contract that they have received the token by calling a predetermined function. This hands the control flow over to that function.</li><li>When an attacking contract receives control, it doesn’t have to call the same function that handed over control. It could call a different function in the victim smart contract (cross-function reentrancy) or even a different contract (cross-contract reentrancy)</li><li>Read-only reentrancy happens when a view function is accessed while the contract is in an intermediate state.</li></ul><h4>Code Example:</h4><pre>function withdraw(uint amount) public{<br>    if (credit[msg.sender]&gt;= amount) {<br>      require(msg.sender.call.value(amount)());<br>      // here we are updating the credit after the external call, which is vulnerable to reentrancy attack<br>      credit[msg.sender]-=amount;<br>    }<br>  </pre><h4>A real-life example</h4><ul><li><a href="https://github.com/pcaversaccio/reentrancy-attacks">A Historical Collection of Reentrancy Attacks</a></li></ul><h4>Mitigation</h4><ul><li>Use the checks-effects-interactions pattern to avoid reentrancy attacks.</li><li>Use a reentrancy lock (ie. OpenZeppelin’s ReentrancyGuard).</li></ul><h4>Reference</h4><ul><li><a href="https://swcregistry.io/docs/SWC-107/">SWC-107</a></li><li><a href="https://www.rareskills.io/post/smart-contract-security">RareSkills article</a></li></ul><p>The below 3 vulnerabilities are related to <strong>access control</strong> issues in smart contracts.</p><p><em>Access control vulnerabilities in smart contracts occur when there are flaws or weaknesses in the way a contract manages and enforces permissions or restrictions related to </em><strong><em>who can perform specific actions or operations within the contract</em></strong><em>. These vulnerabilities can lead to unauthorized access, manipulation, or control of the smart contract, potentially resulting in security breaches or financial losses. To simplify the explanation, we can say that </em><strong><em>access control is about controlling who calls a function.</em></strong></p><h3>#2 Missing Access Controls:</h3><ul><li>A smart contract may be missing access controls, allowing anyone to perform certain actions or operations that should be restricted to specific users or accounts. For example, a smart contract may allow anyone to withdraw funds from a contract or destruct the contract, when only the contract owner should be able to do so.</li></ul><h4>Code Example:</h4><pre>pragma solidity ^0.4.22;<br>   contract SimpleSuicide {<br>   function sudicideAnyone() {<br>       selfdestruct(msg.sender);<br>       }<br>   }</pre><h4>A real-life example</h4><ul><li>0xbad, a notorious MEV bot.An anonymous attacker noticed a flaw in the bots arbitrage contract code, and drained 0xbad’s wallet “1,101 ETH”. The attacker noticed that “callFunction,” which is the function called by the dYdX router as a part of flashloan execution, wasn’t properly protected and allowed arbitrary code to be executed. The attacker used this to get 0xbad to approve all of their WETH for spender on their contract. The attacker then simply transferred the WETH out to their address. The attack has a nice story to read TBH, you can check it <a href="https://rekt.news/ripmevbot/">here</a></li><li>Unprotected init() function was missing onlyOwner modifier, <a href="https://medium.com/immunefi/88mph-function-initialization-bug-fix-postmortem-c3a2282894d3">details</a>.</li></ul><h4>Mitigation</h4><ul><li>Implement Proper Access Controls: Carefully design and implement access control mechanisms within your smart contract. Clearly define who can perform specific actions and enforce these rules in the contract’s code.</li></ul><h4>Reference</h4><ul><li><a href="https://swcregistry.io/docs/SWC-106/">SWC-106</a></li><li><a href="https://swcregistry.io/docs/SWC-105/">SWC-105</a></li><li><a href="https://rekt.news/ripmevbot/">rekt.news</a></li></ul><h3>#3 Weak Access Controls:</h3><h4>Description</h4><p>Contracts may implement access controls, but they are not robust enough to adequately restrict access to sensitive functions or data. Weak access controls often rely on simple checks that can be bypassed.</p><h4>Code Example:</h4><pre>function claimAirdrop(bytes32 calldata proof[]) {<br>    bool verified = MerkleProof.verifyCalldata(proof, merkleRoot, keccak256(abi.encode(msg.sender)));<br>    require(verified, &quot;not verified&quot;);<br>    require(alreadyClaimed[msg.sender], &quot;already claimed&quot;);<br>    _transfer(msg.sender, AIRDROP_AMOUNT);<br>    //  &quot;alreadyClaimed&quot; is never set to true, so the claimant can issue call the function multiple times.<br>}</pre><h4>Mitigation</h4><ul><li>Implement Proper Access Controls: Carefully design and implement access control mechanisms within your smart contract. Clearly define who can perform specific actions and enforce these rules in the contract’s code.</li></ul><h4>A real-life example</h4><ul><li>On October 27, 2022 UvToken lost $1.5M due to <a href="https://substack.com/redirect/3b95d4b4-da92-49c0-beba-6ccb2a0ba7fb?r=1n8pr"><strong>insufficient access controls</strong></a>.</li></ul><h4>Reference</h4><ul><li><a href="https://medium.com/@numencyberlabs/loss-1-5-m-technical-analysis-for-uvtoken-attacked-83ae7c35f10e">https://medium.com/@numencyberlabs/loss-1-5-m-technical-analysis-for-uvtoken-attacked-83ae7c35f10e</a></li></ul><h3>#4 Privilege Escalation:</h3><h4>Description:</h4><p>Privilege escalation vulnerabilities occur when a user can upgrade their own permissions within the contract, gaining access to functions or data they were initially restricted from. As common example of this is when an attacker takes ownership of the contract . Code Example:</p><h4>A real-life example</h4><ul><li>E<a href="https://medium.com/immunefi/enzyme-finance-missing-privilege-check-bugfix-review-ddb5e87b8058">nzyme Finance bug</a>: Enzyme Finance implements meta transaction via OpenGNS. In Enzyme Finance Implementation, there wasn’t any verification of the provided forwarder’s address in the paymaster making any malicious <strong>forwarder</strong> makes many relayCalls to the <strong>RelayHub</strong> until the target fund’s Vault is drained. The bug and fix are well explained in this <a href="https://medium.com/immunefi/enzyme-finance-missing-privilege-check-bugfix-review-ddb5e87b8058">article</a>.</li><li>Implement Proper Access Controls: Carefully design and implement access control mechanisms within your smart contract. Clearly define who can perform specific actions and enforce these rules in the contract’s code.</li></ul><h4>Reference</h4><h4>Reference</h4><ul><li><a href="https://medium.com/immunefi/enzyme-finance-missing-privilege-check-bugfix-review-ddb5e87b8058">https://medium.com/immunefi/enzyme-finance-missing-privilege-check-bugfix-review-ddb5e87b8058</a></li></ul><h3>#5 Missing or Improper Input Validation</h3><h4>Description</h4><p>Missing or improper input validation is a vulnerability in a smart contract that occurs when the contract fails to adequately check and validate the data and parameters supplied by users or external sources before processing them. This vulnerability can have significant security implications as it may allow malicious actors to exploit the contract’s weaknesses. Here’s a breakdown of the key aspects of this vulnerability:</p><h4>Code Example:</h4><pre>contract UnsafeBank {<br>    mapping(address =&gt; uint256) public balances;<br>    // allow depositing on other&#39;s behalf<br>    function deposit(address _for) public payable {<br>        balances[_for] += msg.value;<br>    }<br>    function withdraw(address from, uint256 amount) public {<br>        require(balances[from] &lt;= amount, &quot;insufficient balance&quot;);<br>        // attacker can withdraw more than their balance. Also attacker can withdraw from any address because no checks for authorization as well <br>        balances[from] -= amount;<br>        msg.sender.call{value: amout}(&quot;&quot;);<br>    }<br>}</pre><h4>A real-life example</h4><p>SushiSwap RouteProcessor2 : This contract contained a vulnerability where it didn’t properly validate the route parameter provided by the user to the processRoute function. This vulnerability allowed an attacker to set the route to point to a malicious, attacker-controlled pool. With a malicious pool, the attacker can call <strong>swapUniV3</strong>, which will set the variable <strong>lastCalledPool</strong> to the address of its pool and call the swap function of the malicious pool. That swap function will call uniswapV3SwapCallback, which validates the sender by checking to see that they are the <strong>lastCalledPool</strong>. Since this value is set to the malicious pool’s address, its callback is accepted. With the ability to call back into the <strong>uniswapV3SwapCallback</strong> function, the attacker can construct transactions that drain tokens from the account of users that set up approvals for the new <strong>RouteProcessor2</strong> contract. <strong><em>The attackers managed to steal about $3.3 million</em></strong>, and the scope of the attack was limited by whitehack hacks that frontrun malicious transactions.</p><h4>Mitigation</h4><p>To mitigate this vulnerability, smart contracts should implement robust input validation checks. This includes verifying the sender’s authority, checking parameter values against predefined constraints, validating external data sources, and ensuring that input doesn’t exceed specified limits.</p><h4>Reference</h4><ul><li><a href="https://www.halborn.com/blog/post/explained-the-sushi-swap-hack-march-2023">SushiSwap hack explained</a></li><li>i<a href="https://medium.com/immunefi/the-top-10-most-common-vulnerabilities-in-web3-bf7a921d489f#:~:text=Improper%20input%20validation%20occurs%20when,data%2C%20or%20cause%20unexpected%20behavior.">The Top 10 Most Common Vulnerabilities In Web3</a></li></ul><h4>Description</h4><p>A signature replay attack, also known as a replay attack, occurs when an attacker takes a valid signature from one transaction and reuses it to authenticate a different transaction in the same chain or in differnt b blockchain network.</p><h4>Code Example:</h4><pre>// missing noonce <br>// SPDX-License-Identifier: MIT<br>pragma solidity ^ 0.8.17;<br><br>import &quot;github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.5/contracts/utils/cryptography/ECDSA.sol&quot;;<br><br>contract Vault {<br>    using ECDSA for bytes32;<br><br>        address public owner;<br><br>    constructor() payable {<br>        owner = msg.sender;<br>    }<br><br>    function transfer(address to, uint amount, bytes[2]memory sigs) external {<br>        bytes32 hashed = computeHash(to, amount);<br>        require(validate(sigs, hashed), &quot;invalid sig&quot;);<br><br>        (bool sent, ) = to.call{ value: amount } (&quot;&quot;);<br>        require(sent, &quot;Failed to send Ether&quot;);<br>    }<br><br>    function computeHash(address to, uint amount) public pure returns(bytes32) {<br>        return keccak256(abi.encodePacked(to, amount));<br>    }<br><br>    function validate(bytes[2]memory sigs, bytes32 hash) private view returns(bool) {<br>        bytes32 ethSignedHash = hash.toEthSignedMessageHash();<br><br>        address signer = ethSignedHash.recover(sigs[0]);<br>        bool valid = signer == owner;<br><br>        if (!valid) {<br>            return false;<br>        }<br><br>        return true;<br>    }<br>}<br><br><br>// missing chain id <br><br>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.5/contracts/utils/cryptography/ECDSA.sol&quot;;<br><br>contract Vault {<br>    using ECDSA for bytes32;<br><br>    address public owner;<br>    mapping(bytes32 =&gt; bool) public executed;<br><br>    constructor() payable {<br>        owner = msg.sender;<br>    }<br><br>    function transfer(address to, uint amount, uint nonce, bytes[2] memory sigs) external {<br>        bytes32 hashed = computeHash(to, amount, nonce);<br>        require(!executed[hashed], &quot;tx already executed&quot;);<br>        require(validate(sigs, hashed), &quot;invalid sig&quot;);<br><br>        executed[hashed] = true;<br><br>        (bool sent, ) = to.call{value: amount}(&quot;&quot;);<br>        require(sent, &quot;Failed to send Ether&quot;);<br>    }<br><br>    function computeHash(address to, uint amount, uint nonce) public view returns (bytes32) {<br>        return keccak256(abi.encodePacked(address(this), to, amount, nonce));<br>    }<br><br>    function validate(bytes[2] memory sigs, bytes32 hash) private view returns (bool) {<br>        bytes32 ethSignedHash = hash.toEthSignedMessageHash();<br><br>        address signer = ethSignedHash.recover(sigs[0]);<br>        bool valid = signer == owner;<br><br>        if (!valid) {<br>            return false;<br>        }<br><br>        return true;<br>    }<br>}</pre><h4>A real-life example</h4><ul><li>Yearn Vaults on ETH POW forks that use the same chainId and a DOMAIN_SEPARATOR value that is calculated at contract deployment are vulnerable to replay attacks, <a href="https://github.com/yearn/yearn-security/blob/master/disclosures/2022-09-06.md">details</a>.</li></ul><h4>Mitigation</h4><ol><li>Use <strong>Nonces or Timestamps</strong> Incorporate nonces (random numbers) or timestamps into messages. Each message should have a unique nonce or timestamp, making it impossible for an attacker to replay the same message multiple times.</li><li>Use a chain-specific signature scheme such as <a href="https://eips.ethereum.org/EIPS/eip-155/">EIP-155</a>, which includes the chain ID in the signed message. This will prevent transactions signed on one chain from being valid on another chain with a different ID.</li></ol><h4>Reference</h4><ul><li><a href="https://neptunemutual.com/blog/understanding-signature-replay-attack/">replay attack explained</a></li><li><a href="https://coinsbench.com/signature-replay-hack-solidity-13-735997ad02e5">https://coinsbench.com/signature-replay-hack-solidity-13-735997ad02e5</a></li></ul><h3>#7 Sandwich attacks (front-running/back-running)</h3><h4>Description</h4><p>Sandwich attacks, also known as front-running and back-running, are types of malicious trading strategies that exploit the order execution process on decentralized exchanges (DEXs) and automated market makers (AMMs) in the cryptocurrency space. These attacks involve manipulating the order book to profit from the price movements caused by a victim’s trade. Here’s how sandwich attacks work:</p><p>Front-Running: In a front-running attack, an attacker monitors pending transactions in a blockchain’s mempool to identify a large trade about to occur. The attacker quickly places their own buy or sell order with slightly better terms than the victim’s trade. This causes the victim’s trade to execute at a less favorable price, while the attacker’s trade benefits from the price change caused by the victim’s order.</p><p>Back-Running: Back-running is a similar concept but involves the attacker placing their trade just after the victim’s trade has been confirmed but not yet included in a block. This allows the attacker to profit from the price change caused by the victim’s trade before it becomes part of the blockchain.</p><h4>A real-life example</h4><p><a href="https://medium.com/@Hypernative/exotic-culinary-hypernative-systems-caught-a-unique-sandwich-attack-against-curve-finance-6d58c32e436b">Exotic culinary</a>: Hypernative systems caught a unique Sandwich Attack against Curve Finance</p><h4>Mitigation</h4><ul><li>Implement anti-front-running measures: Developers can implement technical measures to prevent front-running and other attacks. This might include measures such as batched orders, preventing attackers from seeing the details of pending trades.</li><li>Use private mempool “ dark pool” to hide your transactions</li></ul><h4>Reference</h4><ul><li><a href="https://beincrypto.com/learn/sandwich-attacks-explained/">https://beincrypto.com/learn/sandwich-attacks-explained/</a></li><li><a href="https://systemweakness.com/caught-in-the-middle-understanding-and-preventing-defi-sandwich-attacks-bdf1d33e401d">https://systemweakness.com/caught-in-the-middle-understanding-and-preventing-defi-sandwich-attacks-bdf1d33e401d</a></li><li><a href="https://medium.com/@Hypernative/exotic-culinary-hypernative-systems-caught-a-unique-sandwich-attack-against-curve-finance-6d58c32e436b">https://medium.com/@Hypernative/exotic-culinary-hypernative-systems-caught-a-unique-sandwich-attack-against-curve-finance-6d58c32e436b</a></li></ul><h3>#8 Price oracle manipulation</h3><h4>Description:</h4><p>Price oracle manipulation is a form of attack or manipulation in decentralized finance (DeFi) and blockchain-based systems that involves manipulating the data provided by a price oracle to gain an unfair advantage or exploit vulnerabilities in smart contracts. Price oracles are external data sources that supply real-world data, such as asset prices or exchange rates, to smart contracts for various purposes, including decentralized trading and lending. Price oracle manipulation can have serious consequences, as it can lead to financial losses and destabilize DeFi platforms.</p><p>Code Example:</p><blockquote><em>It is a price manipulation issue, which can be exploited by donation to incorrectly calculate the price as shown in the following figures.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jTeU7zC1VnM-WrPN.png" /></figure><h4>A real-life example</h4><ul><li>On May 28, 2023 Baby Doge lost $137k in a <a href="https://substack.com/redirect/e66978d5-8c91-47a9-9c4a-977394ad9713?j=eyJ1IjoiMW44cHIifQ.PH66MPldlvxG4kPdBKNQh1ysrK4mQjR32SvDEvH9rrc"><strong>price oracle manipulation</strong></a> exploit.</li><li><a href="https://twitter.com/ZunamiProtocol/"><strong>Zunami Protocol</strong></a> lost $2.1M as the project’s Ether- and USD-pegged stablecoins came under a price manipulation attack.</li></ul><h4>Mitigation</h4><ul><li>Properly implement Decentralized Oracles e.g Chainlink: DeFi platforms and smart contracts can use multiple independent oracles to aggregate price data. This reduces the risk of manipulation because an attacker would need to manipulate multiple oracles simultaneously, making it more challenging.</li></ul><h4>Reference</h4><ul><li><a href="https://medium.com/beaver-smartcontract-security/defi-security-lecture-7-price-oracle-manipulation-d716cdeaaf77">https://medium.com/immunefi/enzyme-finance-missing-privilege-check-bugfix-review-ddb5e87b8058</a></li><li><a href="https://rekt.news/zunami-protocol-rekt/">https://rekt.news/zunami-protocol-rekt/</a></li><li><a href="https://github.com/calvwang9/oracle-manipulation">https://github.com/calvwang9/oracle-manipulation</a></li></ul><h3>#9 Governance attacks</h3><p>A governance attack, also known as a governance manipulation attack, is a type of attack that occurs within decentralized autonomous organizations (DAOs) and DeFi platforms where malicious actors attempt to manipulate or control the decision-making processes of the platform’s governance system for their own benefit. Governance in these contexts typically involves voting on proposals to make changes or decisions about the platform’s rules, parameters, and operations.<br>Governance attacks can take various forms, including allowing proposals to be executed without quorum, allowing execution of proposals without any voting step, or directly manipulating the votes of other participants. These attacks can compromise the decentralized nature of the protocol and lead to centralization of power, or result in financial benefits for the attackers. Governance attacks are particularly relevant in DAOs, where decision-making authority is distributed among token holders.</p><h4>Code Example:</h4><pre>pragma solidity ^0.4.22;<br>pragma solidity ^0.8.13;<br> <br>import &quot;@oz/token/ERC20/ERC20.sol&quot;;<br>import &quot;@oz/token/ERC20/utils/SafeERC20.sol&quot;;<br>import &quot;@uniswap-v2-periphery/interfaces/IUniswapV2Router02.sol&quot;;<br>import &quot;forge-std/console.sol&quot;;<br> <br>contract Attacker {<br>   using SafeERC20 for ERC20;<br> <br>   ERC20 usdc = ERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);<br>   ERC20 bean = ERC20(0xDC59ac4FeFa32293A95889Dc396682858d52e5Db);<br> <br>   function proposeBip() external payable {<br>       swapEthForBean();<br>       console.log(<br>           &quot;After ETH -&gt; BEAN swap, Bean balance of attacker: %s&quot;,<br>           bean.balanceOf(address(this)) / 1e6<br>       );<br> <br>       depositAllBean();<br>       console.log(<br>           &quot;After BEAN deposit to beanStalk, Bean balance of attacker: %s&quot;,<br>           bean.balanceOf(address(this)) / 1e6<br>       );<br> <br>       submitProposal();<br>   }<br> <br>   function attack() external {<br>       approveEverything();<br> <br>       flashloanAave();<br> <br>       console.log(<br>           &quot;Final profit, usdc balance of attacker: %s&quot;,<br>           usdc.balanceOf(address(this)) / (10**usdc.decimals())<br>       );<br>      <br>       usdc.transfer(msg.sender, usdc.balanceOf(address(this)));<br>   }<br>}</pre><h4>A real-life example</h4><ul><li>On April 17, 2022, Beanstalk suffered a $182 million governance attack where the attacker exploited the project’s protocol governance mechanism and drain funds from the pools. <a href="https://de.fi/blog/beanstalk-losses-181-million-the-governance-attack-using-a-flash-loan-7459174dfa8e">Source</a></li></ul><h4>Mitigation</h4><ul><li>Establish a robust, well-defined, and transparent governance framework that outlines the decision-making processes, voting mechanisms, and rules for participation. Implement secure and tamper-resistant voting systems that ensure the integrity of votes.</li></ul><h4>Reference</h4><ul><li><a href="https://medium.com/@emanherawy/flash-loans-the-double-edged-sword-of-defi-5f9b46c45d6e">https://medium.com/@emanherawy/flash-loans-the-double-edged-sword-of-defi-5f9b46c45d6e</a></li><li><a href="https://de.fi/blog/beanstalk-losses-181-million-the-governance-attack-using-a-flash-loan-7459174dfa8e">https://de.fi/blog/beanstalk-losses-181-million-the-governance-attack-using-a-flash-loan-7459174dfa8e</a></li></ul><h3>#10 Faulty Calculation</h3><h4>Description</h4><p>Errors or inaccuracies in the mathematical or computational logic within smart contracts or DeFi protocols. These errors can lead to unintended consequences, financial losses, or vulnerabilities that can be exploited by malicious actors.</p><h4>Code Example:</h4><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract LendingPlatform {<br>    mapping(address =&gt; uint256) public userBalances;<br>    uint256 public totalLendingPool;<br><br>    function deposit() public payable {<br>        userBalances[msg.sender] += msg.value;<br>        totalLendingPool += msg.value;<br>    }<br><br>    function withdraw(uint256 amount) public {<br>        require(userBalances[msg.sender] &gt;= amount, &quot;Insufficient balance&quot;);<br>        <br>        // Faulty calculation: Incorrectly reducing the user&#39;s balance without updating the total lending pool<br>        userBalances[msg.sender] -= amount;<br>        <br>        // This should update the total lending pool, but it&#39;s omitted here.<br>        <br>        payable(msg.sender).transfer(amount);<br>    }<br>}</pre><h4>A real-life example</h4><ul><li>On May 1, 2023, Level Finance was exploited due to a business logic issue and incorrect calculation, resulting in a total loss of <strong>$1.1M, </strong><a href="https://blog.solidityscan.com/level-finance-hack-analysis-16fda3996ecb"><strong>link</strong></a></li></ul><h4>Mitigation</h4><ul><li>security Audits: Conduct thorough security audits of smart contracts and DeFi protocols by reputable auditing firms. Auditors can identify coding errors and logic flaws.</li><li>Code Review: Review the smart contract code carefully to identify potential calculation errors. Enlist experienced developers or auditors for this task.</li><li>Test Environments: Use testnet environments to thoroughly test smart contracts and DeFi protocols before deploying them on the mainnet. Test for various scenarios, including edge cases.</li><li>Fuzzing testing : use fuzzing to generate all the possible values</li></ul><p>These 10 vulnerabilities serve as lessons, highlighting the importance of robust security practices in blockchain development. It’s crucial to understand that these vulnerabilities can not only exist in isolation but are often combined in intricate ways to exploit smart contracts. By comprehending these weaknesses and the potential for their interplay, developers and auditors can better fortify blockchain systems, fostering a more secure and resilient landscape for the future of decentralized technology.</p><h4>Reference</h4><ul><li><a href="https://blog.solidityscan.com/level-finance-hack-analysis-16fda3996ecb">https://blog.solidityscan.com/level-finance-hack-analysis-16fda3996ecb</a></li><li><a href="https://github.com/yearn/yearn-security/blob/master/disclosures/2022-09-06.md">https://github.com/yearn/yearn-security/blob/master/disclosures/2022-09-06.md</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38562685fca2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/10-smart-contract-vulnerabilities-with-code-examples-38562685fca2">10 smart contract vulnerabilities with code examples</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Smart Contract Vulnerabilities: A Case Study on the Euler Finance Hack]]></title>
            <link>https://medium.com/coinmonks/understanding-smart-contract-vulnerabilities-a-case-study-on-the-euler-finance-hack-f39ac43e50d8?source=rss-65e6393574a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f39ac43e50d8</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[smartcontract-audit]]></category>
            <category><![CDATA[flash-loan]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Eman Herawy]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 16:11:32 GMT</pubDate>
            <atom:updated>2023-10-10T17:32:09.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOOgwhyZ7dCqxAaTB3MlqQ.png" /></figure><h3>Disclaimer</h3><p>This article, “Understanding Smart Contract Vulnerabilities: A Case Study on the Euler Finance Hack” was prepared as part of <a href="https://www.ekolance.io/smartcontractauditor">Ekolance’s smart contract audit training</a>. It is intended for educational purposes only.</p><h3>Important note:</h3><p>4/6/23: Hacker returns stolen funds, marking one of the largest DeFi recoveries.</p><h3>Introduction</h3><p>On March 13, 2023, Euler Finance, fell victim to one of the largest DeFi attacks in 2023. Euler Finance is a permissionless lending/ borrowing DeFi protocol operating on the Ethereum network. Euler Finance is over collateralized lending platform that support any erc20 token. The attacker could steal $197M in ETH, WBTC, USDC and DAI through flashloan and price manipulation.</p><p>This attack is ranked as the 6th largest attack in crypto based on the r<a href="https://rekt.news/leaderboard/">ekt.new</a> leaderboard, and Euler’s TVL dropped from $264M to just $10M. In addition to Euler itself (whose token, EUL, fell over 50%), the fallout affected <a href="https://twitter.com/0xNikitaMashkov/status/1635261107068878852">many projects integrated with Euler</a>.</p><h3>Timeline of Events</h3><p>In 11:59 AM (GMT+3) · Mar 13, 2023, PeckShield raised an <a href="https://twitter.com//status/1635203838939652097">alarm</a> about suspicious activity happening in Euler Finance protocol. After one hour, Euler Labs <a href="https://twitter.com/eulerfinance/status/1635218198042918918">acknowledged</a> the exploit, stating they were “working with security professionals and law enforcement”.</p><h3>Intro to Euler Finance Protocol</h3><p>In order to better understand the incident, we need to understand some important information about the protocol and how it works.</p><blockquote>“Euler is a non-custodial permissionless lending protocol on Ethereum that helps users to earn interest on their crypto assets or hedge against volatile markets without the need for a trusted third-party” Euler doc.</blockquote><p>Euler Protocol issues <strong>eToken</strong> and <strong>dToken</strong> whenever a user borrows /lends a token. When Euler protocol users perform lending or borrowing operations , they transact with two types of tokens: <strong>eTokens</strong> (which represent <strong>collateral</strong>) and <strong>dTokens</strong> (which represent <strong>debt</strong>).</p><p>Euler issues <strong>eTokens</strong> based on the types of funds deposited by users; dTokens automatically trigger on-chain liquidation when the platform <strong>holds more dTokens than eTokens</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6cFJ6m0rV9PTWziJ" /></figure><p>The Euler protocol checks a user’s position on the platform “<strong>Health Score</strong> ‘’ by comparing the value of the user’s <strong>eTokens</strong> (collateral) to their <strong>dTokens</strong> (debt). If a user has a higher value of collateral compared to the debt, then the user is in a healthy position; otherwise, the user’s position may become subject to liquidation. This operation is called “<strong>liquidation checks</strong>’ ‘ and is very important for ensuring that the user can repay their debt and maintain the security of their assets.</p><p>When a position becomes under-collateralized, the platform can liquidate the user’s collateral to recover the debt. This process usually involves selling the collateral at a discount to incentivize liquidators to participate and facilitate the recovery of the debt.</p><h3>Root Cause Analysis</h3><p>In July 2022, Euler Finance team introduced <a href="https://forum.euler.finance/t/eip-14-contract-upgrades/305"><strong>eIP14</strong></a>, where the vulnerable code was introduced . The introduced changes were audited by Sherlock . This update has many changes but what we care about is the DonateToReserve function that enables depositing of <strong>eToken </strong>which basically burns <strong>eToken</strong> only , no <strong>dToken</strong> burn, leading to an incorrect conversion of borrowed assets to collateralized assets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B8oTrqEE7Mbi0ntd" /></figure><p>The attacker could perform his attack by leveraging the below features</p><ol><li>Flash Loan</li><li>liquidity issue in the DonateToReserve function</li><li>liquidation discount of Euler Finance, <a href="https://www.euler.finance/blog/eulers-innovative-liquidation-engine">check</a></li></ol><h3>Execution Flow ( reference ) :</h3><p>1- Attacker gets 30 M DAI flash loan from Aave</p><p>2- Deploy <a href="https://etherscan.io/address/0x583c21631c48d442b5c0e605d624f54a0b366c72">Violator</a> contract ( which would incur bad debt)</p><blockquote>- Transfer the full 30m DAI loan balance to the violator</blockquote><blockquote>- Deposit 20m DAI to the DAI EToken of Euler Finance, receiving ~19,56m eDAI tokens</blockquote><blockquote>- Create a 200m artificial eDAI leverage, minting ~195,68m eDAI and 200m dDAI to the violator</blockquote><blockquote>- Repay 10m DAI on the violator’s position, causing their dDAI balance to go to 190m</blockquote><blockquote>- Create another 200m artificial eDAI leverage, minting ~195,68m eDAI and 200m dDAI to the violator</blockquote><blockquote>- Donate 100m eDAI to the reserve of the EToken</blockquote><p>At this point, we have the following violator state:</p><ul><li>eDAI: ~310,93m</li><li>dDAI: 390m</li></ul><p>The liquidator will exploit this due to the calculations within the Liquidation module.</p><p>3- Deploy <a href="https://etherscan.io/address/0xa0b3ee897f233f385e5d61086c32685257d4f12b">liquidator</a> Contract:</p><blockquote>- Liquidate the position, acquiring ~310,93m eDAI tokens and ~259,31m dDAI tokens</blockquote><blockquote>- Withdraw the full reserve of DAI tokens by burning the corresponding eDAI tokens on exchange rate of 0,97 eDAI per DAI</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GGVehjSa4knFFQzG" /></figure><p>4- Repay the flash loan</p><p>5- Swap USDC and WBTC for DAI and ETH</p><h3>Response and Mitigation</h3><ul><li>Euler <a href="https://etherscan.io/tx/0x539c6fff0fce70e02dddd80a5534acf3df57deafbdc40f41abb20aa8f94a6d0d">reached out </a>to the attacker’s address via tx input data:</li></ul><blockquote>We understand that you are responsible for this morning’s attack on the Euler platform. We are writing to see whether you would be open to speaking with us about any potential next steps.</blockquote><ul><li>Sherlock has taken responsibility for missing the vulnerability in their review of EIP-14 last year, and will pay a claim of $4.5M to Euler.</li><li>The hacker returned the stolen funds and apologized through a series of encrypted messages.</li></ul><h3>Lessons Learned</h3><ul><li>Testing for different simulated scenarios is crucial.</li><li>Pushing updates to smart contracts is so dangerous and should be carefully tested and reviewed. Any tiny modification might open many back doors for dangerous vulnerabilities.</li></ul><h3>Resources:</h3><ul><li><a href="https://rekt.news/euler-rekt/">https://rekt.news/euler-rekt/</a></li><li><a href="https://medium.com/@omniscia.io/euler-finance-incident-post-mortem-1ce077c28454">https://medium.com/@omniscia.io/euler-finance-incident-post-mortem-1ce077c28454</a></li><li><a href="https://twitter.com/FrankResearcher/status/1635241492079067144">https://twitter.com/FrankResearcher/status/1635241492079067144</a></li><li><a href="https://blockapex.io/hack-analysis/euler-finance-hack-analysis/#:~:text=In%20the%20Euler%20Finance%20hack%2C%20the%20attacker%20exploited,loan%20%28the%20flash%20loan%29%20to%20the%20third%20party">https://blockapex.io/hack-analysis/euler-finance-hack-analysis/#:~:text=In%20the%20Euler%20Finance%20hack%2C%20the%20attacker%20exploited,loan%20%28the%20flash%20loan%29%20to%20the%20third%20party</a>.</li><li><a href="https://www.chainalysis.com/blog/euler-finance-flash-loan-attack/">https://www.chainalysis.com/blog/euler-finance-flash-loan-attack/</a></li><li><a href="https://www.euler.finance/blog/eulers-innovative-liquidation-engine">https://www.euler.finance/blog/eulers-innovative-liquidation-engine</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f39ac43e50d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/understanding-smart-contract-vulnerabilities-a-case-study-on-the-euler-finance-hack-f39ac43e50d8">Understanding Smart Contract Vulnerabilities: A Case Study on the Euler Finance Hack</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut in Arabic- Level 6 Delegation]]></title>
            <link>https://medium.com/@emanherawy/%D8%B3%D9%84%D8%B3%D9%84%D8%A9-%D8%AA%D8%B4%D8%B1%D8%AD-%D8%AD%D9%84%D9%88%D9%84-%D8%A7%D9%8A%D8%AB%D8%B1%D9%86%D8%A7%D9%88%D8%AA-622f240f30f1?source=rss-65e6393574a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/622f240f30f1</guid>
            <category><![CDATA[secuirty]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethernaut]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Eman Herawy]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 15:40:28 GMT</pubDate>
            <atom:updated>2023-09-03T15:44:21.987Z</atom:updated>
            <content:encoded><![CDATA[<p>سلسلة تشرح حلول ايثرناوت</p><p>بسم الله الرحمن الرحيم ،</p><p>نبدا فى المستوى السادس فى لعبة ايثرناوت</p><p>وكالعادة نبدا بالمطلوب</p><pre>The goal of this level is for you to claim ownership of the instance you are given.<br>  <br><br>Things that might help<br><br>Look into Solidity&#39;s documentation on the delegatecall low level function, how it works, how it can be used to delegate operations to on-chain libraries, and what implications it has on execution scope.<br>Fallback methods<br>Method id</pre><blockquote>نبص على الكود مع بعض</blockquote><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract Delegate {<br><br>  address public owner;<br><br>  constructor(address _owner) {<br>    owner = _owner;<br>  }<br><br>  function pwn() public {<br>    owner = msg.sender;<br>  }<br>}<br><br>contract Delegation {<br><br>  address public owner;<br>  Delegate delegate;<br><br>  constructor(address _delegateAddress) {<br>    delegate = Delegate(_delegateAddress);<br>    owner = msg.sender;<br>  }<br><br>  fallback() external {<br>    (bool result,) = address(delegate).delegatecall(msg.data);<br>    if (result) {<br>      this;<br>    }<br>  }<br>}</pre><p>هو عاوزك تبقى مالك العقد ،</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*jaYAT_C3SuF4qNUE.jpeg" /></figure><p>اه والله بس ادالك هنت ازاى تعمل ده ، من خلال</p><p>ال delegatecall <br>دايما كتير ناس بتتلخبط فيها بس علشان ابسطها لك تعالى نضرب مثال</p><p>تعالى نتخيل ان ليك جيران عندهم حفلة ما ، فانت قولت قشطه اروح اكلمهم علشان اهيص معاهم ، وااكل حلويات وروق على نفسي . <br>زى الباشا رحت خبطت عليهم ، فلقيتهم كلهم جم عندك ، فى الشقه .. والعيال بتننط ع الكراسي ، وفتحوا التالجه وطلبوا دليفرى على حسابك ، عملوا اللى نفسهم فيه بس على حسابك انت ، وشقتك انت اللى اتبهدلت</p><p>ده بالظبط اللى بيحصل لما عقد يكلم عقد من خلال delegatecall</p><p>العقد بينفذ اى حاجه موجوده ف العقد التانى اللى بيكلمه بس ف الحقيقه التغيير بيبتم ف العقد اللى بعت ، مش اللى اتبعت له</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-hz0JoCW2c_0OWUr.jpg" /></figure><p>طبعا الخاصيه دى مفيده جدا جداا في مواطن معينه زى لما احب استخدم بروكسى كونتراكت واخلى العقد بتاعى قابل للتحديث، بس فى نفس الوقت خطيرة جداااااااااااا ﻻنك بتدى سلطه كبيرة جدا لكود ما انه يشقلب لك الدنيا ، وكانك عزمت حراميه فى بيتك ومنتظر منهم يشوفوا الفلوس فى اﻻرض يحطوها فى صندوق اﻻمانات</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/0*RW7u19oItsb4M87n.jpg" /></figure><p>بعد م فسرنا فكرة ال delegatecall <br>تفتكروا ازاى نقدر ناخد ملكية العقد ؟ <br>لوبصين هنلاقى العقد</p><pre>contract Delegate {<br><br>  address public owner;<br><br>  constructor(address _owner) {<br>    owner = _owner;<br>  }<br>// اى حد بينادى ع الفنكشن دى بيبقى المالك للعقد<br>  function pwn() public {<br>    owner = msg.sender;<br>  }<br>}</pre><p>ويبقى الحل ايه؟</p><pre>contract Delegation {<br><br>  address public owner;<br>  Delegate delegate;<br><br>  constructor(address _delegateAddress) {<br>    delegate = Delegate(_delegateAddress);<br>    owner = msg.sender;<br>  }<br>/* pwn نكلم الفنكشن <br> بس من خلال الفنكشن دى*/<br>  fallback() external {<br>    (bool result,) = address(delegate).delegatecall(msg.data);<br>    if (result) {<br>      this;<br>    }<br>  }<br>}</pre><p>طب هتبعت الفنكشن دى ازاى؟ <br>، ببساطه لو هتعملها من الفرونت اند ، انت بس محتاج تجيب السجنتشر بتاعها، فيه طرق كتير تانيه بس دى كمثال</p><pre>web3.eth.abi.encodeFunctionSignature(&quot;pwn()&quot;)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*Llo0638kknmZ1Zv47DEymw.png" /></figure><p>ونسلم الحل</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*oFusIi7bcx7wqUqTRUeOlg.png" /></figure><p>وبكده انتهى المقال ، ونلتقى فى التحدى القادم</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=622f240f30f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[سلسلة تشرح حلول ايثرناوت]]></title>
            <link>https://medium.com/@emanherawy/%D8%B3%D9%84%D8%B3%D9%84%D8%A9-%D8%AA%D8%B4%D8%B1%D8%AD-%D8%AD%D9%84%D9%88%D9%84-%D8%A7%D9%8A%D8%AB%D8%B1%D9%86%D8%A7%D9%88%D8%AA-a2f865f85e2f?source=rss-65e6393574a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2f865f85e2f</guid>
            <category><![CDATA[arabic]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[audit]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[Eman Herawy]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 10:16:21 GMT</pubDate>
            <atom:updated>2023-09-03T15:45:56.039Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/@emanherawy/ethernaut-in-arabic-level-4-telephone-17a375455971">Ethernaut in Arabic- Level 5 </a>Token</h3><p>سلسلة تشرح حلول ايثرناوت</p><p>بسم الله الرحمن الرحيم ،</p><p>بقالى كتير مكتبتش ، للاسف . المهم</p><p>نبدا فى المستوى الخامس فى لعبة ايثرناوت</p><p>خلونا نبدا بالمطلوب</p><pre>The goal of this level is for you to hack the basic token contract below.<br><br>You are given 20 tokens to start with and you will beat the level if you somehow manage to get your hands on any additional tokens. Preferably a very large amount of tokens.<br><br>  Things that might help:<br><br>What is an odometer?</pre><blockquote>لو بصينا على الكود مع بعض</blockquote><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.6.0;<br><br>contract Token {<br><br>  mapping(address =&gt; uint) balances;<br>  uint public totalSupply;<br><br>  constructor(uint _initialSupply) public {<br>    balances[msg.sender] = totalSupply = _initialSupply;<br>  }<br><br>  function transfer(address _to, uint _value) public returns (bool) {<br>    require(balances[msg.sender] - _value &gt;= 0);<br>    balances[msg.sender] -= _value;<br>    balances[_to] += _value;<br>    return true;<br>  }<br><br>  function balanceOf(address _owner) public view returns (uint balance) {<br>    return balances[_owner];<br>  }<br>}</pre><p>للوهلة اﻻولى ربما تقول الكود آمن والاختراق ده غير قابل للتنفيذ ،</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/0*yVAPlXYgGJDPsDEe.jpg" /></figure><p>بس هو عاوز يعلمك حاجمه مهمه قوى فى سوليدتى <br>overflow and underflow attack</p><p>ده <a href="https://blog.sigmaprime.io/solidity-security.html#ou-vuln">لينك</a> بيشرحها بشكل لطيف للمهتمين</p><p>فكرتها ببساطه ان الكومبيلر قبل اصدار 0.8 ، مكنش بيعمل فحص لحجم الداتا ، بمعنى انك لو اخترت لمتغير ما داتا تياب ع سبيل المثال unit8 <br>ده يعنى ان المتغير ده مبيقدرش يحفظ اراقام اﻻ فى نطاق ( 0 ل 2**8–1)</p><p>ولو بعت له 2**8 ، اللى بيحصل ان الترانسزاكشن بيتم عادى والرقم بيعد من اﻻول ، يعنى الرقم بيرجع ف المثال اللى فوق 0</p><p>لذلك فى اﻻصدارات القديمه كان مهم جدا نشتغل بمكتبات بتظبط العمليات الرياضيه بشكل آمن زى <br>OZ afeMath</p><p>ملحوظه : ابتداء من اصدار 0.8 ، معدناش بنحتاج نستخدم المكتبات دى ، ﻻن ال <br> EVM<br>بقت بتشيك بشكل افتراضى ، ولو الرقم زيادة او اقل ، الترانساكشن بيفشل</p><p>بعد ما فسرنا فكرة التحدى ، يلا بينا نحل <br>لما جيت شوفت الاكونت بتاعى معاه قد ايه توكن لقيت معاه 21 <br>ولما بصيت على data type <br>لقيتها بتاخد من 0لحد 2**256–1 لان</p><p>uint == uint256</p><blockquote>int / uint: Signed and unsigned integers of various sizes. Keywords uint8 to uint256 in steps of 8 (unsigned of 8 up to 256 bits) and int8 to int256. uint and int are aliases for uint256 and int256, respectively.</blockquote><blockquote>حسب الدوكيمنتاشن الخاصه سوليديتى<br>ولو ان اللى بنحدد فيها وبنقول 256 بتوفر جاز اكتر ، بس ما علينا</blockquote><p>فانا كنت اللى محتاجاه انى انقص من حسابي لحد ما يبقى -1 ، علشان يلف ويرجع ب 2**255</p><p>وقد كان</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*CMj9gNjy11NJUY4gqETmZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*b_7DcQkzSkh8MmSznHsEeQ.png" /></figure><p>وسلمنا الحل</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*WhByhIRuiE6Bs9GSvvszRw.png" /></figure><p>وبكده انتهى المقال ، ونلتقى فى التحدى القادم</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2f865f85e2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flash Loans: The Double-Edged Sword of DeFi]]></title>
            <link>https://medium.com/@emanherawy/flash-loans-the-double-edged-sword-of-defi-5f9b46c45d6e?source=rss-65e6393574a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f9b46c45d6e</guid>
            <category><![CDATA[flash-loan]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Eman Herawy]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 11:01:22 GMT</pubDate>
            <atom:updated>2023-08-14T11:01:22.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3axbbFwTQ9318QrsETbRA.png" /></figure><h3>Introduction:</h3><p>In the fast-paced world of decentralized finance (DeFi), financial innovation meets blockchain technology, promising groundbreaking opportunities for open, permissionless, and borderless financial services. As a passionate blockchain developer and smart contract auditor, my journey into the DeFi domain has been fueled by the desire to understand its complexities and contribute to strengthening its security. My commitment to mastering DeFi has led me to embark on a transformative learning experience in the esteemed <a href="https://web3-talents.io/defi-talents">DeFi Talent Program</a>. In this program, I acquire the expertise to explore one of the most powerful financial tools in the DeFi space: flash loans. This article delves into the captivating world of flash loans, dissecting their real-world applications, their pivotal role in DeFi’s expansion, and the security vulnerabilities they introduce.</p><h4>To better understand flash loans, let’s start by explaining what a loan is in general and the difference between traditional centralized loans and decentralized loans.</h4><p><strong>Loans</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*aAwHsDKeOf3vrvTD.png" /><figcaption><a href="https://medium.com/beaver-smartcontract-security/defi-security-lecture-2-flash-loan-attacks-4aee2d3f07ca">Source</a></figcaption></figure><p>A loan refers to a sum of money borrowed by one party (the borrower) from another (the lender), with the agreement that the borrower will repay the borrowed amount along with applicable interest or fees within a specified time frame. Loans are a common financial arrangement used by individuals, businesses, and governments to access funds for various purposes, such as acquiring assets, funding projects, or managing cash flow.</p><p><strong>Traditional centralized Loans:</strong></p><p>In the realm of traditional finance, this process ( mentioned above) is overseen by trusted centralized financial entities, often banks. Collateral for traditional loans may encompass tangible assets (real estate, vehicles) or financial assets (stocks, bonds). Typically, these loans involve a comprehensive credit check and assessment of the borrower’s creditworthiness, income, and financial stability.</p><p><strong>Crypto Loans:</strong></p><p>A cryptocurrency-backed loan is a financial arrangement where an individual or business utilizes their cryptocurrency holdings as collateral, which is locked within a smart contract, to secure a loan. This approach enables crypto holders to access liquidity without having to sell their assets. This way, they can benefit from potential price appreciation while still obtaining funds for various purposes. Such loans are typically facilitated through crypto lending platforms. While these platforms usually don’t require a traditional credit check, some may carry out limited KYC (Know Your Customer) processes to adhere to regulatory compliance.</p><p><strong>With this foundation, let’s get to Flash loans :</strong></p><p>Within the dynamic landscape of decentralized finance (DeFi), flash loans in 2020, also known as atomic loans, have emerged as a groundbreaking concept. These loans are revolutionizing liquidity access and utilization within blockchain ecosystems. Unlike traditional DeFi loans, flash loans offer instantaneous and uncollateralized borrowing capabilities. This empowers users to access substantial funds within a single transaction, presenting new opportunities for sophisticated financial operations such as arbitrage, yield farming, and liquidity provision — all executed at remarkable speeds.</p><p>In simple terms, a blockchain transaction to a smart contract can involve multiple internal transactions if the main transaction calls a function that triggers other transactions. With this feature, a user can send a transaction to a lending platform and secure a zero-collateral loan (flash loan). They can then utilize this borrowed capital for arbitrage opportunities in various DeFi protocols and, ultimately, repay the loan with interest to make a profit. If the user fails to repay the loan with interest, the entire transaction is invalidated. In this scenario, all stakeholders benefit: Lenders receive passive income, borrowers gain from zero-collateral loans, and lending protocols promote liquidity, innovation, and community engagement.</p><p><strong>Top Flash Loan Providers:</strong></p><p>Here are some of the leading flash loan providers in the DeFi ecosystem:</p><h3><strong>Aave</strong>:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*alauwKWdNbhVpHT9.jpg" /></figure><p>Aave, a prominent DeFi lending platform, offers flash loans as part of its comprehensive suite of services. Aave was the first protocol to introduce real flash loans on Ethereum in 2020. Users can borrow a wide range of tokens, and a 0.09% fee is charged for each flash loan transaction.</p><h3>dYdX:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*6UQkF2kPhtzv0cUNr8gBPA.png" /></figure><p>Operating on the Ethereum blockchain, dYdX is a DeFi borrowing and lending platform. Unlike other lending platforms, dYdX does not impose a fee for flash loans. Borrowers are only required to repay the borrowed funds along with a nominal 2 Wei fee.</p><h3><strong>Vulnerabilities in Flash Loans: Unraveling the Risks</strong></h3><p>Despite these advantages, it’s important to recognize that flash loans also come with a range of business risks that warrant careful consideration by both users and platforms. These risks possess the potential to reverberate across the stability, reputation, and overall financial well-being of DeFi platforms. Lenders, too, may find themselves facing the danger of losing their liquidity.</p><p>Regrettably, the DeFi landscape has witnessed a surge in recent instances of flash loan attacks, serving as a stark reminder of the darker side of this innovation. These attacks are characterized by their low-risk, low-cost, and high-reward nature, where malicious actors take out substantial flash loans to manipulate the market and exploit various DeFi protocols, yielding significant profits with minimal cost. Let’s delve into some of the critical vulnerabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HjrcyFLBPYDRVZQe.jpg" /></figure><h3>Common Types of Attacks: Real Examples of Notable Flash Loan Exploits</h3><p><strong>Flash Loan Liquidity Drain Attack: The “Value DeFi” Incident</strong></p><p>In November 2020, the Value DeFi protocol experienced a $6 million flash loan attack that targeted its liquidity pools. The attacker exploited vulnerabilities in the protocol’s smart contracts to manipulate token prices and drain significant funds from the pools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/0*uu8YxDq-UB3rDX4T" /></figure><p>This attack highlighted the risk of flash loans being used to manipulate prices and drain liquidity from vulnerable DeFi protocols.</p><p><strong>Flash Loan Governance Manipulation Attack: Beanstalk incident</strong></p><p>Flash loans can be leveraged to manipulate governance processes within DeFi protocols. Malicious actors may borrow significant funds through flash loans to gain a substantial amount of governance tokens, subsequently using these tokens to influence protocol decisions and control critical functionalities. On April 17, 2022, Beanstalk suffered a $182 million governance attack where the attacker exploited the project’s protocol governance mechanism and drain funds from the pools. <a href="https://de.fi/blog/beanstalk-losses-181-million-the-governance-attack-using-a-flash-loan-7459174dfa8e">Source</a></p><p><strong>Flash Loan Price Manipulation Attack: The “PancakeBunny” Incident</strong></p><p>In May 2021, the PancakeBunny protocol on the Binance Smart Chain fell victim to a flash loan attack that focused on price manipulation. The attacker used flash loans to manipulate the prices of USDT/BNB and BUNNY/BNB causing disruptions and inconsistencies in the protocol’s operations. This attack demonstrated how flash loans can be employed to exploit price discrepancies and disrupt the functionality of DeFi platforms. <a href="https://www.halborn.com/blog/post/explained-the-pancakebunny-protocol-hack-may-2021">Source</a></p><p><strong>Flash Loan Reentrancy Attack: $5.4 Million The “dForce” Incident</strong></p><p>The dForce protocol suffered a significant flash loan attack in April 2020. The attacker utilized a reentrancy attack in <strong>Vyper_contract’s</strong> ‘remove_liquidity’ and ‘get_virtual_price’ functions. This allowed The attacker to take advantage of two issues: When sending ETH to the attacker’s contract, the fallback function is triggered, which calls other methods. During the callback, the LP Token total has not been updated, resulting in an incorrect price calculation. <a href="https://medium.com/@numencyberlabs/technical-analysis-of-dforce-networks-5-4-million-attack-ea3d4ba7cad8">Source</a></p><p><strong>Flash Loan Oracle Manipulation Attack: The “Elephant Money” Incident</strong></p><p>Elephant Money, a stablecoin platform that employs the TRUNK token, was a victim of the flash loan assault, which manipulated a token price oracle, resulting in a $22.2 million loss. <a href="https://de.fi/blog/price-manipulation-attack-elephant-money-loses-22-2-million-aab84e469350">Source</a></p><p>Mitigating flash loan attacks and their associated risks within the decentralized finance (DeFi) ecosystem requires a multi-faceted approach that combines technical measures, risk management strategies, and community collaboration. Here are some important things to do:</p><p><strong>1. Strong Smart Contract Audits:</strong></p><p>Perform thorough audits of the smart contracts that enable flashloans. This involves reviewing the code to identify and address vulnerabilities, bugs, and potential attack vectors. Third-party security audits conducted by reputable firms can help identify and rectify any issues before the contracts go live.</p><p><strong>2. Testing and Simulation:</strong></p><p>Conduct extensive testing and simulation of flashloan transactions to identify any unforeseen scenarios or potential risks. Testing can help uncover bugs, ensure proper transaction sequencing, and validate the correctness of the smart contracts.</p><p><strong>3. Liquidity Monitoring:</strong></p><p>Monitor the liquidity within the platform closely, particularly during periods of high flashloan activity. A sudden drain of liquidity due to flashloans could impact the platform’s overall stability and the ability of other users to transact.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f9b46c45d6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut in Arabic- Level 4 Telephone]]></title>
            <link>https://medium.com/@emanherawy/ethernaut-in-arabic-level-4-telephone-17a375455971?source=rss-65e6393574a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/17a375455971</guid>
            <dc:creator><![CDATA[Eman Herawy]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 16:02:24 GMT</pubDate>
            <atom:updated>2023-01-11T16:02:24.618Z</atom:updated>
            <content:encoded><![CDATA[<p>سلسلة تشرح حلول ايثرناوت</p><p>بسم الله الرحمن الرحيم ،</p><p>نبدا فى المستوى الرابع فى لعبة ايثرناوت</p><p>خلونا نبدا بالمطلوب</p><pre>Claim ownership of the contract below to complete this level.<br><br>  Things that might help<br><br>See the Help page above, section &quot;Beyond the console&quot;</pre><p>عاوزك تستحوذ على ملكية العقد ، ولما نبص على الكود</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract Telephone {<br><br>  address public owner;<br><br>  constructor() {<br>    owner = msg.sender;<br>  }<br><br>  function changeOwner(address _owner) public {<br>    if (tx.origin != msg.sender) {<br>      owner = _owner;<br>    }<br>  }<br>}</pre><p>هنلاقى ان فيه فنكشن ، اى حد معدى ف الشارع يقدر نادى عليها ويستحوذ على ملكية العقد ، بس بشرط صغير</p><pre>function changeOwner(address _owner) public {<br>    if (tx.origin != msg.sender) {<br>      owner = _owner;<br>    }<br>  }</pre><p>التحدى ده بسيط جدا ، وهدفه يعرفك على نقطه مهمه جدا ، مين اللى بيكلم الفنكشن دى ، او بعبارة اكثر مهنيه</p><p>function caller</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pVoLTRn2BKEY4oIC.jpg" /></figure><p>خلينا نتفق انه نظريا وعمليا ، طالما سوليدتى بتدعم انك العقود تعمل تواصل مع عقود اخرى ، او ما يسمى بال <br>external calls</p><p>فانا اقدر ابعت لفنكشن فى عقد ، يكلم عقد تانى ، اللى بدورة يكلم عقد تالت ، وهكذا</p><p>فلو افترضنا انى عندى سلسلة من العقود، كل عقد فيه فنكشن بتنادى على فنكشن فى العقد اللى بعدها ، فانا هيكون عندى التالى فى سوليدتى</p><pre>  // ده هيكون اخر مرسل <br>        msg.sender;<br>   //  انما ده هيكون اول مرسل <br>        tx.origin;<br> </pre><p>طبعا لو انا معنديش غير</p><p>1 call <br>فده بيعنى ان</p><pre><br>        msg.sender=tx.origin;</pre><p>وبناء على ما سبق، مهم جدا ننتبه لما نبرمج العقد انه مينفعش انى لما احب استوثق من المرسل لاى سبب زى نقل ملكية او غيرها انى استخدام</p><pre>tx.origin</pre><p>ﻻن سهل جدا التلاعب بيها</p><p>طب علشان نحل التحدى ده محتاجين ايه ؟</p><p>محتاجين نعمل عقد بسيط يكلم العقد ده</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/0*PUZgGOqIoQFIhaWF.jpg" /></figure><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>interface ITelephone { <br>  function changeOwner(address _owner) external;<br>}<br><br>contract TelephoneAttack { <br>    <br>  function attack(address victim) public{<br>    ITelephone(victim).changeOwner(msg.sender);<br>  }<br>}</pre><p>ونسلم النسخه</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUs69ymEgYq19PDCqntSJg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17a375455971" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>