<?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 Jerry George on Medium]]></title>
        <description><![CDATA[Stories by Jerry George on Medium]]></description>
        <link>https://medium.com/@jerrygeorge360?source=rss-d488cfe4c1e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*o9Mz0kd8Psd0uJfG3EXSeA.jpeg</url>
            <title>Stories by Jerry George on Medium</title>
            <link>https://medium.com/@jerrygeorge360?source=rss-d488cfe4c1e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 17:28:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jerrygeorge360/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[NEAR Security Patterns: Access Control, Upgrades, and Trust]]></title>
            <link>https://medium.com/@jerrygeorge360/near-security-patterns-access-control-upgrades-and-trust-c76654aaaa6f?source=rss-d488cfe4c1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c76654aaaa6f</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[near-protocol]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Jerry George]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 16:53:44 GMT</pubDate>
            <atom:updated>2026-04-17T16:53:44.372Z</atom:updated>
            <content:encoded><![CDATA[<h4>Owner patterns, role-based access, pausable contracts, multisig, and upgrade strategies. For developers who know what happens when you get this wrong.</h4><p>The first two articles covered contract structure and state management. Both assumed a single owner and simple access control. Real contracts are more complex. Multiple roles, emergency stops, upgrade authority shared across a team or DAO. This article covers all of it.</p><p>Every pattern here has a direct Ethereum parallel. Every one diverges from it in ways that matter.</p><h3>Owner Pattern</h3><p>On Ethereum, msg.sender is a global in every function. On NEAR, you call near.predecessorAccountId() to get the same thing. And unlike Solidity, there is no modifier syntax. You write the check as a plain helper method and call it at the top of any protected function.</p><pre>import { NearBindgen, view, call, near, assert, initialize } from &quot;near-sdk-js&quot;;<br>@NearBindgen({ requireInit: true })<br>class Contract {<br>  @initialize({})<br>  init({ owner_id }) {<br>    this.owner_id = owner_id;<br>  }<br>  assertOwner() {<br>    assert(near.predecessorAccountId() === this.owner_id, &quot;Owner only&quot;);<br>  }<br>  @call({})<br>  transfer_ownership({ new_owner }) {<br>    this.assertOwner();<br>    this.owner_id = new_owner;<br>  }<br>  @view({})<br>  get_owner() {<br>    return this.owner_id;<br>  }<br>}</pre><p>assertOwner() is just a method. It runs before whatever logic follows it. Simple and explicit.</p><p>There is one thing Ethereum developers often miss here. Ownership transfer on NEAR is <strong>permanent and immediate</strong>. One typo in the address and you are locked out with no recovery path. For contracts that hold real value, add a two-step transfer:</p><pre>@call({})<br>propose_ownership({ new_owner }) {<br>  this.assertOwner();<br>  this.pending_owner_id = new_owner;<br>}<br>@call({})<br>accept_ownership() {<br>  assert(<br>    near.predecessorAccountId() === this.pending_owner_id,<br>    &quot;Not pending owner&quot;<br>  );<br>  this.owner_id         = this.pending_owner_id;<br>  this.pending_owner_id = &quot;&quot;;<br>}</pre><p>The new owner must actively accept before anything changes. A typo in propose_ownership costs nothing because ownership only transfers on accept_ownership. This is a small amount of extra code for a meaningful safety guarantee.</p><h3>Role-Based Access</h3><p>A single owner is too rigid for most production systems. A DeFi protocol needs an operator that can pause, an admin that can upgrade, and a treasurer that can withdraw. None of them should be the same key.</p><p>OpenZeppelin’s AccessControl handles this on Ethereum. On NEAR, you build it from a LookupMap:</p><pre>import { NearBindgen, view, call, near, assert, initialize, LookupMap } from &quot;near-sdk-js&quot;;<br>@NearBindgen({ requireInit: true })<br>class Contract {<br>  @initialize({})<br>  init({ owner_id }) {<br>    this.owner_id = owner_id;<br>    this.roles    = new LookupMap(&quot;roles&quot;);<br>    this.roles.set(owner_id, &quot;admin&quot;);<br>  }<br>  assertOwner() {<br>    assert(near.predecessorAccountId() === this.owner_id, &quot;Owner only&quot;);<br>  }<br>  assertRole(role) {<br>    const caller      = near.predecessorAccountId();<br>    const caller_role = this.roles.get(caller);<br>    assert(<br>      caller_role === role || caller === this.owner_id,<br>      `Requires role: ${role}`<br>    );<br>  }<br>  @call({})<br>  grant_role({ account_id, role }) {<br>    this.assertOwner();<br>    this.roles.set(account_id, role);<br>  }<br>  @call({})<br>  revoke_role({ account_id }) {<br>    this.assertOwner();<br>    this.roles.remove(account_id);<br>  }<br>  @view({})<br>  get_role({ account_id }) {<br>    return this.roles.get(account_id) ?? &quot;none&quot;;<br>  }<br>  @call({})<br>  operator_action() {<br>    this.assertRole(&quot;operator&quot;);<br>    // protected logic<br>  }<br>  @call({})<br>  withdraw({ amount }) {<br>    this.assertRole(&quot;treasurer&quot;);<br>    // withdrawal logic<br>  }<br>}</pre><p>LookupMap gives O(1) role lookup without loading the entire roles map on every call. Roles are strings, so the permission model is as flexible as you need it to be.</p><h3>Pausable Contract</h3><p>Every serious protocol needs an emergency stop. On Ethereum you implement it with a boolean flag and a modifier. On NEAR the mechanics are identical, just written slightly differently.</p><pre>import { NearBindgen, view, call, near, assert, initialize } from &quot;near-sdk-js&quot;;<br>@NearBindgen({ requireInit: true })<br>class Contract {<br>  @initialize({})<br>  init({ owner_id }) {<br>    this.owner_id = owner_id;<br>    this.paused   = false;<br>  }<br>  assertOwner() {<br>    assert(near.predecessorAccountId() === this.owner_id, &quot;Owner only&quot;);<br>  }<br>  assertNotPaused() {<br>    assert(!this.paused, &quot;Contract is paused&quot;);<br>  }<br>  @call({})<br>  pause() {<br>    this.assertOwner();<br>    this.paused = true;<br>    near.log(`EVENT_JSON:${JSON.stringify({<br>      standard: &quot;nep297&quot;, version: &quot;1.0.0&quot;,<br>      event: &quot;contract_paused&quot;,<br>      data: [{ paused_by: near.predecessorAccountId() }]<br>    })}`);<br>  }<br>  @call({})<br>  unpause() {<br>    this.assertOwner();<br>    this.paused = false;<br>    near.log(`EVENT_JSON:${JSON.stringify({<br>      standard: &quot;nep297&quot;, version: &quot;1.0.0&quot;,<br>      event: &quot;contract_unpaused&quot;,<br>      data: [{ unpaused_by: near.predecessorAccountId() }]<br>    })}`);<br>  }<br>  @call({})<br>  sensitive_operation() {<br>    this.assertNotPaused();<br>    this.assertOwner();<br>    // protected logic<br>  }<br>  @view({})<br>  is_paused() {<br>    return this.paused;<br>  }<br>}</pre><p>Two things worth being deliberate about here. First, emit events when pausing and unpausing. Your users, your monitoring systems, and any protocol built on top of yours needs to know when this happens. Second, never put assertNotPaused on unpause itself. A paused contract that cannot call unpause is bricked permanently with no recovery.</p><h3>Multi-Signature</h3><p>On Ethereum, most protocols use a Gnosis Safe as the owner. The Safe is an external contract that requires M-of-N signatures before executing anything. On NEAR, the same logic lives inside the contract itself.</p><pre>import { NearBindgen, view, call, near, assert, initialize, LookupMap } from &quot;near-sdk-js&quot;;<br>@NearBindgen({ requireInit: true })<br>class Contract {<br>  @initialize({})<br>  init({ signers, required }) {<br>    this.signers        = new LookupMap(&quot;s&quot;);<br>    this.proposals      = new LookupMap(&quot;p&quot;);<br>    this.required_sigs  = required;<br>    this.signer_count   = 0;<br>    this.proposal_count = 0;<br>    for (const signer of signers) {<br>      this.signers.set(signer, true);<br>      this.signer_count += 1;<br>    }<br>    assert(<br>      required &lt;= this.signer_count,<br>      &quot;Required sigs cannot exceed signer count&quot;<br>    );<br>  }<br>  assertSigner() {<br>    assert(<br>      this.signers.get(near.predecessorAccountId()) === true,<br>      &quot;Not a signer&quot;<br>    );<br>  }<br>  @call({})<br>  propose({ action, params }) {<br>    this.assertSigner();<br>    const proposal_id = this.proposal_count;<br>    this.proposals.set(proposal_id.toString(), {<br>      action,<br>      params,<br>      approvals: [near.predecessorAccountId()],<br>      executed:  false,<br>    });<br>    this.proposal_count += 1;<br>    near.log(`EVENT_JSON:${JSON.stringify({<br>      standard: &quot;nep297&quot;, version: &quot;1.0.0&quot;,<br>      event: &quot;proposal_created&quot;,<br>      data: [{ proposal_id, action, proposed_by: near.predecessorAccountId() }]<br>    })}`);<br>    return proposal_id;<br>  }<br>  @call({})<br>  approve({ proposal_id }) {<br>    this.assertSigner();<br>    const proposal = this.proposals.get(proposal_id.toString());<br>    assert(proposal,             &quot;Proposal not found&quot;);<br>    assert(!proposal.executed,   &quot;Already executed&quot;);<br>    assert(<br>      !proposal.approvals.includes(near.predecessorAccountId()),<br>      &quot;Already approved&quot;<br>    );<br>    proposal.approvals.push(near.predecessorAccountId());<br>    this.proposals.set(proposal_id.toString(), proposal);<br>    near.log(`EVENT_JSON:${JSON.stringify({<br>      standard: &quot;nep297&quot;, version: &quot;1.0.0&quot;,<br>      event: &quot;proposal_approved&quot;,<br>      data: [{<br>        proposal_id,<br>        approved_by:    near.predecessorAccountId(),<br>        approval_count: proposal.approvals.length<br>      }]<br>    })}`);<br>    if (proposal.approvals.length &gt;= this.required_sigs) {<br>      proposal.executed = true;<br>      this.proposals.set(proposal_id.toString(), proposal);<br>      near.log(`EVENT_JSON:${JSON.stringify({<br>        standard: &quot;nep297&quot;, version: &quot;1.0.0&quot;,<br>        event: &quot;proposal_executed&quot;,<br>        data: [{ proposal_id, action: proposal.action }]<br>      })}`);<br>    }<br>  }<br>  @view({})<br>  get_proposal({ proposal_id }) {<br>    return this.proposals.get(proposal_id.toString()) ?? null;<br>  }<br>}</pre><p>Every action goes through propose, then multiple approve calls, then auto-execution when the threshold is met. The full audit trail lives on-chain. No external Safe contract needed, no dependency on a third-party wallet.</p><h3>Upgrade Pattern</h3><p>This is the one that gets people. NEAR lets you redeploy Wasm to the same account and the code is replaced. The state is preserved. That sounds convenient until you change your contract’s data structure and forget to write a migration.</p><p>If you add a field, rename one, or change a type, the old serialized bytes will not deserialize into the new struct. The contract panics on every call after the upgrade. There is no fallback and no automatic recovery.</p><p><strong>Schema migrations are not optional.</strong> Here is what one looks like:</p><pre>// V1 had: owner_id and counter<br>// V2 adds: version and description<br>@NearBindgen({ requireInit: true })<br>class Contract {<br>  @call({})<br>  migrate() {<br>    assert(<br>      near.predecessorAccountId() === near.currentAccountId(),<br>      &quot;Migration must be called by the contract itself&quot;<br>    );<br>    // old state is already loaded by @NearBindgen<br>    // set safe defaults for the new fields<br>    this.version     = &quot;2.0.0&quot;;<br>    this.description = &quot;&quot;;<br>    near.log(`EVENT_JSON:${JSON.stringify({<br>      standard: &quot;nep297&quot;, version: &quot;1.0.0&quot;,<br>      event: &quot;contract_migrated&quot;,<br>      data: [{ new_version: &quot;2.0.0&quot; }]<br>    })}`);<br>  }<br>}</pre><p>Deploy and migrate in a single atomic transaction:</p><pre>near deploy mycontract.near \<br>  --wasmFile contract_v2.wasm \<br>  --initFunction migrate \<br>  --initArgs &#39;{}&#39;</pre><p>Either both the deploy and the migration succeed together, or neither does. This is actually cleaner than Ethereum’s upgrade flow where you deploy a new implementation and call upgradeTo() as two separate transactions.</p><h3>The Trust Gradient</h3><p>Every NEAR contract sits somewhere on this spectrum. Be honest with your users about where yours sits.</p><p>Stage What It Means Development Single owner key. Move fast. Redeploy freely. Early Mainnet Multisig ownership (2-of-3 or 3-of-5). Add pause. Emit events on all admin actions. Mature Protocol DAO with time-locked proposals. 48 to 72 hour delay before execution. Fully Trustless All Full Access Keys removed. Code is the only authority.</p><p>On Ethereum, immutability is the default and upgradeability requires deliberate engineering. On NEAR, upgradeability is the default and immutability requires deliberate key removal. The end state of a trustless protocol is the same on both chains. The path to get there is different.</p><p>The first thing you should check when auditing any NEAR contract:</p><pre>near keys &lt;contract&gt;.near</pre><p>Keys present means someone can change the contract. Empty means nobody can. Everything else, multisig, DAO, timelock, is the governance layer that determines who that someone is and how constrained they are.</p><h3>Five Things That Actually Matter</h3><ol><li><strong>Write </strong><strong>assertOwner() and </strong><strong>assertRole() as reusable helpers.</strong> Repeating the assert inline in every method is how one method gets missed during a refactor and becomes an unprotected backdoor.</li><li><strong>Emit events on every privileged action.</strong> Pause, unpause, ownership transfer, role grant, upgrade. All of it. It is your audit trail and your users only window into what governance is doing.</li><li><strong>Plan your upgrade path before you launch.</strong> “We will figure out governance later” always means a single key holds full control indefinitely. It never gets figured out later.</li><li><strong>Schema migrations are not optional.</strong> If the state structure changes, write the migration. There is no fallback.</li><li><strong>The two-step ownership transfer is worth the extra ten lines.</strong> You will never regret having it. You will deeply regret not having it exactly once.</li></ol><p><em>Part 3 of 3. If you found this useful, Part 1 covers NEAR contract structure for EVM developers and Part 2 covers state management, collections, and events.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c76654aaaa6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NEAR State Management: Why Your JavaScript Instincts Will Fail You]]></title>
            <link>https://medium.com/@jerrygeorge360/near-state-management-why-your-javascript-instincts-will-fail-you-433282d97703?source=rss-d488cfe4c1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/433282d97703</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[near-protocol]]></category>
            <dc:creator><![CDATA[Jerry George]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 11:43:24 GMT</pubDate>
            <atom:updated>2026-04-13T11:43:24.656Z</atom:updated>
            <content:encoded><![CDATA[<h4>Collections, input validation, error handling, and events. The parts of NEAR that actually trip up experienced developers.</h4><p>In the previous article we covered contract structure and basic read/write methods. That foundation assumed simple scalar state: a string, a number, an owner ID. Real contracts store lists, mappings, and complex records. This is where NEAR’s state model starts to diverge sharply from both Ethereum and standard JavaScript, and where most developers hit their first real wall.</p><h3>The State Model You Need to Understand First</h3><p>Every time a @call method runs, @NearBindgen deserializes your <strong>entire contract state</strong> from storage into memory. When the method finishes, it serializes everything back. Every call. Every time.</p><pre>@NearBindgen({})<br>class Contract {<br>  constructor() {<br>    this.counter = 0;<br>    this.records = [];        // stored and loaded in full on every call<br>    this.user_greetings = {}; // same<br>  }<br>}</pre><p>On a small contract this is fine. As data grows, it becomes a real problem. Imagine a contract with 10,000 records loading all of them just because someone called increment(). That is wasteful by design, and NEAR&#39;s collection types exist specifically to fix it. They lazy-load only what is actually accessed.</p><p>The rule from the official docs is simple: <strong>up to around 100 entries, native collections are acceptable. Beyond that, use SDK collections.</strong> The cost of deserializing a native collection grows with every entry. At some point your contract will exhaust all available gas just reading its own state, and every function call starts failing.</p><p><strong>⚠️ Storage is not free.</strong> Every byte costs approximately 1 NEAR per 100kb, locked as a deposit in the account. It comes back when storage is freed, so it is a stake rather than a fee. Unbounded native collections are doubly dangerous because they waste gas on every call and quietly accumulate storage costs you may not notice until it is too late.</p><h3>State Management: Counters and Basic Fields</h3><p>Simple numeric state is the easiest place to start:</p><pre>import { NearBindgen, near, call, view, initialize, assert } from &quot;near-sdk-js&quot;;<br>@NearBindgen({ requireInit: true })<br>class Contract {<br>  @initialize({})<br>  init({ owner_id }) {<br>    this.owner_id = owner_id;<br>    this.counter  = 0;<br>  }<br>  @call({})<br>  increment() {<br>    this.counter += 1;<br>  }<br>  @view({})<br>  get_counter() {<br>    return this.counter;<br>  }<br>  @call({})<br>  set_counter({ value }) {<br>    assert(<br>      near.predecessorAccountId() === this.owner_id,<br>      &quot;Only owner can set counter&quot;<br>    );<br>    this.counter = value;<br>  }<br>  @call({})<br>  reset_counter() {<br>    assert(<br>      near.predecessorAccountId() === this.owner_id,<br>      &quot;Only owner can reset counter&quot;<br>    );<br>    this.counter = 0;<br>  }<br>}</pre><p>near.predecessorAccountId() is your msg.sender. The account that signed the transaction. One thing that surprises Ethereum developers here is that access control on NEAR is entirely manual. There is no onlyOwner modifier, no OpenZeppelin to lean on. You write the assert yourself on every protected method. We will cover the full Owner Pattern in Article 3.</p><h3>Input Validation: Fail Early, Fail Loudly</h3><p>Solidity reverts the entire transaction on a failed require. NEAR&#39;s assert does the same thing within a single receipt. Use it aggressively on inputs before you touch any state.</p><pre>@call({})<br>add_record({ record }) {<br>  if (record.length === 0) {<br>    near.panicUtf8(&quot;Record cannot be empty&quot;);<br>  }<br>  this.records.push(record);<br>}</pre><p>near.panicUtf8 is the explicit panic. Think of it as revert(&quot;message&quot;) in Solidity. Use it when you want to fail with a specific message outside of a boolean condition. assert handles condition checks and near.panicUtf8 handles explicit exits.</p><p><strong>Safe integer arithmetic</strong> is something Solidity handles automatically since 0.8, but on NEAR with JavaScript you are on your own:</p><pre>@view({})<br>safe_add({ a, b }) {<br>  if (a + b &gt; Number.MAX_SAFE_INTEGER) {<br>    return null;<br>  }<br>  return a + b;<br>}</pre><p>JavaScript numbers are 64-bit floats. Number.MAX_SAFE_INTEGER is 2^53 - 1. Go beyond that and integer precision is lost silently. No error, no revert, just wrong numbers. Guard this yourself or use BigInt for values that might exceed this bound.</p><p><strong>Parsing untrusted input</strong> follows a similar principle:</p><pre>@view({})<br>try_parse({ s }) {<br>  const result = parseInt(s);<br>  if (isNaN(result)) return null;<br>  return result;<br>}</pre><p>parseInt does not throw on invalid input. It returns NaN. Always check with isNaN before you use the result.</p><h3>Error Handling: What Reverting Actually Means on NEAR</h3><p>This is the one that catches Ethereum developers off guard the most.</p><p>On Ethereum, revert unwinds the <strong>entire transaction</strong> atomically. Every state change across every contract call gets rolled back. One failure, everything undone.</p><p>On NEAR, execution is broken into <strong>receipts</strong>. A panic only reverts the current receipt, not the whole chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uk53Ly59nW_UVE4OOj3e9A.png" /><figcaption>Ethereum vs Near Error Handling</figcaption></figure><p>For single-contract methods this does not matter much. The moment you start writing cross-contract calls it becomes the most important thing to understand. We will go deep on that in Article 3.</p><p>For something like get_record, validate bounds before accessing the array:</p><pre>@view({})<br>get_record({ index }) {<br>  if (index &lt; 0 || index &gt;= this.records.length) {<br>    return null;<br>  }<br>  return this.records[index];<br>}</pre><p>Return null for expected invalid states rather than panicking. When a view method panics, callers have no way to tell whether the contract is broken or the query was just invalid. Return null for things that are legitimately missing. Panic for things that should genuinely never happen.</p><h3>Collections: Vector</h3><p>The records array works fine for small datasets. It does not scale. The entire array is loaded from storage on every contract call, even when you only need one element.</p><p>NEAR’s Vector collection fixes this by storing elements individually in the key-value store and loading only what you access:</p><pre>import { NearBindgen, near, call, view, initialize, Vector } from &quot;near-sdk-js&quot;;<br>@NearBindgen({ requireInit: true })<br>class Contract {<br>  @initialize({})<br>  init() {<br>    this.records = new Vector(&quot;r&quot;);<br>  }<br>  @call({})<br>  add_record({ record }) {<br>    if (!record || record.length === 0) {<br>      near.panicUtf8(&quot;Record cannot be empty&quot;);<br>    }<br>    this.records.push(record);<br>  }<br>  @view({})<br>  get_record({ index }) {<br>    if (index &lt; 0 || index &gt;= this.records.length) {<br>      return null;<br>    }<br>    return this.records.get(index);<br>  }<br>  @view({})<br>  get_all_records() {<br>    return this.records.toArray();<br>  }<br>}</pre><p>The &quot;r&quot; passed to new Vector(&quot;r&quot;) is the storage prefix. Each element gets its own key-value entry in storage (r-0, r-1, r-2...) so only the elements you actually touch get loaded. Think of it as namespacing.</p><p><strong>⚠️ Two rules about prefixes you cannot break.</strong> Never use the same prefix for two collections in the same contract. It causes silent data corruption that is incredibly hard to debug. And never re-assign a collection to a new instance without clearing the old one first. Doing so orphans the old data in storage and leaks your storage stake indefinitely.</p><p>Plain JS Array NEAR Vector Load behavior Fully loaded on every call Lazy-loaded per element Safe up to ~100 entries Any size Storage prefix Not needed Required, must be unique API Standard JS .push(), .get(index), .length, .toArray()</p><h3>Collections: LookupMap</h3><p>Plain JavaScript objects used as maps load entirely from storage on every call, just like arrays. For any key-value data that grows, use LookupMap:</p><pre>import { NearBindgen, near, call, view, initialize, assert, LookupMap } from &quot;near-sdk-js&quot;;<br>@NearBindgen({ requireInit: true })<br>class Contract {<br>  @initialize({})<br>  init({ owner_id }) {<br>    this.owner_id       = owner_id;<br>    this.user_greetings = new LookupMap(&quot;ug&quot;);<br>  }<br>  @call({})<br>  set_greeting({ account, greeting }) {<br>    assert(greeting.length &gt; 0, &quot;Greeting cannot be empty&quot;);<br>    this.user_greetings.set(account, greeting);<br>  }<br>  @view({})<br>  get_greeting({ account }) {<br>    return this.user_greetings.get(account) ?? &quot;Default greeting&quot;;<br>  }<br>}</pre><p>LookupMap loads only the specific key you request. It is the direct equivalent of Solidity&#39;s mapping. The tradeoff is that you cannot iterate over it. If you need to iterate, use UnorderedMap instead.</p><p>Need Use O(1) lookup, no iteration LookupMap O(1) lookup and iteration UnorderedMap Ordered list by index Vector Unique values, no iteration LookupSet Unique values and iteration UnorderedSet</p><h3>Pagination: Do Not Expose Unbounded Reads</h3><p>Never write a view method that calls toArray() on a collection without limits. Vector and UnorderedMap can grow past what a single gas-limited call can read. At some point that method will start failing on every call, with no way to recover short of redeployment.</p><p>Add from_index and limit to any view that reads multiple entries:</p><pre>@view({})<br>get_records({ from_index, limit }) {<br>  return this.records.toArray().slice(from_index, from_index + limit);<br>}</pre><p>One thing to watch here: the second argument to slice is the end index, not the count. It should be from_index + limit, not just limit. This is an easy off-by-one to miss.</p><h3>Events: Structured Logs on NEAR</h3><p>Ethereum events are indexed and filterable at the protocol level. NEAR does not have this natively, but the <strong>NEAR Event Standard (NEP-297)</strong> defines a structured log format that indexers know how to consume.</p><pre>@call({})<br>set_greeting({ account, greeting }) {<br>  assert(greeting.length &gt; 0, &quot;Greeting cannot be empty&quot;);<br>const old_greeting = this.user_greetings.get(account) ?? &quot;&quot;;<br>  this.user_greetings.set(account, greeting);<br>  near.log(`EVENT_JSON:${JSON.stringify({<br>    standard: &quot;nep297&quot;,<br>    version:  &quot;1.0.0&quot;,<br>    event:    &quot;greeting_updated&quot;,<br>    data: [{<br>      account_id:   account,<br>      old_greeting: old_greeting,<br>      new_greeting: greeting,<br>    }]<br>  })}`);<br>}</pre><p>The EVENT_JSON: prefix is the signal that NEAR indexers like The Graph and Pagoda look for. Without it, the log is just a string. With it, the log becomes queryable structured data. NEAR logs are not filterable by the protocol itself, so you depend on indexer infrastructure to make them useful. For most practical use cases though, they work the same way Ethereum events do from an application perspective.</p><h3>Putting It Together</h3><pre>import { <br>  NearBindgen, near, call, view, initialize,<br>  assert, Vector, LookupMap<br>} from &quot;near-sdk-js&quot;;<br>@NearBindgen({ requireInit: true })<br>class Contract {<br>  @initialize({})<br>  init({ owner_id }) {<br>    this.owner_id       = owner_id;<br>    this.counter        = 0;<br>    this.records        = new Vector(&quot;r&quot;);<br>    this.user_greetings = new LookupMap(&quot;ug&quot;);<br>  }<br>  @call({})<br>  increment() { this.counter += 1; }<br>  @view({})<br>  get_counter() { return this.counter; }<br>  @call({})<br>  reset_counter() {<br>    assert(near.predecessorAccountId() === this.owner_id, &quot;Owner only&quot;);<br>    this.counter = 0;<br>  }<br>  @call({})<br>  add_record({ record }) {<br>    if (!record || record.length === 0) near.panicUtf8(&quot;Empty record&quot;);<br>    this.records.push(record);<br>    near.log(`EVENT_JSON:${JSON.stringify({<br>      standard: &quot;nep297&quot;, version: &quot;1.0.0&quot;,<br>      event: &quot;record_added&quot;, data: [{ record }]<br>    })}`);<br>  }<br>  @view({})<br>  get_records({ from_index, limit }) {<br>    return this.records.toArray().slice(from_index, from_index + limit);<br>  }<br>  @view({})<br>  get_record({ index }) {<br>    if (index &lt; 0 || index &gt;= this.records.length) return null;<br>    return this.records.get(index);<br>  }<br>  @view({})<br>  safe_add({ a, b }) {<br>    if (a + b &gt; Number.MAX_SAFE_INTEGER) return null;<br>    return a + b;<br>  }<br>  @view({})<br>  try_parse({ s }) {<br>    const result = parseInt(s);<br>    return isNaN(result) ? null : result;<br>  }<br>  @call({})<br>  set_greeting({ account, greeting }) {<br>    assert(greeting.length &gt; 0, &quot;Empty greeting&quot;);<br>    this.user_greetings.set(account, greeting);<br>  }<br>  @view({})<br>  get_greeting({ account }) {<br>    return this.user_greetings.get(account) ?? &quot;Default greeting&quot;;<br>  }<br>}</pre><h3>The Patterns That Matter</h3><p>Six things from this article that apply to every real NEAR contract you will write:</p><ol><li><strong>Native collections are fine up to around 100 entries.</strong> Beyond that, always use SDK collections.</li><li><strong>Unique prefixes per collection, always.</strong> Never re-assign without clearing the old data first.</li><li><strong>Validate inputs before touching state.</strong> Panic early and never leave state half-updated.</li><li><strong>NEAR panics revert the current receipt only.</strong> Cross-contract failures do not unwind previous receipts automatically.</li><li><strong>Paginate any view that reads a growing collection.</strong> Add from_index and limit from day one, not as an afterthought.</li><li><strong>Emit structured NEP-297 logs for any state change that matters.</strong> Your frontend and your future self will thank you.</li></ol><p><em>Part 2 of 3. Next up: security patterns in NEAR. Owner access, role-based access, pausable contracts, multisig, and how to think about upgrades responsibly.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=433282d97703" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NEAR Smart Contract Fundamentals for EVM Developers]]></title>
            <link>https://medium.com/@jerrygeorge360/near-smart-contract-fundamentals-for-evm-developers-f875eb99d4bc?source=rss-d488cfe4c1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f875eb99d4bc</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[near-protocol]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[earn]]></category>
            <dc:creator><![CDATA[Jerry George]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 11:15:09 GMT</pubDate>
            <atom:updated>2026-04-13T11:16:13.066Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 1 of a three-article series on building with NEAR as an Ethereum developer. This article covers contract structure, storage, view methods, and change methods, written for someone who already thinks in Solidity.</em></p><h3>The Mental Model Shift</h3><p>The syntax is easy. The hard part is <strong>unlearning Ethereum assumptions</strong> that feel so natural you don’t notice you’re making them.</p><h3>Your First NEAR Contract</h3><pre>import { NearBindgen, view, call, initialize, assert, near } from &quot;near-sdk-js&quot;;<br>@NearBindgen({ requireInit: true })<br>class Contract {<br>    // state and storage<br>    owner_id: string = &quot;&quot;;<br>    greeting: string = &quot;&quot;;<br>    // schema (compulsory)<br>    static schema = {<br>        owner_id: &quot;string&quot;,<br>        greeting: &quot;string&quot;,<br>    };<br>    @initialize({})<br>    init({ owner_id, greeting = &quot;Hello from NEAR!&quot; }: { owner_id: string; greeting?: string }): void {<br>        this.owner_id = owner_id;<br>        this.greeting = greeting;<br>    }<br>    @view({})<br>    get_greeting(): string {<br>        return this.greeting;<br>    }<br>    @call({})<br>    set_greeting({ new_greeting }: { new_greeting: string }): void {<br>        assert(<br>            near.predecessorAccountId() === this.owner_id,<br>            &quot;Only owner can set greeting&quot;<br>        );<br>        near.log(`Saving greeting ${new_greeting}`);<br>        this.greeting = new_greeting;<br>    }<br>}</pre><blockquote><em>This looks like a Solidity contract with decorators instead of modifiers. The execution model underneath is fundamentally different.</em></blockquote><h3>Contract Structure: One Account, One Contract</h3><p>On Ethereum, contracts and wallets are two separate entity types. A contract address holds bytecode. An EOA holds a key. They never overlap.</p><p>NEAR has one account type. Every account can optionally hold a contract. alice.near can hold your token contract and still sign transactions with her key. <strong>The account is the contract.</strong></p><p>@NearBindgen handles serializing your class fields to NEAR&#39;s key-value storage and deserializing them back on every call. Your class fields are your contract state. No mappings, no SSTORE, no storage slots.</p><pre>@NearBindgen({ requireInit: true })<br>class Contract {<br>// state and storage<br>    owner_id: string = &quot;&quot;; // persisted to account storage<br>    greeting: string = &quot;&quot;; // persisted to account storage</pre><p><strong>⚠️ Always use </strong><strong>requireInit: true.</strong> Without it, the first person to call any function triggers the constructor. In a contract that sets owner_id from near.predecessorAccountId(), that means the first caller becomes the owner. This has been exploited.</p><h3>Initialization: You Control It Explicitly</h3><p>On Ethereum, constructors run exactly once at deployment. NEAR doesn’t work that way. <strong>Deployment and initialization are separate steps.</strong></p><pre>@initialize({ privateFunction: true })<br>init({ owner_id, greeting = &quot;Hello from NEAR!&quot; }: { owner_id: string; greeting?: string }): void {<br>    this.owner_id = owner_id;<br>    this.greeting = greeting;<br>}</pre><ul><li>@initialize ensures this method can only be called <strong>once</strong>. Call it twice and the contract panics.</li><li>Miss calling it before other methods and, with requireInit: true, the contract panics there too.</li></ul><pre># Deploy the Wasm<br>near deploy mycontract.near --wasmFile contract.wasm<br><br># Initialize with explicit owner<br>near call mycontract.near init \<br>  &#39;{&quot;owner_id&quot;: &quot;alice.near&quot;}&#39; \<br>  --accountId alice.near</pre><p><strong>The tradeoff:</strong> this separation is more flexible than Solidity constructors. You can batch deploy and init, or delay initialization deliberately. But the contract is <strong>not in a safe state</strong> between deploy and init.</p><h3>View Methods: Read-Only, Free to Call</h3><pre>@view({})<br>get_greeting(): string {<br>    return this.greeting;<br>}</pre><p>Property Detail Modifies state? No Costs gas? No Requires transaction? No. Direct RPC query. Solidity equivalent view modifier</p><pre>near view mycontract.near get_greeting &#39;{}&#39;<br># &quot;Hello from NEAR!&quot;</pre><p><strong>⚠️ Calling </strong><strong>near.predecessorAccountId() inside a </strong><strong>@view method will panic.</strong> There is no predecessor in a view call. Use near.currentAccountId() instead.</p><h3>Change Methods: Transactions That Modify State</h3><pre>@call({})<br>set_greeting({ new_greeting }: { new_greeting: string }): void {<br>    assert(<br>        near.predecessorAccountId() === this.owner_id,<br>        &quot;Only owner can set greeting&quot;<br>    );<br>    near.log(`Saving greeting ${new_greeting}`);<br>    this.greeting = new_greeting;<br>}</pre><p>NEAR Solidity Equivalent @call non-view function near.predecessorAccountId() msg.sender assert require</p><p>assert panics and reverts state changes, <strong>but only for the current receipt</strong>. In cross-contract call chains, each call is a separate receipt. A failure in one does <strong>not</strong> automatically unwind previous receipts. For a single-contract method, it behaves exactly like require.</p><pre># Owner sets greeting<br>near call mycontract.near set_greeting \<br>  &#39;{&quot;new_greeting&quot;: &quot;Hello World&quot;}&#39; \<br>  --accountId alice.near<br><br># Non-owner attempt, panics: &quot;Only owner can set greeting&quot;<br>near call mycontract.near set_greeting \<br>  &#39;{&quot;new_greeting&quot;: &quot;Hacked&quot;}&#39; \<br>  --accountId bob.near</pre><h3>A Note on near-sdk-js Versions</h3><p>You will likely encounter patterns in learning environments that differ from the official documentation:</p><pre>@NearBindgen({})<br>class Contract {<br>  constructor({ owners } = { owners: [] }) {<br>    this.owners = owners || [];<br>  }<br>@call({})<br>  init({ initial_owner }) {       // plain @call, not @initialize<br>    this.owners.push(initial_owner);<br>  }<br>  @call({})<br>  add_owner({ account }) {<br>    require(this.is_owner(near.predecessorAccountId()), &quot;Only owner&quot;);<br>    this.owners.push(account);<br>  }<br>}</pre><p>Learning Env Production Init @call named init @initialize decorator Uninit guard None requireInit: true Access control require() assert() Collections Plain arrays/objects Vector, LookupMap Constructor Inline predecessorAccountId() Empty strings + init</p><p><strong>Three of these differences are safety issues:</strong></p><ul><li>@initialize guarantees one-time-only. A regular @call named init can be called <strong>repeatedly</strong>, overwriting state each time.</li><li>requireInit: true prevents any call before initialization.</li><li>require is <strong>not</strong> exported by the SDK. It will throw a ReferenceError.</li></ul><h3>The State Model: What Actually Gets Stored</h3><p>In Solidity, every state variable maps to a specific storage slot. NEAR uses a key-value store. @NearBindgen serializes your entire class via <strong>Borsh</strong> and deserializes it back on every call.</p><p><strong>⚠️ Schema changes require a migration function.</strong> If you redeploy with a different class structure (adding a field, renaming one, changing a type), the old serialized bytes won’t deserialize into your new struct. The contract panics on every call.</p><p>Storage on NEAR is also not free. Every byte requires a proportional amount of NEAR tokens locked in the account. This is called <strong>storage staking</strong>. Tokens are returned when storage is freed. It’s not a fee; it’s a deposit.</p><h3>The Five Core Patterns</h3><p>Every NEAR contract is built on these five patterns:</p><ul><li>@NearBindgen: state serialization and contract lifecycle</li><li>requireInit + @initialize: safe, explicit initialization</li><li>@view: read-only queries, no gas, no transaction</li><li>@call + assert: state changes with access control</li><li>near.predecessorAccountId(): the NEAR equivalent of msg.sender</li></ul><p>Get these right and you have the skeleton of any NEAR contract. Everything else (collections, events, cross-contract calls, upgrades) is built on top.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f875eb99d4bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding NEAR’s Random Seed: How Deterministic Randomness Actually Works]]></title>
            <link>https://medium.com/@jerrygeorge360/understanding-nears-random-seed-how-deterministic-randomness-actually-works-84ee117b58ed?source=rss-d488cfe4c1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/84ee117b58ed</guid>
            <category><![CDATA[near-protocol]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Jerry George]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 07:07:04 GMT</pubDate>
            <atom:updated>2025-08-31T07:07:04.011Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started building smart contracts on NEAR, one feature that really caught my attention was the built-in random seed. Coming from other blockchains where getting good randomness is a real headache, NEAR’s approach felt almost too good to be true. Let me walk you through how this elegant system actually works under the hood.</p><h3>THE CHALLENGE OF BLOCKCHAIN RANDOMNESS</h3><p>Before diving into NEAR’s solution, it’s worth understanding why randomness is so tricky on blockchains in the first place. Traditional blockchains are deterministic by design; given the same inputs, every node needs to produce exactly the same outputs. This is great for consensus, but terrible for generating random numbers.</p><p>Most developers end up using block hashes or timestamps as pseudo-random sources, but these are either predictable or manipulable. NEAR took a different approach that’s both clever and practical.</p><h3>HOW NEAR’S RANDOM SEED WORKS</h3><p>NEAR provides what they call a “deterministic and verifiable” random seed. Here’s the beautiful part: the random seed comes from the validator who produced the block, created by signing the previous block hash with their private key.</p><p>Think about what this means:</p><p><strong>It’s deterministic</strong> because given the same previous block hash and the same validator’s private key, you’ll always get the same signature (and thus the same random seed).</p><p><strong>It’s verifiable</strong> because anyone can check that the validator actually signed the previous block hash correctly using standard cryptographic verification.</p><p>This creates a randomness source that’s both unpredictable (you can’t know the validator’s private key) and tamper-proof (the validator has to sign a specific previous block hash).</p><h3>THE ELEGANT DESIGN CHOICES</h3><p>What I find most interesting about this approach is how it balances predictability and unpredictability:</p><p><strong>Only the current validator knows the outcome.</strong> Since the random seed is generated using their private key, only they can predict what number will come out. Everyone else has to wait for the block to be mined.</p><p><strong>The validator can’t manipulate the seed itself.</strong> They’re forced to sign the previous block hash, which (with high probability) they had no control over. They can’t just pick a convenient random number.</p><p>This creates an interesting dynamic where randomness is generated through a process that’s partially predictable (to one party) but cryptographically sound.</p><h3>PRACTICAL IMPLICATIONS FOR DEVELOPERS</h3><p>Understanding how this works changes how you think about building applications that use randomness. The random seed isn’t just some magical black box; it’s the result of a specific cryptographic process with specific properties.</p><p>When you call for a random seed in your NEAR contract, you’re essentially asking: “What did the current validator get when they signed the previous block hash?” This makes the randomness feel more concrete and understandable.</p><h3>THE NUANCED REALITY</h3><p>While NEAR’s approach is clever, it’s not perfect. There are some edge cases where validators might have slight advantages:</p><p><strong>Input timing matters.</strong> If your application takes user input and immediately uses it with the random seed, a validator could potentially optimize their input since they know the outcome.</p><p><strong>Block inclusion is discretionary.</strong> Validators have some control over which transactions they include in their blocks, which could theoretically be used strategically.</p><p><strong>Multi-block scenarios work better.</strong> If you separate user input (block N) from random resolution (block N+1), you eliminate most timing-based advantages.</p><p>These aren’t necessarily “attacks” they’re just the natural properties of how the system works. Understanding them helps you design better applications.</p><h3>BUILDING WITH RANDOMNESS IN MIND</h3><p>The key insight is that NEAR’s random seed works best when you design your application flow thoughtfully. Instead of worrying about edge cases, focus on leveraging the strengths of the system:</p><p>Use the random seed for applications where verifiable randomness is more important than perfect unpredictability. Design multi-step processes where input and resolution happen in different blocks. Take advantage of the fact that the randomness is deterministic and can be verified by anyone.</p><h3>WHY THIS APPROACH MATTERS</h3><p>NEAR’s random seed implementation represents a practical compromise in blockchain design. It’s not theoretically perfect, but it’s incredibly useful for real applications. Most randomness use cases don’t require perfect unpredictability; they just need something that’s “random enough” and verifiable.</p><p>For building games, lotteries, or any application that needs some element of chance, NEAR’s random seed gives you a tool that’s both accessible and cryptographically sound. You don’t need to import external oracles or build complex commit reveal schemes for basic randomness needs.</p><h3>WRAPPING UP</h3><p>NEAR’s approach to randomness shows how blockchain protocols can provide practical solutions to common developer challenges. The random seed isn’t just a feature; it’s a thoughtful design choice that balances security, usability, and verifiability.</p><p>Next time you’re building something that needs randomness on NEAR, you’ll have a deeper understanding of what’s actually happening when you call that random seed function. It’s not magic, it’s cryptography working exactly as designed.</p><p>Have you used NEAR’s random seed in your projects? I’d be curious to hear how it worked out for your specific use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84ee117b58ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Cross-Contract Patterns in NEAR: Beyond the Basics]]></title>
            <link>https://medium.com/@jerrygeorge360/advanced-cross-contract-patterns-in-near-beyond-the-basics-a6905b1e1630?source=rss-d488cfe4c1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6905b1e1630</guid>
            <category><![CDATA[near-protocol]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Jerry George]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 06:36:51 GMT</pubDate>
            <atom:updated>2025-08-31T06:36:51.646Z</atom:updated>
            <content:encoded><![CDATA[<p>So you’ve mastered simple cross-contract calls in NEAR and you’re ready to level up? Perfect. Today we’re diving deep into the sophisticated patterns that make NEAR’s asynchronous architecture truly shine: batch operations, parallel execution, and complex callback orchestration.</p><p>If you’re building anything more complex than basic token transfers or simple data queries, these patterns will become your bread and butter.</p><h3>Why Complex Patterns Matter</h3><p>Here’s the thing about NEAR’s sharded, asynchronous design — it’s not just different for the sake of being different. It unlocks capabilities that are simply impossible on synchronous blockchains.</p><p>Imagine trying to coordinate a flash loan, price oracle updates, and liquidity pool adjustments all in a single atomic operation on Ethereum. You’d hit gas limits, face reentrancy issues, and deal with cascading failures. On NEAR? You can orchestrate these operations elegantly across multiple shards while maintaining proper error isolation.</p><h3>Pattern 1: Batch Actions — When Atomicity Matters</h3><p>Sometimes you need multiple operations on the same contract to succeed or fail together. That’s where batch actions become invaluable.</p><h3>The Real-World Scenario</h3><p>Think about a complex DeFi operation: you want to withdraw collateral, swap tokens, and update your position — all atomically. If the swap fails, you don’t want to be left with withdrawn collateral and an unchanged position.</p><pre># All these calls execute sequentially<br># If any fails, everything reverts<br>Promise.create_batch(&quot;defi_protocol.testnet&quot;)\<br>  .function_call(&quot;withdraw_collateral&quot;, {&quot;amount&quot;: &quot;1000&quot;}, 0, 50_000_000_000_000)\<br>  .function_call(&quot;swap_tokens&quot;, {&quot;from&quot;: &quot;USDC&quot;, &quot;to&quot;: &quot;NEAR&quot;, &quot;amount&quot;: &quot;1000&quot;}, 0, 50_000_000_000_000)\<br>  .function_call(&quot;update_position&quot;, {&quot;new_collateral_ratio&quot;: &quot;150&quot;}, 0, 30_000_000_000_000)</pre><h3>What Makes This Powerful</h3><p>The beauty of batch actions lies in their atomicity. Either your entire complex operation succeeds, or none of it happens. No partial states, no cleanup required — just clean, predictable behavior.</p><p>Your callback receives the result from the last action in the sequence, which makes sense because if any earlier action had failed, you wouldn’t have gotten to the callback at all.</p><pre>from near_sdk_py import callback, Context, Contract<br>class DeFiContract(Contract):<br>    <br>    @callback<br>    def defi_operation_callback(self, user_id: str, operation_type: str):<br>        result = Context.promise_result(0)<br>        <br>        if not result.success:<br>            return {<br>                &quot;success&quot;: False,<br>                &quot;message&quot;: &quot;DeFi operation failed - no changes made&quot;,<br>                &quot;user_id&quot;: user_id<br>            }<br>        <br>        # Process the successful final result<br>        final_position = result.data<br>        return {<br>            &quot;success&quot;: True,<br>            &quot;message&quot;: f&quot;{operation_type} completed successfully&quot;,<br>            &quot;new_position&quot;: final_position,<br>            &quot;user_id&quot;: user_id<br>        }</pre><h3>Pattern 2: Parallel Execution — Embrace the Chaos</h3><p>Here’s where NEAR gets really interesting. You can fire off multiple cross-contract calls simultaneously, and they’ll execute in parallel across different shards. If one fails, the others keep going.</p><h3>When Parallel Makes Sense</h3><p>Perfect for scenarios like:</p><ul><li>Fetching price data from multiple oracles</li><li>Executing independent operations across different protocols</li><li>Building resilient systems that don’t fail completely when one component has issues</li></ul><pre># These all execute simultaneously<br>Promise.all([<br>    Promise.create(&quot;oracle-a.testnet&quot;).function_call(&quot;get_price&quot;, {&quot;symbol&quot;: &quot;NEAR&quot;}, 0, 30_000_000_000_000),<br>    Promise.create(&quot;oracle-b.testnet&quot;).function_call(&quot;get_price&quot;, {&quot;symbol&quot;: &quot;NEAR&quot;}, 0, 30_000_000_000_000),<br>    Promise.create(&quot;oracle-c.testnet&quot;).function_call(&quot;get_price&quot;, {&quot;symbol&quot;: &quot;NEAR&quot;}, 0, 30_000_000_000_000)<br>])</pre><h3>Handling Partial Success Like a Pro</h3><p>With parallel execution, your callback needs to be smart about partial failures. You’ll get an array of results — some successful, some failed — and you need to decide what to do with that mixed bag.</p><pre>from near_sdk_py import callback, Context, Contract<br>class OracleAggregator(Contract):<br>    <br>    @callback<br>    def oracle_aggregation_callback(self, request_id: str, min_responses_required: int):<br>        all_results = []<br>        <br>        # Process each oracle response<br>        for i in range(3):<br>            result = Context.promise_result(i)<br>            <br>            if result.success:<br>                try:<br>                    price_data = result.data<br>                    all_results.append({<br>                        &quot;oracle_id&quot;: i, <br>                        &quot;price&quot;: price_data[&quot;price&quot;], <br>                        &quot;success&quot;: True<br>                    })<br>                except Exception as error:<br>                    all_results.append({<br>                        &quot;oracle_id&quot;: i, <br>                        &quot;success&quot;: False, <br>                        &quot;error&quot;: &quot;Parse failed&quot;<br>                    })<br>            else:<br>                all_results.append({<br>                    &quot;oracle_id&quot;: i, <br>                    &quot;success&quot;: False, <br>                    &quot;error&quot;: &quot;Call failed&quot;<br>                })<br>        <br>        successful_responses = [r for r in all_results if r[&quot;success&quot;]]<br>        <br>        if len(successful_responses) &lt; min_responses_required:<br>            return {<br>                &quot;success&quot;: False,<br>                &quot;message&quot;: f&quot;Insufficient oracle responses: {len(successful_responses)}/{min_responses_required}&quot;,<br>                &quot;request_id&quot;: request_id<br>            }<br>        <br>        # Calculate median price from successful responses<br>        prices = sorted([r[&quot;price&quot;] for r in successful_responses])<br>        median_price = prices[len(prices) // 2]<br>        <br>        return {<br>            &quot;success&quot;: True,<br>            &quot;price&quot;: median_price,<br>            &quot;sources_used&quot;: len(successful_responses),<br>            &quot;request_id&quot;: request_id<br>        }</pre><h3>Pattern 3: Uniform Response Handling — When Structure Matters</h3><p>Sometimes you’re calling multiple contracts that all return the same data structure. Maybe you’re polling multiple identical data sources or calling the same method across contract instances. This pattern makes that elegant.</p><h3>The Scenario</h3><p>Imagine you’re building a cross-chain bridge that needs to verify the same transaction across multiple validator contracts:</p><pre># Call multiple validator contracts<br>from near_sdk_py import Promise<br>validator_contracts = [<br>    &quot;validator-1.testnet&quot;,<br>    &quot;validator-2.testnet&quot;, <br>    &quot;validator-3.testnet&quot;<br>]<br>validator_promises = [<br>    Promise.create(validator).function_call(<br>        &quot;verify_transaction&quot;,<br>        {&quot;tx_hash&quot;: transaction_hash, &quot;chain_id&quot;: source_chain},<br>        0,<br>        50_000_000_000_000<br>    )<br>    for validator in validator_contracts<br>]<br>return Promise.all(validator_promises)</pre><h3>Processing Uniform Responses Efficiently</h3><p>When all your external calls return the same structure, you can process them more systematically:</p><pre>from near_sdk_py import callback, Context, Contract<br>class TransactionValidator(Contract):<br>    <br>    @callback<br>    def verification_callback(self, transaction_hash: str, required_confirmations: int):<br>        verifications = []<br>        <br>        # Since all validators return the same structure, we can process uniformly<br>        for i in range(3):<br>            result = Context.promise_result(i)<br>            <br>            if result.success:<br>                try:<br>                    verification = result.data<br>                    verifications.append({<br>                        &quot;validator&quot;: i,<br>                        &quot;verified&quot;: verification[&quot;is_valid&quot;],<br>                        &quot;confidence&quot;: verification[&quot;confidence_score&quot;],<br>                        &quot;timestamp&quot;: verification[&quot;checked_at&quot;]<br>                    })<br>                except Exception as error:<br>                    verifications.append({<br>                        &quot;validator&quot;: i,<br>                        &quot;verified&quot;: False,<br>                        &quot;error&quot;: &quot;Invalid response format&quot;<br>                    })<br>            else:<br>                verifications.append({<br>                    &quot;validator&quot;: i,<br>                    &quot;verified&quot;: False,<br>                    &quot;error&quot;: &quot;Validator unreachable&quot;<br>                })<br>        <br>        confirmed = len([v for v in verifications if v[&quot;verified&quot;]])<br>        verification_passed = confirmed &gt;= required_confirmations<br>        <br>        return {<br>            &quot;transaction_hash&quot;: transaction_hash,<br>            &quot;verification_passed&quot;: verification_passed,<br>            &quot;confirmations&quot;: confirmed,<br>            &quot;required&quot;: required_confirmations,<br>            &quot;validator_details&quot;: verifications<br>        }</pre><h3>The Production Reality: What They Don’t Tell You</h3><p>Building real applications with these patterns requires understanding some nuances that aren’t obvious from simple examples.</p><h3>Callbacks Always Execute (Yes, Always)</h3><p>This is probably the most important thing to understand: your callback will run whether external calls succeed or fail. This has profound implications for how you design your error handling.</p><p>If you’ve modified state in your original function call and then an external call fails, you need to manually clean up. NEAR won’t do it for you.</p><pre>from near_sdk_py import call, callback, Context, Contract, init<br><br>class PaymentContract(Contract):<br>    <br>    @init<br>    def __init__(self):<br>        self.storage[&#39;user&#39;] = {}<br>        <br>    @call<br>    def risky_operation(self, user_id: str, amount: int):<br>        # State change happens here<br>        self.storage[&#39;user&#39;][f&quot;pending_{user_id}&quot;] = {<br>            &quot;amount&quot;: amount,<br>            &quot;status&quot;: &quot;pending&quot;,<br>            &quot;timestamp&quot;: Context.block_timestamp()<br>        }<br>        <br>        # External call might fail<br>        return CrossContract(&quot;external.testnet&quot;).call(<br>            &quot;process_payment&quot;,<br>            user_id=user_id,<br>            amount=amount<br>        ).then(<br>            &quot;payment_callback&quot;,<br>            user_id=user_id,<br>            amount=amount<br>        ).value()<br><br>    @callback<br>    def payment_callback(self, user_id: str, amount: int):<br>        result = Context.promise_result(0)<br>        <br>        if not result.success:<br>            # External call failed - manual cleanup required<br>            if f&quot;pending_{user_id}&quot; in self.storage:<br>                del self.storage[&#39;user&#39;][f&quot;pending_{user_id}&quot;]<br>            self.refund_user(user_id, amount)<br>            <br>            return {<br>                &quot;success&quot;: False,<br>                &quot;message&quot;: &quot;Payment processing failed - funds refunded&quot;<br>            }<br>        <br>        # Success - update state accordingly<br>        if f&quot;pending_{user_id}&quot; in self.storage:<br>            del self.storage[&#39;user&#39;][f&quot;pending_{user_id}&quot;]<br>        self.record_successful_payment(user_id, amount)<br>        <br>        return {&quot;success&quot;: True, &quot;message&quot;: &quot;Payment completed&quot;}</pre><h3>Gas Economics in Complex Calls</h3><p>Each cross-contract call consumes gas, and complex patterns can get expensive quickly. Here’s what I’ve learned about managing gas effectively:</p><ol><li><strong>Budget for callbacks</strong>: Your callback execution also consumes gas</li><li><strong>Parallel calls aren’t free</strong>: Each parallel call requires its own gas allocation</li><li><strong>Batch operations can be efficient</strong>: Sequential calls in a batch share overhead costs</li></ol><pre># Be explicit about gas allocation<br>from near_sdk_py import call, ONE_TGAS</pre><pre>EXTERNAL_CALL_GAS = 50 * ONE_TGAS  # 50 TGas<br>CALLBACK_GAS = 20 * ONE_TGAS       # 20 TGas<br>TOTAL_REQUIRED = EXTERNAL_CALL_GAS + CALLBACK_GAS</pre><pre>class HeavyComputationContract(Contract):<br>    <br>    @call(gas=TOTAL_REQUIRED)<br>    def expensive_operation(self):<br>        return CrossContract(&quot;heavy_contract.testnet&quot;).call(<br>            &quot;complex_computation&quot;, <br>            {},<br>            gas=EXTERNAL_CALL_GAS<br>        ).then(<br>            &quot;process_result&quot;,<br>            {}<br>        ).value()</pre><h3>Building Resilient Multi-Contract Applications</h3><p>The real power of these patterns emerges when you combine them thoughtfully. Here’s a pattern I use for building resilient applications:</p><h3>The Circuit Breaker Pattern</h3><pre>from near_sdk_py import call, callback, Context, Contract, Promise<br>class ResilientDataContract(Contract):<br>    <br>    @call<br>    def resilient_data_fetch(self, data_sources: dict, fallback_enabled: bool):<br>        # Try primary sources in parallel<br>        primary_promises = [<br>            Promise.create(source).function_call(&quot;get_data&quot;, {}, 0, 30_000_000_000_000)<br>            for source in data_sources[&quot;primary&quot;]<br>        ]<br>        <br>        return Promise.all(primary_promises).then(<br>            &quot;evaluate_primary_results&quot;,<br>            fallback_sources=data_sources[&quot;fallback&quot;],<br>            fallback_enabled=fallback_enabled<br>        ).value()<br>    @callback<br>    def evaluate_primary_results(self, fallback_sources: list, fallback_enabled: bool):<br>        results = self.get_all_promise_results()<br>        successful = [r for r in results if r[&quot;success&quot;]]<br>        <br>        # If we have enough successful primary responses, use them<br>        if len(successful) &gt;= 2:<br>            return self.aggregate_successful_data(successful)<br>        <br>        # If fallback is enabled and primary sources failed, try fallback<br>        if fallback_enabled and len(fallback_sources) &gt; 0:<br>            Context.log(&quot;Primary sources insufficient, trying fallback&quot;)<br>            <br>            fallback_promises = [<br>                Promise.create(source).function_call(&quot;get_data&quot;, {}, 0, 30_000_000_000_000)<br>                for source in fallback_sources<br>            ]<br>            <br>            return Promise.all(fallback_promises).then(<br>                &quot;process_fallback_results&quot;,<br>                {}<br>            ).value()<br>        <br>        return {&quot;success&quot;: False, &quot;message&quot;: &quot;All data sources failed&quot;}</pre><h3>The Mental Model Shift</h3><p>Coming from synchronous blockchains, these patterns require a different way of thinking. Instead of “call and get result,” you’re now “schedule, continue, and process later.”</p><p>This shift is liberating once you embrace it. You start designing applications that are naturally more resilient, more scalable, and more sophisticated than what’s possible with immediate execution models.</p><h3>What’s Next?</h3><p>These patterns are building blocks. The real magic happens when you combine them:</p><ul><li>Use parallel calls to gather data from multiple sources</li><li>Apply batch actions for atomic multi-step operations</li><li>Implement sophisticated error recovery with callback chains</li><li>Build applications that gracefully degrade when some components fail</li></ul><p>The asynchronous nature of NEAR isn’t just a technical detail — it’s a fundamental capability that enables building the next generation of blockchain applications. Applications that don’t just work, but work reliably at scale.</p><p><em>Ready to implement these patterns? Check out the </em><a href="https://github.com/near-examples/cross-contract-calls"><em>complete working examples</em></a><em> with full smart contract code, testing suites, and deployment instructions. The rabbit hole goes deep, and it’s worth the journey.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6905b1e1630" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Cross-Contract Calls in NEAR: Why Asynchronous is Actually Awesome]]></title>
            <link>https://medium.com/@jerrygeorge360/mastering-cross-contract-calls-in-near-why-asynchronous-is-actually-awesome-76d21c096fbf?source=rss-d488cfe4c1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/76d21c096fbf</guid>
            <category><![CDATA[near-protocol]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Jerry George]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 06:08:28 GMT</pubDate>
            <atom:updated>2025-08-31T06:08:28.912Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re coming from Ethereum or other blockchain ecosystems, NEAR’s approach to cross-contract calls might feel foreign at first. But once you understand the “why” behind the design, you’ll appreciate how elegant and powerful it actually is.</p><h3>The NEAR Difference: Why Everything is Asynchronous</h3><p>Unlike most blockchains where contract calls happen synchronously within a single transaction, NEAR operates differently due to its sharded architecture. This isn’t a limitation; it’s a feature that enables massive scalability.</p><p>Here are the two fundamental principles you need to understand:</p><p><strong>Cross-contract calls are independent</strong>: Each contract runs in its own execution environment <strong>Cross-contract calls are asynchronous</strong>: You can’t get immediate results from external calls</p><p>Think of it like sending emails instead of having phone calls. You send your message, continue with other work, and handle the response when it arrives.</p><h3>Three Powerful Patterns for Cross-Contract Interactions</h3><p>NEAR’s asynchronous nature enables three distinct patterns that give you incredible flexibility:</p><h3>1. Batching Actions to a Single Contract</h3><p>When you need to call multiple methods on the same contract, you can batch them together. The beauty here is atomicity; either all actions succeed, or they all get reverted together.</p><pre>Promise.create_batch(&quot;other.testnet&quot;)\<br>       .function_call(&quot;first_method&quot;, {}, 0, 10**12)\<br>       .function_call(&quot;second_method&quot;, {}, 0, 10**12)</pre><p>This is perfect for complex operations that need to maintain consistency across multiple state changes.</p><h3>2. Parallel Calls to Multiple Contracts</h3><p>Need to interact with several contracts simultaneously? NEAR lets you fire off multiple calls in parallel, and failures in one won’t affect the others.</p><pre>Promise.all([<br>    Promise.create(&quot;a.testnet&quot;).function_call(&quot;foo&quot;, {}, 0, 10**12),<br>    Promise.create(&quot;b.testnet&quot;).function_call(&quot;bar&quot;, {}, 0, 10**12)<br>])</pre><p>This pattern is incredibly powerful for creating complex DeFi protocols or multi-contract workflows.</p><h3>3. Handling Callbacks Like a Pro</h3><p>Here’s where NEAR really shines. You can chain actions and handle responses elegantly using callbacks, essential for any meaningful cross-contract interaction.</p><h3>Understanding Promises: Your Gateway to Async Calls</h3><p>In NEAR, a Promise isn&#39;t just a programming concept—it&#39;s a scheduled instruction for the blockchain. Think of it as booking a future appointment that will definitely happen after your current transaction succeeds.</p><p>Here’s a simple example:</p><pre>from nearsdk_py import Promise<br>Promise.create(&quot;other_contract.testnet&quot;).function_call(&quot;do_something&quot;, {}, 0, 10**12)</pre><p>This code doesn’t execute the call immediately. Instead, it schedules it to run after the current transaction completes successfully.</p><h3>Creating Cross-Contract Calls: Two Approaches</h3><p>NEAR gives you two ways to make cross-contract calls, depending on your needs and preferences.</p><h3>The High-Level Approach (Recommended)</h3><p>For most use cases, the high-level Contract API is your best friend:</p><pre>from near_sdk_py import Contract, Context, ONE_TGAS<br># Clean and readable<br>CrossContract(&quot;external_address&quot;).call(<br>    &quot;function_name&quot;,<br>    arg1=&quot;value1&quot;,<br>    arg2=&quot;value2&quot;<br>).then(<br>    &quot;callback_name&quot;,<br>    context_data=&quot;saved_for_callback&quot;<br>).value()</pre><h3>The Low-Level Promise API</h3><p>When you need fine-grained control, the Promise API gives you all the power:</p><pre>from near_sdk_py import Promise<br>Promise.create_batch(&quot;external_address&quot;).function_call(<br>    &quot;function_name&quot;, <br>    {&quot;arg1&quot;: &quot;value1&quot;, &quot;arg2&quot;: &quot;value2&quot;},<br>    amount=0,<br>    gas=5 * ONE_TGAS<br>).then(<br>    Context.current_account_id()<br>).function_call(<br>    &quot;callback_name&quot;,<br>    {&quot;context_data&quot;: &quot;saved_for_callback&quot;}<br>).value()</pre><h3>Mastering Callbacks: Where the Magic Happens</h3><p>Callbacks are where your cross-contract calls come full circle. Here’s how to handle them properly:</p><pre>from near_sdk_py import callback, PromiseResult, Contract<br>class CrossContractExample(Contract):<br>    @callback<br>    def query_greeting_callback(self, result: PromiseResult, additional_context=None):<br>        &quot;&quot;&quot;<br>        This method automatically gets called after your cross-contract call completes.<br>        The @callback decorator handles all the heavy lifting for you.<br>        &quot;&quot;&quot;<br>        if not result.success:<br>            return {<br>                &quot;success&quot;: False, <br>                &quot;message&quot;: &quot;Failed to get greeting&quot;,<br>                &quot;context&quot;: additional_context<br>            }<br>            <br>        # Success! Process the result<br>        return {<br>            &quot;success&quot;: True,<br>            &quot;greeting&quot;: result.data,<br>            &quot;message&quot;: f&quot;Successfully got greeting: {result.data}&quot;,<br>            &quot;context&quot;: additional_context<br>        }</pre><p>The @callback decorator is doing a lot of work behind the scenes:</p><ul><li>Reading promise result data</li><li>Handling serialization and deserialization</li><li>Providing proper error handling</li></ul><h3>The Gotchas: What Every Developer Should Know</h3><p>Here’s where many developers trip up, and understanding these points will save you hours of debugging:</p><h4>Callbacks Always Execute</h4><p>Your callback will run whether the external contract succeeds or fails. This might seem obvious, but it has important implications for your error handling strategy.</p><h4>Manual Rollbacks are Your Responsibility</h4><p>If an external function fails, your callback executes, but any state changes you made in the original call won’t automatically revert. You need to handle this manually:</p><pre>@callback<br>def my_callback(self, result: PromiseResult):<br>    if not result.success:<br>        # The external call failed - handle cleanup<br>        # Refund users if you attached NEAR tokens<br>        # Revert any state changes you made<br>        self.handle_failure_cleanup()<br>        return<br>    <br>    # Process successful result<br>    self.handle_success(result.data)</pre><h4>Gas and Token Management</h4><p>When your contract attaches NEAR tokens to a cross-contract call and that call fails, those funds return to your contract — not to the original caller. Make sure your callback handles refunds appropriately.</p><h3>Real-World Example: Building a Multi-Contract Workflow</h3><p>Let’s put it all together with a practical example:</p><pre>contract_a = CrossContract(self.contract_a)<br>promise_a = contract_a.call(&quot;method_a&quot;)<br>contract_b = CrossContract(self.contract_b)  <br>promise_b = contract_b.call(&quot;method_b&quot;)<br>combined_promise = promise_a.join(<br>    [promise_b],<br>    &quot;multi_contract_callback&quot;,<br>    contract_ids=[self.contract_a, self.contract_b]<br>)<br>return combined_promise.value()</pre><p>This pattern lets you coordinate between multiple contracts and handle all their responses in a single callback.</p><h3>Why This Design is Brilliant</h3><p>At first glance, NEAR’s asynchronous approach might seem more complex than synchronous calls. But consider the benefits:</p><ul><li><strong>Scalability</strong>: Sharded execution means your calls don’t compete for the same resources</li><li><strong>Flexibility</strong>: You can design sophisticated workflows that would be impossible in synchronous systems</li><li><strong>Reliability</strong>: Failed calls in one contract don’t cascade failures to others</li><li><strong>Performance</strong>: Parallel execution means faster overall transaction processing</li></ul><h3>Getting Started: Your Next Steps</h3><p>Ready to start building with cross-contract calls? Here’s what I recommend:</p><ol><li><strong>Start simple</strong>: Begin with basic single-contract calls to get comfortable with Promises</li><li><strong>Practice callbacks</strong>: Build a simple contract that calls another and processes the result</li><li><strong>Experiment with patterns</strong>: Try batching, parallel calls, and complex callback chains</li><li><strong>Handle edge cases</strong>: Always plan for failures and implement proper cleanup logic</li></ol><p>The asynchronous nature of NEAR might require a mental shift, but once you embrace it, you’ll find it opens up possibilities that simply aren’t available on other platforms.</p><p><em>Want to dive deeper into NEAR development? The patterns covered here are just the beginning. Cross-contract calls are the foundation for building sophisticated DeFi protocols, complex dApps, and innovative blockchain solutions that leverage NEAR’s unique sharded architecture.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76d21c096fbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Array vs Hashmap]]></title>
            <link>https://medium.com/@jerrygeorge360/array-vs-hashmap-95dfed63dccc?source=rss-d488cfe4c1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/95dfed63dccc</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Jerry George]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 20:56:59 GMT</pubDate>
            <atom:updated>2025-03-15T20:56:59.872Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>When it comes to storing data and managing data , arrays and hashmaps are two of the most popular data structures. Both serve different purposes and have their own tradeoffs. In this article, since we would be making use of the python programming language, the concept of these data structure is equally the same in any other dynamic language such as Javascript.</p><p>An Array is a linear data structure where all elements are arranged sequentially. It is a collection of elements of <strong>same data type</strong>( for static languages)<strong> </strong>stored at <strong>contiguous memory locations</strong>.</p><p>A hashmap (also known as a dictionary in Python) is a key-value store that provides fast lookup, insertion, and deletion operations by leveraging a hashing function.</p><p>Choosing between an array and a hashmap depends on several factors, including time complexity, space efficiency, and the type of operations required. In this article, we will dive deep into how they work, compare their performance, and explore when to use one over the other.</p><h3><strong>Array</strong></h3><p>As previously stated above,an Array is a linear data structure where all elements are arranged sequentially. It is a collection of elements of <strong>same data type</strong>( for static languages)<strong> </strong>stored at <strong>contiguous memory locations</strong>.</p><p>In python programming language, there is no in built array but there are different ways array can be created.</p><ol><li>List(inbuilt)</li><li>numpy array</li><li>through the array module</li></ol><h4><strong>Types of array</strong></h4><ol><li>Static Array (Fixed size, e.g., array module in Python, C arrays).</li><li>Dynamic Array (Resizable, e.g., Python list, Java arraylist).</li></ol><p>Static Array: An array with a fixed size, determined at the time of its creation, and cannot be resized or modified in terms of its length after that.</p><p>Dynamic Array: An array that can grow or shrink in size during runtime, allowing elements to be added or removed as needed.</p><p>There are key words that would need explanations</p><h4><strong>Contiguous memory locations</strong></h4><p>Contiguous memory allocation refers to the allocation of a single, uninterrupted block of memory to a process or program. In this scheme, a process occupies a series of adjacent memory locations, enabling fast and direct access to data. This stands in contrast to non-contiguous memory allocation, where a process can be scattered across various locations in the memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*E0nOlTVQteMYvRUX1vGvKQ.png" /></figure><pre>arr = [10, 20, 30, 40, 50]<br><br>print(&quot;Array memory location:&quot;, id(arr))<br><br>for i, value in enumerate(arr):<br>    print(f&quot;Memory location of arr[{i}] ({value}):&quot;, id(value))</pre><pre>import numpy as np<br><br>arr = np.array([10, 20, 30, 40, 50])<br>print(&quot;NumPy array:&quot;, arr)<br>print(&quot;Memory address of the array:&quot;, arr.__array_interface__[&#39;data&#39;][0])<br><br>for i in range(len(arr)):<br>    print(f&quot;Memory location of arr[{i}] ({arr[i]}):&quot;, id(arr[i]))</pre><p>In the above code snippets , in the first one which was implemented by a list we were expecting to see a memory address that is in a sequential manner but lists are implemented in an abstract way with the elements being objects. This is as a result of a list being able to store different data types.</p><p>while in the second code snippet,the array is seen to be truly contiguous, it can only store one data type at a time.</p><h4><strong>Time and space complexity of a dynamic array</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cP3y3E6yQxZTs8CB4NNN0A.png" /></figure><h4>Time Complexity of an Array:</h4><ul><li><strong>Access (Read/Write)</strong>: <strong>O(1)</strong> — Accessing or modifying an element by index is very fast (constant time).</li><li><strong>Search</strong>: <strong>O(n)</strong> — Searching for an element might require checking every item.</li><li><strong>Insert/Delete (at the end)</strong>: <strong>O(1)</strong> — Adding or removing an element at the end is fast.</li><li><strong>Insert/Delete (beginning or middle)</strong>: <strong>O(n)</strong> — Inserting or removing an element at the start or middle requires shifting other elements.</li></ul><h4>Space Complexity of an Array:</h4><ul><li><strong>O(n)</strong> — The space it takes up is proportional to the number of elements in the array.</li></ul><h4><strong>Where arrays are used</strong></h4><ul><li>Implementing stacks and queues.</li><li>Storing <strong>sequential</strong> data like time-series values.</li><li>Graphics processing (storing pixel data).</li></ul><h4>Advantages of Arrays</h4><ul><li>Fast <strong>random access</strong> (O(1) indexing).</li><li>Memory-efficient for storing large datasets.</li><li>Better for sequential data processing.</li></ul><h4>Disadvantages of Arrays</h4><ul><li>Slow insertions/deletions at arbitrary positions (O(n)).</li><li>Fixed size (in static arrays).</li><li>Searching is O(n) unless sorted (binary search reduces it to O(log n)).</li></ul><h3>Hashmaps</h3><p>A hashmap is a key-value store that provides fast lookup, insertion, and deletion operations by leveraging a hashing function. In python programming language a hashmap is implemented by using a dictionary.</p><h4>The hashing function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*dkbfVkipOk4TSsfrre8Jqg.png" /></figure><p>A<strong> </strong>hashing function converts an input (like a key) into a fixed-size value, often an integer, which represents that input. It is used in data structures like <strong>hash tables</strong> to efficiently store and retrieve data.</p><h4>Key Points:</h4><ul><li><strong>Deterministic</strong>: Same input always gives the same output.</li><li><strong>Fast</strong>: The function should be efficient.</li><li><strong>Uniform Distribution</strong>: Outputs should be spread evenly to minimize <strong>collisions</strong> (different inputs giving the same output).</li><li><strong>Minimizes Collisions</strong>: Reduces the chance of two different inputs producing the same hash.</li></ul><p>In <strong>hash tables</strong>, a hash function calculates an index where data is stored, allowing for quick lookups and modifications<strong>.</strong></p><p><strong>Implementation</strong></p><pre>class HashTable:<br>    def __init__(self):<br>        self.MAX = 100  # Size of the hash table<br>        self.arr = [[] for _ in range(self.MAX)]  # Each index points to a list (for chaining)<br><br>    def get_hash(self, key):<br>        h = 0<br>        for char in key:<br>            h += ord(char)<br>        return h % self.MAX  # Hash value modded by array size for index<br><br>    def add(self, key, val):<br>        h = self.get_hash(key)<br>        # Check if key already exists at the hashed index<br>        for idx, element in enumerate(self.arr[h]):<br>            if element[0] == key:<br>                self.arr[h][idx] = (key, val)  # Update value if key is found<br>                return<br>        self.arr[h].append((key, val))  # Add new key-value pair to the list<br><br>    def get(self, key):<br>        h = self.get_hash(key)<br>        # Search for the key in the chain<br>        for element in self.arr[h]:<br>            if element[0] == key:<br>                return element[1]<br>        return None  # Return None if key not found<br><br>    def __setitem__(self, key, value):<br>        self.add(key, value)  # Adding a key-value pair<br><br>    def __getitem__(self, key):<br>        return self.get(key)  # Retrieving value for the key<br><br>    def __delitem__(self, key):<br>        h = self.get_hash(key)<br>        # Find and remove the key-value pair from the chain<br>        for idx, element in enumerate(self.arr[h]):<br>            if element[0] == key:<br>                del self.arr[h][idx]<br>                return<br>        raise KeyError(f&quot;Key &#39;{key}&#39; not found.&quot;)<br><br># Testing the hash table<br>a = HashTable()<br>a.add(&#39;jerry&#39;, &#39;ultimate&#39;)<br>a.add(&#39;jerry&#39;, &#39;changed&#39;)  # Update value for the existing key<br>a.add(&#39;john&#39;, &#39;doe&#39;)<br><br># Using __setitem__ and __getitem__ (like dictionary syntax)<br>a[&#39;alice&#39;] = &#39;wonderland&#39;<br>print(a[&#39;alice&#39;])  # Output: wonderland<br><br># Display the hash table contents<br>print(a.arr)<br><br># Deleting an item<br>del a[&#39;john&#39;]<br>print(a.arr)</pre><h4>Time and space complexity</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozkTkjOn-6F1jw9LcVU2pQ.png" /></figure><ol><li><strong>Access (Lookup)</strong>: <strong>O(1)</strong> (average)</li></ol><p>In the best case, the hash function distributes keys evenly across the table, so finding a key requires constant time. However, in the worst case (with many collisions), it can degrade to <strong>O(n)</strong>, where n is the number of elements in the table.</p><p><strong>2. Insertion</strong>: <strong>O(1)</strong> (average)</p><p>Inserting a key-value pair usually takes constant time, as long as there are no significant collisions. If there are collisions, it may require searching through a chain (linked list or another structure) at that index.</p><p><strong>3. Deletion</strong>: <strong>O(1)</strong> (average)</p><p>Deleting a key is generally a constant-time operation, as long as it is directly found at the hashed index. With collisions (like in chaining), it may require searching through the list at that index.</p><p><strong>4. Worst-case (with collisions)</strong>:</p><p><strong>O(n)</strong>: If many collisions occur (e.g., all elements hash to the same index), operations could degrade to linear time.</p><h4>Space Complexity of a HashMap:</h4><p><strong>O(n)</strong>:The space complexity is proportional to the number of elements n stored in the hash map. It requires an array or list of size m (where m is the table size), and each bucket can contain multiple elements in case of collisions. Thus, the space is mainly determined by the number of stored key-value pairs.</p><h4>Usage of the hashmap</h4><ul><li>Caching (e.g., LRU Cache).</li><li>Storing user sessions in web applications.</li></ul><h4>Advantages of HashMaps</h4><ul><li>Fast lookups (O(1) on average).</li><li>Flexible key-value storage.</li><li>Ideal for applications where search and retrieval are frequent.</li></ul><h4>Disadvantages of HashMaps</h4><ul><li>Consumes more memory (extra space for hashing, keys, and collision handling).</li><li>No order guarantee</li><li>Performance degrades to O(n) in case of too many collisions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95dfed63dccc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HOW TO USE JAVASCRIPT TO RECORD AND PLAY AUDIO IN THE BROWSER.]]></title>
            <link>https://medium.com/@jerrygeorge360/how-to-use-javascript-to-record-and-play-audio-in-the-browser-753bf3f16572?source=rss-d488cfe4c1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/753bf3f16572</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[browser-api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[getusermedia]]></category>
            <dc:creator><![CDATA[Jerry George]]></dc:creator>
            <pubDate>Sun, 21 Aug 2022 13:17:24 GMT</pubDate>
            <atom:updated>2022-08-21T13:43:52.253Z</atom:updated>
            <content:encoded><![CDATA[<p>Accessing the microphone in your device and then storing the recorded audio through the web browser could be very tasking. This article is written to simplify the process and to properly explain certain concepts.</p><blockquote>THE STEPS YOU SHOULD KNOW:</blockquote><blockquote>1. ACCESSING THE STREAM.</blockquote><blockquote>2. CAPTURING THE STREAM.</blockquote><blockquote>3. PROCESSING THE STREAM.</blockquote><blockquote>4. PLAYING THE STREAM.</blockquote><p><strong>ACCESSING THE STREAM.</strong></p><p>The browser contains the necessary toolset to easily record and play audio, there is no need for a third-party library. The browser has several APIs that have different functionalities. Here is a the link to see the several API that the web browser has <a href="https://developer.mozilla.org/en-US/docs/Web/API">https://developer.mozilla.org/en-US/docs/Web/API</a>. To access the microphone we make use of the window.navigator,the window navigator contains several details about the browser.</p><blockquote>The windows.navigator contains several methods,and one of those methods we can use to access the microphone is the getUserMedia().</blockquote><p>The getUserMedia method is responsible for the permission grant and it is a promise which resolves into a stream. The stream either video or audio stream would now be accessible for you to capture and process.</p><blockquote>Side-note: Computers can not process continuous analog signals, hence it has to convert them to a digital signal into an array of 1’s and 0’s, those 1’s and 0’s are called array buffers. Hence this stream is a sequence of array buffers.</blockquote><p>The getUserMedia method has an optional parameter that requires an object to be passed,this parameter is just to tell it whether the audio or video device would be accessed or both.The values are Boolean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_ccVJtJW1zMfIIFjS-XUA.png" /></figure><p><strong>Capturing the stream.</strong></p><p>Just like how the getUserMedia it main purpose is to access the streamof data being generated by the streaming device(microphone).</p><p>The job of the media recorder API is to capture the data. And it is very easy to set up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTeFz7rBhfWXralFCax_-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfyJaBqc3Zc0gZtBIsjpDQ.png" /></figure><p>There are series of methods that the media recorder api have, the most important methods are:</p><p>Start() and stop()</p><p>The ondataavailable is an important event.</p><p>The start() method would start the recording.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*Vr-F8Rcgbkjvm9Lf7IhUFg.png" /></figure><p>The stop() method would stop the recording.</p><p>The ondataavailable is where the actual data capturing takes place. Remember that the getUserMedia resolves a promise which is a stream of data(an audiobuffer) hence we call this event to tell the browser what to do if there is data available in the stream ,since this is a real time event we have to actually process and capture the data as soon as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2IeWuKJuUPmcp_caYu8sIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQlojwpcMYVuktpEW3fKPw.png" /></figure><p>Having said that the stream being resolved by the promise are sequence of 1’s and 0’s we can store it in an array. Hence in the ondataavailable event we would append the stream of data into an array.</p><p><strong>PROCESSING THE STREAM</strong></p><blockquote>Side note: A blob is a holder of data. It is a data type that stores binary data. In JavaScript a blob requires two arguments the first argument is an array of the stream of data or data and then the second argument is the name of data type in an object.</blockquote><p>We now have our stream stored in an array,so we would put it inside a blob.The aim is to create an audio file. As discussed above the Blob requires two argument</p><p>1 an array of data</p><p>2 a file type</p><p>We put the array of captured data in the Blob first argument and then specify the type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zq_QPCToQ-UI9FTteZhIhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUN9wE_dYDiKoQMJ6QD4nQ.png" /></figure><p>After the processing stage we need to be able to play what we recorded we are going to use the audio tag as a medium to play the recordings.</p><p><strong>PLAYING THE STREAM</strong></p><p>We all know that the HTML audio tag have the src attribute which takes the path of the audio file (the path of the audio file points to the actual audio file). But in this case our audio object is not a file but a blob hence we need a way to generate a string which would point to the blob created. Luckily for us the windows have a property to that . That property is called URL.createObjectURL() it requires one argument which is the blob object. Now we have created the source we need to assign it to the src attribute and now we can play our audio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhTl_TnFQ4v_qpOO6cda-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbQ0avJDCHKfdBAC2gFCoA.png" /></figure><p>To stop the audio we would use the stop method.</p><p><strong>DEMO:ACCESSING THE STREAM,CAPTURING ,PROCESSING THE STREAM,PLAYING THE STREAM.</strong></p><p>I created a little demo. Link below.</p><p><a href="https://webrecorder.netlify.app/">Document</a></p><p>To be able to access the full code you can get the source code at :</p><p><a href="https://github.com/jerrygeorge360/jbotrex-web-recorder">GitHub - jerrygeorge360/jbotrex-web-recorder: This is a web recorder built with the media device and mediarecorder api&#39;s.</a></p><figure><img alt="html file" src="https://cdn-images-1.medium.com/max/1024/1*otSoub703foHuYlb-H2efQ.png" /></figure><figure><img alt="css file" src="https://cdn-images-1.medium.com/max/1024/1*1ewDyuP6CMZhHd5Q1SzeOQ.png" /></figure><figure><img alt="javascript file" src="https://cdn-images-1.medium.com/max/1024/1*Cl3UXJwBbB9oRuU3ld80AQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=753bf3f16572" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>