<?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 Satyam Agrawal on Medium]]></title>
        <description><![CDATA[Stories by Satyam Agrawal on Medium]]></description>
        <link>https://medium.com/@satyam0499?source=rss-61cd7d3a6004------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*w75hg3xafJ6tGP6H.</url>
            <title>Stories by Satyam Agrawal on Medium</title>
            <link>https://medium.com/@satyam0499?source=rss-61cd7d3a6004------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:41:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@satyam0499/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[Simplifying Smart Contract Testing with the Cadence Test Framework]]></title>
            <link>https://medium.com/@satyam0499/simplifying-smart-contract-testing-with-the-cadence-test-framework-9a5d4a62f6ab?source=rss-61cd7d3a6004------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a5d4a62f6ab</guid>
            <category><![CDATA[testing-framework]]></category>
            <category><![CDATA[cadence]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[flow]]></category>
            <dc:creator><![CDATA[Satyam Agrawal]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 10:25:32 GMT</pubDate>
            <atom:updated>2023-02-08T10:25:32.605Z</atom:updated>
            <content:encoded><![CDATA[<p>Greetings, fellow innovators, students, and visionaries! This piece is a testament to my journey of discovery with the Cadence Test Framework. <a href="https://developers.flow.com/cadence/language">Cadence</a>, a language designed to craft secure smart contracts on the Flow blockchain, has been my companion on this adventure. After spending some time exploring the Flow ecosystem, I feel inspired to share my insights with the community. This is my maiden voyage in doing so, and I’m eager to share my newfound knowledge.</p><p>This article is crafted for those who already possess a fundamental understanding of writing smart contracts in the Cadence programming language. If you are a beginner seeking to deepen your knowledge of Cadence, I recommend exploring <a href="https://developers.flow.com/cadence/tutorial/01-first-steps">these</a> resources.</p><h3>Why Cadence Test Framework?</h3><p>The Cadence Test Framework presents a novel approach to writing test cases for smart contracts written in Cadence. Before the Cadence Test Framework, developers had to be proficient in either JavaScript or Go-Lang to write test cases. This new framework, however, offers a solution for developers who may not have expertise in either of these languages. In the rapidly advancing technological world, it is common for developers to have proficiency in multiple languages, but not every developer may possess these skills. Thus, it’s important to have a framework that enables developers to write test cases directly in the Cadence language.</p><p>The Cadence Test Framework holds the key to unlocking the full potential of the Cadence smart contract programming language. By streamlining the testing process, it reduces the barriers to entry for developers and allows them to concentrate solely on mastering Cadence. This, in turn, accelerates the adoption of Cadence and makes it easier for developers to create secure and reliable smart contracts.</p><h3>How to write tests using Cadence Test Framework?</h3><p>Let’s begin with the preparations.</p><p><strong>Setup</strong></p><p>Developers should use the flow-cli version v0.41.0 or above. To instal or upgrade the flow-cli, follow the guidelines <a href="https://developers.flow.com/tools/flow-cli/install">here</a>.</p><p>After installation or upgrade of flow-cli, make sure cli offers flow test command. It can be verified by running the below command</p><pre>flow test --help</pre><p>, and the output would look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRjhzijte2vzMc3JwRU5RQ.png" /><figcaption>snapshot_1</figcaption></figure><p>While the recommended directory structure to put the cadence test cases is below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*4HKPuWPfElkTeJO84D4jpg.png" /><figcaption>snaptshot_2</figcaption></figure><p>It is recommended that if the name of the contract to be tested is Abc.cdc, then the corresponding test file should be named Abc.cdc. However, it should be noted that the Cadence Test Framework does not impose any restrictions on the naming convention for test files, and developers are free to choose a name of their preference. Above Offers is the contract name that gets tested.</p><p>The mocks directory serves as a repository for transactions, scripts, and contracts that cannot be stored in the root transactions, scripts, and contracts directory. To facilitate successful testing, developers may require transactions that are not directly related to the test contract, such as setup_account_to_receive_fungible_token.cdc. It is advisable to keep these types of transactions within the mocksdirectory.</p><p>Now let’s make our hands dirty.</p><h4><strong>Write Tests</strong></h4><p>Before writing tests, it is necessary to complete basic setup procedures, including establishing accounts and deploying contracts, to execute test cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZKsxsE2BnUo5nAWgB0snA.png" /><figcaption>snapshot_3</figcaption></figure><p>Let’s decode the above code line by line and understands it together.</p><p>Line 1</p><pre>import Test</pre><p>The Test smart contract is an integral component for writing test cases in Cadence. It provides the necessary building blocks for creating test cases and writing tests in Cadence. Without the Test contract, it would be impossible to write test cases.</p><p>Line 3</p><pre>pub var blockchain = Test.newEmulatorBlockchain()</pre><p>The statement mentioned above is used to create a new instance of a blockchain environment that simulates the flow emulator network and facilitates the execution of transactions and scripts. Technically, it is a struct datatype that offers blockchain-related functions, such as createAccount and addTransaction. For more information on these technical aspects, please refer to <a href="https://developers.flow.com/cadence/testing-framework#blockchain">this</a>.</p><p>Line 6 to 8</p><pre>// Setup accounts.<br>pub let signer = blockchian.createAccount()<br>pub let offers = blockchain.createAccount()<br>pub let coreContractsAccount = blockchain.createAccount()</pre><p>The creation of accounts is a fundamental requirement to execute various actions such as transaction execution, smart contract deployment, and script execution. In the code presented, two type of accounts have been established: one for the signer and another for the smart contracts where it get deployed. The account designated for the Offers contract is referred to as offers, while the account designated for the deployment of core contracts, including FungibleToken, NonFungibleToken, MetadataViews, among others, is referred to as coreContractsAccount. This arrangement facilitates the testing process.</p><p>createAccount is the inbuilt function in the blockchain instance and it provides Account struct as return value.</p><pre>/// Account represents info about the account created on the blockchain.<br>///<br>pub struct Account {<br>    pub let address: Address<br>    pub let publicKey: PublicKey<br>}</pre><p>Line 10</p><pre>pub fun setup() { }</pre><p>The setup function is automatically invoked when the test file is executed. It serves as the initial point of orchestration for the test cases, executing tasks such as configuring the test environment and deploying smart contracts.</p><p>Line 12 to 15</p><pre>// Let the CLI know how the above addresses are mapped to the contracts.<br>blockchain.useConfiguration(Test.Configuration({<br>  &quot;CoreContractsAccount&quot;: coreContractsAccount.address,<br>  &quot;Offers&quot;: offers.address<br>})</pre><p>In Cadence projects, a common practice is to declare file locations as imports and to designate network-specific addresses in the Flow CLI configuration file. When crafting tests for such a project, it may also be necessary to specify addresses utilized during the testing process. However, as accounts are dynamically created, and addresses are generated dynamically during testing, statically specifying addresses in a configuration file is not feasible.</p><p>To address this, the test framework uses the useConfiguration(_ configuration: Test.Configuration function within the Blockchain, enabling the specification of addresses for testing purposes.</p><p>Line 17 to 19</p><pre>deploySmartContract(&quot;FungibleToken&quot;, coreContractsAccount, &quot;../../../contracts/core/FungibleToken.cdc&quot;)<br>deploySmartContract(&quot;NonFungibleToken&quot;, coreContractsAccount, &quot;../../../contracts/core/NonFungibleToken.cdc&quot;)<br>deploySmartContract(&quot;Offers&quot;, offers, &quot;../../../contracts/Offers.cdc&quot;)</pre><p>The declaration, as mentioned earlier, is employed to instate the contracts at a specified address, as demonstrated in the deployment of the FungibleToken at the coreContractsAccount. The code for the FungibleToken is obtained from its file path, i.e. ../../../contracts/core/FungibleToken.cdc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kl5ws5Lgzu21ilkw-WmpJw.png" /><figcaption>snapshot_4</figcaption></figure><p>The utility function deploySmartContract was created to facilitate the deployment of contracts. This function utilizes the built-in functions, Test.readFile, to retrieve the contract from the given file path and blockchain.deployContract to deploy the contract to the network.</p><p>Let’s write some tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGllV8Jn0ab9YMJ0aa2W8A.png" /><figcaption>snapshot_5</figcaption></figure><p>In the Cadence test framework, each test case is represented as a function and must be prefixed with the word test to be recognized as a valid test case by the Test Framework. It is advisable to give descriptive names to these test functions, allowing readers to gain an understanding of the intended outcome of the test simply by reading its name.</p><p>It is not feasible to examine every line of the test case in detail. However, I attempt to provide a comprehensive understanding of certain functions utilized within the test.</p><p>I’ve used the prefix execute to refer to functions that generate and submit transactions on the test network, while the prefix get refers to functions that execute scripts and retrieve data from the chain. While this distinction is not strictly necessary, I have used it here for clarity and ease of understanding.</p><p>Creating accounts for performing actions within the test case occurs from lines 3 to 7. Then, from lines 10 to 13, the function executeSetupVaultAndMintTokenTx is called to set up a FungibleToken Vault for the designated account and mint the corresponding tokens. This function serves as a helper, which I have created. But, a deeper examination of it is unnecessary as the following function, executeCreateOfferTx, encompasses much of the relevant technical knowledge.</p><p>At line 15 executeCreateOfferTx a function is used to execute propose_offer.cdc transaction. It is a helper function used to submit the transaction and validate whether it was successfully executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjCbV32LjANBJyFneAn2SA.png" /><figcaption>snapshot_6</figcaption></figure><p>In line 14 of snapshot_6, the contents of the propose_offer.cdc file are retrieved and passed along with the signer of the transaction as signer and a set of parameters contained within lines 18 to 27 to the txExecutor function. The parameters are necessary to execute the transaction, while the expectedError and expectedErrorType are passed as nil, as indicated in snapshot_5. These two parameters will be discussed in further detail in a subsequent section.</p><p>Let’s look at txExecutor function closely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UT-fFGeo0PvsKbgGRe-Ig.png" /><figcaption>snapshot_7</figcaption></figure><p>In snapshot_7, the creation of a transaction with necessary parameters occurs from lines 3 to 8. blockchain.executeTransaction function facilitates the execution of the created transaction instance at line 10. The absence of automatic handling of transaction failure, as offered by Js testing libraries through the shallRevert function, in the Cadence Test Framework, requires explicit handling of the txResult.error. This enables the crafting of test cases for failures by trimming the error message to align with the expectedErrorparameter, providing a mechanism for writing failure tests like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FaDtxw5VlZv_SEz30fwLlg.png" /><figcaption>snapshot_8</figcaption></figure><p>In snapshot_8, at line 14, the expected error message is passed to enable comparison with the error returned by the transaction in the txExecutor function. The success of the test case depends on the match of the expected error. Line 15 specifies the error type, as each error returned by the transaction has a unique starting point for the actual error statement. Developers can determine this by counting the number of characters in the error trace.</p><p>The function in snapshot_9 comprises the initial index of the error statement for the test cases I composed. In snapshot_7, line 14 employs the same function to extract the starting index of the error statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*peyNvojuYeCxCLRJK6guOA.png" /><figcaption>snapshot_9</figcaption></figure><p>In snapshot_5, following the successful execution of the executeCreateOfferTx function at line 15, the next step involves verifying the state changes. To accomplish this, assertions have been made in lines 32 and 33. Furthermore, in lines 30 and 31, getOfferId and getOfferDetails functions have been invoked, which utilize scripts internally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TNn_wFppBPt5mGc4FxiVQ.png" /><figcaption>snapshot_10</figcaption></figure><p>In snapshot_10, it is evident that getOfferId and getOfferDetails functions utilize the scriptExecutor function, which consumes a hardcoded script path along with the necessary parameters. The result of the script execution is then forcibly cast to the expected type via the use of the as and ! operators.</p><p>While below snapshot shows the implementation of the scriptExecutor helper function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSDexua6dCAIZ2o8ESCUbQ.png" /><figcaption>snapshot_11</figcaption></figure><p>The script is read using Test.readFile and executed through blockchain.executeScript, which requires the script code and necessary arguments. If the script throws an error, the assertion will fail. Otherwise, the scriptResult.returnValue will be returned.</p><p>Now we would run the test case that we have built using the below command</p><pre>flow test -l &quot;info,error&quot; ./lib/cadence/test/Offers.cdc</pre><p>and return output should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWum70fddq9qOQdyC5b1Nw.png" /><figcaption>snapshot_12</figcaption></figure><p>Readers can learn more by looking into the actual test file <a href="https://github.com/onflow/Offers/blob/offers-implementation/lib/cadence/test/Offers.cdc">here</a>.</p><p>In conclusion, we have thoroughly examined the test case presented in snapshot_5, and I hope that this journey has provided insight into the workings of the Cadence Test Framework and inspired developers to write tests in the Cadence language.</p><h3>Last Remarks</h3><p>The Cadence Test Framework is in its early stages of development, making it likely to experience various changes and improvements over time. While it is not necessarily the best testing framework for Cadence smart contracts, it is a fast option worth exploring. Expect to see more advancements in this framework as it continues to evolve. Some open tasks are mentioned <a href="https://github.com/onflow/cadence/issues/1889">here</a>.</p><p>Thanks to <a href="https://medium.com/u/a3de1bbaef3b">Supun Setunga</a> for developing a fantastic Test Framework and helping me to understand its working.</p><p>Stay tuned for further insights into the realm of blockchain technologies. This year, I aim to bring a wealth of content to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a5d4a62f6ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Extensions — Polymath and Parity Technical Engagement]]></title>
            <link>https://medium.com/polymathnetwork/smart-extensions-polymath-and-parity-technical-engagement-dfb81ecbd6f0?source=rss-61cd7d3a6004------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfb81ecbd6f0</guid>
            <category><![CDATA[polymesh]]></category>
            <category><![CDATA[security-token]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-extension]]></category>
            <category><![CDATA[tech-blog]]></category>
            <dc:creator><![CDATA[Satyam Agrawal]]></dc:creator>
            <pubDate>Tue, 18 Feb 2020 19:50:04 GMT</pubDate>
            <atom:updated>2020-02-18T19:50:04.310Z</atom:updated>
            <content:encoded><![CDATA[<h3>Smart Extensions — Polymath and Parity Technical Engagement</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MYhUyF_9-aqSPGrxq3LDIQ.png" /></figure><p>Polymath is building a purpose-built blockchain for securities — <a href="https://polymath.network/polymesh-whitepaper">Polymesh</a>. We learned about the strength and power of combining smart contracts and a modular approach on the Ethereum blockchain (<a href="https://github.com/PolymathNetwork/polymath-core">Polymath core</a>) and are introducing smart extensions on Polymesh as an analogous concept. Smart extensions are the backbone of security tokens on Polymesh, giving issuers the ability to program specific rules into their security tokens, whilst executing actions in a standardized way to satisfy an issuer’s need for functionality and regulators’ requirements for compliance.</p><p>More technically a smart extension in Polymesh is a smart contract, deployed as a WASM blob to the blockchain, which can be referenced by assets in Polymesh. This allows users of Polymesh to extend the functionality of their assets, for example for compliance or settlement purposes, whilst still leveraging the standardized financial primitives used for assets and identity.</p><p>This blog will talk about the technical challenges we faced for the seamless interoperability of smart extensions with runtime logic and the solutions we came up with while working closely working with the Parity team. If you want to learn more about the business aspects of Polymesh’s financial primitives and how smart extensions help issuers add an extra layer of financial logic over their assets, please read through<a href="https://blog.polymath.network/polymesh-flexibility-through-smart-extensions-c461f1504ce9"> this awesome article</a> or the <a href="https://polymath.network/polymesh-whitepaper">Polymesh Whitepaper</a>.</p><h3>Challenges faced</h3><p>Polymath is leveraging the <a href="https://github.com/paritytech/substrate">Substrate</a> Framework to build the <a href="https://github.com/PolymathNetwork/polymesh">Polymesh</a> blockchain which provides great flexibility to use different pallets developed and maintained by the Parity team. One of these is <a href="https://github.com/paritytech/substrate/tree/master/frame/contracts">pallet_contracts</a> that will facilitate the smart contract functionality being built-in Polymesh.</p><p>When we decided to add smart extension functionality in Polymesh, pallet-contracts was missing certain functionality that Polymesh needed to make runtime and smart contract interoperability seamless — a key requirement for smart extensions. Polymath decided to expedite the development of the pallet_contractsmodule and specifically rich interactions between runtime modules and smart contracts, by collaborating with the Parity team with their deep expertise in Substrate. The fruits of this engagement have been integrated back into the main Substrate codebase, so they are available for the community as well. We believe this type of functionality, that combines the extensive control and standardization of runtime modules, with the flexibility of dynamically deployed smart contracts, will ease the life of many projects who are planning to add pallet-contracts to their runtime.</p><p>A very brief headline of the functionalities that’s been added during the technical engagement between Polymath &amp; Parity.</p><ol><li>The ability to query runtime module storage items from smart contracts.</li><li>The ability to call a smart contract function from a runtime module.</li><li>The ability to read smart contract storage from a runtime module.</li></ol><h3><strong>Technical Deep Dive</strong>—</h3><ul><li><strong>Query runtime module storage from a smart contract.</strong></li></ul><p>pallet-contractsis a runtime module that is used to sandbox the smart contract functionality. At runtime level, every runtime is following the same standard procedure of reading/writing the runtime variables in storage that will allow any runtime or sub-module to read other runtime or sub-module storage by using the standard way of reading the runtime storage variables.</p><p>Every piece of data is stored in the key-value fashion in the Substrate framework. The key can be derived as:</p><p><strong>Singelton variable</strong> -&gt; Twox128(module_prefix) ++ Twox128(storage_prefix)</p><p><strong>Mapping</strong> -&gt; Twox128(module_prefix) ++ Twox128(storage_prefix) ++ Hasher(encode(key))</p><p>eg -</p><pre>// This module&#39;s storage items.</pre><pre>decl_storage! {</pre><pre>   trait Store for Module&lt;T: Trait&gt; as TemplateModule {</pre><pre>   // Just a dummy storage item.</pre><pre>   // Here we are declaring a StorageValue, `Something` as a   Option&lt;u32&gt;</pre><pre>   // `get(fn something)` is the default getter which returns either the stored `u32` or `None` if nothing stored</pre><pre>  Something get(fn something): Option&lt;u32&gt;;<br>  FooStore get(fn foo): Option&lt;Foo&gt;;</pre><pre>}}</pre><p>In the above code,</p><p>module_prefix = TemplateModule,</p><p>storage_prefix = Something</p><p>hence, Key for accessing the Something variable from the runtime storage is: Twox128(TemplateModule)++ Twox128(Something). where Twox128 is a hashing technique used to calculate 128-bit hash &amp; ++ represent the concatenation of the two hashes.</p><p>Leveraging the same technique Parity introduces a wrapper function i.e <a href="https://github.com/paritytech/ink/blob/6fd834d0f2c41432b897b89a3f9d7a40b619855f/core/src/env2/env_access/immutable.rs#L329">get_runtime_storage</a>() in env_access of ink! — is an <a href="https://wiki.haskell.org/Embedded_domain_specific_language">eDSL</a> to write WebAssembly based smart contracts— that will take the storage key whose data need to read.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d2cd0d4e17e350613e4d7e41987559f/href">https://medium.com/media/9d2cd0d4e17e350613e4d7e41987559f/href</a></iframe><p>In the above code snippet, lines 8–11 represent the calculation of the key as we did above, at line 15 we are calling get_runtime_storage() function to access the runtime storage by providing the calculated key &amp; lines 16–26 represent the error handling &amp; output decoding using Parity Scale codec.</p><p><strong>Note-</strong> <em>If smart contract wants to read custom type variables then that type should derive parity scale encoding &amp; decoding properties.</em></p><p>Using this functionality any Polymesh based smart extension can access the runtime storage and act accordingly. For example to know whether a compliance rule is valid or not. The contract needs to access asset holder balance, the total supply of the asset and so on.</p><p><strong>Trick to create dynamic getter function for the runtime </strong>😉</p><p>We can read the storage of the runtime from outside of blockchain by using state RPC function get_storage() but there is no way to add a filtration layer over that data dynamically. Anyone can use the above functionality to create the filtration layer over data using the stateless smart contract and use newly introduced call RPC function of pallet-contracts to call those smart-contract functions without paying any gas for it.</p><ul><li><strong>Call a smart contract function from the runtime.</strong></li></ul><p>This functionality drives the connection of runtime to smart contracts. It will allow calling any function of the smart contract from the runtime and returns the output of the functions. To facilitate, this functionality Parity team adds a non-dispatchable function i.e <a href="https://github.com/paritytech/substrate/blob/9195fac755df57e18ed59fbd358ee528d2a52d0e/frame/contracts/src/lib.rs#L684">bare_call</a> in pallet-contracts module. Its signature and functionality is somewhat similar to the low-levelcall function in Solidity. In Solidity, it is used to call an arbitrary function of the smart contract from another contract whilst here it used to call an arbitrary function of a smart contract from a runtime module.</p><pre>/// Perform a call to a specified contract.<br>///<br>/// This function is similar to `Self::call`, but doesn&#39;t perform any address lookups and better<br>/// suitable for calling directly from Rust.<br>/// # Arguments<br>/// * `origin`- Caller of the extension<br>/// * `dest`- Address/AccountId of the smart extension whom get called<br>/// * `value`- Amount of native currency that need to transfer to the extension<br>/// * `gas_limit`- Maximum amount of gas passed to successfully execute the function<br>/// * `input_data` - Encoded data that contains function selector and function arguments values.</pre><pre>pub fn bare_call(<br>    origin: T::AccountId,<br>    dest: T::AccountId,<br>    value: BalanceOf&lt;T&gt;,<br>    gas_limit: Gas,<br>    input_data: Vec&lt;u8&gt;,<br>) -&gt; ExecResult {</pre><p>The cost of execution of the bare_call will be paid by the caller of contract i.e origin.</p><p>input_data is an encoded value of function selector and its argument values. the selector is the 4-byte hex of the function name i.e keccak(fn do_something()).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d904eee80c0689f095d5fd88af5c072/href">https://medium.com/media/7d904eee80c0689f095d5fd88af5c072/href</a></iframe><p>In Polymesh this functionality is a key for interoperability between Smart Extensions and runtime modules. Using this any issuer on Polymesh can achieve an <em>Extended Compliance Rule, Token Sale Integration, Escrow Management, Corporate Governance, </em>etc. Extended compliance can be attained by adding different compliance logic within the different Smart Extensions and calling them when any transfer happens.</p><pre>Self::extensions((ticker, SmartExtensionTypes::TransferManager))<br>.into_iter()<br>.filter(|tm| Self::extension_details((ticker, tm)).is_archive == false)<br>.for_each(|tm| {</pre><pre>let result = Self::verify_transfer(ticker, extension_caller.clone(), from_did, to_did, value, tm);<br>if result == RestrictionResult::VALID {<br>    is_valid = true;<br>}<br>else if result == RestrictionResult::INVALID {<br>    is_in_valid = true;<br>}<br>else if result == RestrictionResult::FORCE_VALID {<br>    force_valid = true;<br>}<br>});</pre><p>Similarly, token sale integration can be done by introducing a generic investment function in runtime which will call its attached smart extension with the asset.</p><ul><li><strong>Read the smart contract storage from runtime.</strong></li></ul><p>To facilitate this Parity team introduces a non-dispatchable function called <a href="https://github.com/paritytech/substrate/blob/9195fac755df57e18ed59fbd358ee528d2a52d0e/frame/contracts/src/lib.rs#L697">get_storage</a>() in pallet-contracts. It will allow the reading storage variable by passing a storage key and the required address of the smart contract.</p><p>In the Polymesh scenario, this functionality will be helpful to know the state of the smart extension on the runtime side to pre-validate certain checks before committing changes into the runtime.</p><h3>RPC functions</h3><p>During this engagement Parity team also introduced RPC functionality in the contract pallet namely call &amp; get_storage.</p><p>call is performed locally without submitting any transactions. Thus executing this won’t change any state. Nonetheless, the calling state-changing contracts is still possible. This method is useful for calling getter-like methods on contracts.</p><p>get_storage is to read the contract storage for the given value.</p><p>What we discussed above is also covered within the <a href="https://www.youtube.com/watch?v=b3HIXufMHnc&amp;list=PLp0_ueXY_enXRfoaW7sTudeQH10yDvFOS">video recording of the substrate and collaborative learning session</a>. and a complete smart contract code &amp; runtime that covers every bit of functionality can be found <a href="https://github.com/satyamakgec/substrate-runtime-contract-sample/tree/multiple-read">here</a>.</p><h3>About Parity</h3><p><em>Parity is a core blockchain infrastructure company. Parity is creating an open-source creative commons that will enable people to create better institutions through technology. Learn more at </em><a href="https://parity.io/"><em>https://parity.io</em></a></p><h3>About Polymath</h3><p><em>Polymath makes it easy to create and manage security tokens. The platform simplifies the complex technical challenges of creating a security token and aims to bring the multi-trillion dollar financial securities market to the blockchain. Learn more at </em><a href="https://polymath.network/"><em>https://polymath.network</em></a></p><h3>Joining Polymath</h3><p>Are you interested in joining the security token revolution? We are always looking for high-quality talent. <strong>Check out our careers page at </strong><a href="https://polymath.bamboohr.com/jobs/?source=post_page---------------------------"><strong>https://polymath.bamboohr.com/jobs/</strong></a><strong> to apply!</strong></p><h3>Follow us</h3><p>Newsletter: <a href="https://polymath.network/newsletter">https://polymath.network/newsletter</a><br>Reddit: <a href="https://www.reddit.com/r/PolymathNetwork/?source=post_page---------------------------">https://www.reddit.com/r/PolymathNetwork/</a><br>Twitter: <a href="https://twitter.com/polymathnetwork?source=post_page---------------------------">https://twitter.com/polymathnetwork</a><br>Telegram: <a href="https://t.me/polymathnetwork?source=post_page---------------------------">https://t.me/polymathnetwork</a><br>Facebook: <a href="https://www.facebook.com/polymathnetwork/?source=post_page---------------------------">https://www.facebook.com/polymathnetwork/</a><br>Youtube: <a href="https://www.youtube.com/c/polymathnetwork?source=post_page---------------------------">https://www.youtube.com/c/polymathnetwork</a><br>Website: <a href="https://polymath.network/?source=post_page---------------------------">https://polymath.network</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfb81ecbd6f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/polymathnetwork/smart-extensions-polymath-and-parity-technical-engagement-dfb81ecbd6f0">Smart Extensions — Polymath and Parity Technical Engagement</a> was originally published in <a href="https://medium.com/polymathnetwork">Polymath Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wallet Extension for Substrate based chain]]></title>
            <link>https://medium.com/@satyam0499/wallet-extension-for-substrate-based-chain-249d44e3b542?source=rss-61cd7d3a6004------2</link>
            <guid isPermaLink="false">https://medium.com/p/249d44e3b542</guid>
            <category><![CDATA[wallet]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[polkadot]]></category>
            <category><![CDATA[substrate]]></category>
            <dc:creator><![CDATA[Satyam Agrawal]]></dc:creator>
            <pubDate>Wed, 28 Aug 2019 05:51:57 GMT</pubDate>
            <atom:updated>2019-08-28T05:59:15.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>Next Metamask for Substrate based chains?</h3><p>Substrate is a framework that allows developers to build custom blockchain as they needed, Developers can build runtime modules and plug it with their blockchain. Substrate also facilitates a forkless upgrade of blockchain. <em>This </em><a href="https://www.parity.io/substrate-in-a-nutshell/"><em>good read</em></a><em> will help you to know more about the substrate.</em></p><p>Web3 Foundation and Parity both are maximizing their efforts to provide a swiss army knife to developers that will make the development of runtime module a piece of cake. We all know that web3.js plays a crucial role in the dApp development over Ethereum network. Similarly, for substrate-based chains, we have <em>polkadot.js </em>library that will act as a gateway for interaction with chains. Same goes for wallet, Ethereum has Metamask while the substrate is still looking its correspondence.</p><p>So I decided to look through all existing browser extension wallets for substrate-based chain and summarize what they are currently offering and try to find which wallet will act as a proxy of the metamask wallet in the substrate based chain ecosystem.</p><h3>1. polkadot{.js} extension</h3><p>It is super simple and easy to use extension developed by the Parity team, It is marked as a POC so I am not sure how does the end product look like but this extension is the working prototype which can be easily downloaded from the <a href="https://chrome.google.com/webstore/detail/polkadot%7Bjs%7D-extension/mopnmbcafieddcagagdcbnhejhlodfdd">chrome-app</a> store and also available at <a href="https://addons.mozilla.org/en-US/firefox/addon/polkadot-js-extension/">Mozilla addons</a>.</p><p>My recommendation is not to use it for the production-grade application development but it will give you a flavor on the local or testnet chains. On the functionality side, it will allow you to sign a transaction on the connected chain while it extends its support for Polkadot, Substrate(development &amp; default) &amp; Kusama chain. It still lacks a lot of functionality, one of them is showing the balance of the addresses.</p><p>The best part of this extension is modularity that will allow developers to build upon it. The extension is divided among different packages —</p><ul><li><a href="https://github.com/polkadot-js/extension/blob/master/packages/extension">extension</a> — All the injection and background processing logic (the main entry)</li><li><a href="https://github.com/polkadot-js/extension/blob/master/packages/extension-ui">extension-</a>ui — The UI components for the extension, to build the popup</li><li><a href="https://github.com/polkadot-js/extension/blob/master/packages/extension-dapp">extension-dapp</a> — A convenience wrapper to work with the injected objects, simplifying data extraction for any dapp that wishes to integrate the extension (or any extension that supports the interface)</li><li><a href="https://github.com/polkadot-js/extension/blob/master/packages/extension-inject">extension-inject</a> — A convenience wrapper that allows extension developers to inject their extension for use by any dapp</li></ul><p>If your project wants its own custom extension then polkadot{.js} is the best choice to work upon. Read <a href="https://github.com/polkadot-js/extension/blob/master/README.md"><em>this</em></a><em> </em>to learn more.</p><h3>2. Speckle-browser-extension</h3><p>It is developed by <a href="https://www.speckleos.io/">SpeckleOS</a> which provides some kind of identity solution for the Polkadot ecosystem. This extension inherits a lot of security features from the metamask wallet like mnemonic verification and many more. Speckle also provides a promising UI/UX experience compared to other wallet extensions and stake, governance type feature in the extension itself but here is a catch, you will not be able to use those features because these features only exist on UI and missing on the implementation side. I assumed that those features will be workable in the future as the extension is still under the development phase.</p><p>The downside of the speckle extension that it is not available at any browser stores. If you want to play with you have to run the extension code locally and allow the unpacked extension to load in your browser. I personally feel it is a bit of a pain so I accumulate some of the <a href="https://imgur.com/a/ED6k2ZC">screenshots</a> of the extension UI to feel you at home 😜.</p><p>Speckle extension may not be the best extension you want to customize as it doesn’t provide any kind of modularity. I bet it will be a mess if anyone even tries to. One thing that irritates me that I am not able to connect with the local chain, submitted an <a href="https://github.com/SpeckleOS/speckle-browser-extension/issues/111">issue</a> regarding the same.</p><h3>3. <strong>Enzyme</strong></h3><p>This wallet is developed and maintained by the <a href="https://github.com/blockxlabs">blockxlabs</a> which is mainly focused on Polkadot blockchain, it is available at the <a href="https://chrome.google.com/webstore/detail/enzyme/amligljifngdnodkebecdijmhnhojohh">chrome store</a> as well. This wallet also comes in the list of recommended wallets for claiming KSM tokens (Kusama network token). It also comprises the functionality of signing transaction, sends/receive tokens, etc. The difference between polkadot{.js} and enzyme is that later provides good UI and show the balance of the addresses as well.</p><p>It works smoothly with Polkadot chain while if you are running any substrate-based chain then it will not be the best fit to play with.</p><p>If any project wants to customize the enzyme wallet for their use case then they should know-how AGPLv3 license works.</p><h3>4. Math-wallet</h3><p>It is a generalized wallet that supports more than 18 public blockchains, one of them is Polkadot and ChainX (Substrate based chain). It uses a very simple <a href="https://github.com/mathwallet/math-substratejs">API set</a> to interact with the substrate based chain.</p><p>I don’t have much on math-wallet as it is a generalized wallet and not focussed on the substrate-based chains that make it unsuitable for the customization related to the chain. One way to do so is to directly connect with the math-wallet team.</p><p>None of the wallets are perfect but I am sure that their team is putting up day and night to make them best. Every wallet is in the development phase so it is not suitable to call which one of them is best. I hope every wallet will contribute to the Polkadot ecosystem in their own way.</p><p>If I missed any wallet in the above list then please let me know in the comments, I will be happy to test them out.</p><p><em>Happy Coding! Cheers!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=249d44e3b542" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ERC1400 —  Implementation Approach]]></title>
            <link>https://medium.com/polymathnetwork/erc1400-implementation-approach-c668c4fbf40?source=rss-61cd7d3a6004------2</link>
            <guid isPermaLink="false">https://medium.com/p/c668c4fbf40</guid>
            <category><![CDATA[tech-blog]]></category>
            <category><![CDATA[erc1400]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[security-token]]></category>
            <dc:creator><![CDATA[Satyam Agrawal]]></dc:creator>
            <pubDate>Wed, 31 Jul 2019 19:24:38 GMT</pubDate>
            <atom:updated>2019-07-31T19:24:38.587Z</atom:updated>
            <content:encoded><![CDATA[<h3>ERC1400 — Implementation Approach</h3><p>ERC1400 has received immense support from the community since its inception and has evolved as the most accepted and versatile standard for securities on Ethereum. After multiple rounds of interactions with the community (e.g. community calls, Ethereum Magician Token Rings), the ERC1400 standard is now mature enough to move into the next stage of its development life cycle to lead the security token space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*Q9Fia0_7tFn0k52Apdaf1A.png" /></figure><p>ERC1400 is also called a library of security token standards. It acts as an umbrella and additional standards falling under the umbrella include:</p><ul><li><a href="https://github.com/ethereum/EIPs/issues/1410">ERC1410 (Partially fungible token standard)</a></li><li><a href="https://github.com/ethereum/EIPs/issues/1643">ERC1643 (Document management standard)</a></li><li><a href="https://github.com/ethereum/EIPs/issues/1644">ERC1644 (Controller token standard)</a></li><li><a href="https://github.com/ethereum/EIPs/issues/1594">ERC1594 (Core security token standard)</a></li></ul><h3><strong>Distinct Implementation of ERC1400 standard</strong></h3><p>ERC1400 is a community-driven standard which allows the community to implement ERC1400 API call in their own ways. View three different implementations below:</p><p><em>SecurityTokenStandard Implementation</em></p><p><a href="https://github.com/SecurityTokenStandard/EIP-Spec">SecurityTokenStandard/EIP-Spec</a></p><p><em>Consensys implementation</em></p><p><a href="https://github.com/ConsenSys/ERC1400">ConsenSys/ERC1400</a></p><p><em>BokkyPooBah Implementation</em></p><p><a href="https://github.com/bokkypoobah/SecurityToken">bokkypoobah/SecurityToken</a></p><h3><strong>How does the ST20 protocol implement the ERC1400 library set?</strong></h3><p>Polymath is one of the major contributors in the security token community and Polymath has its own security token implementation called ST20 which conforms to the ERC1400 standard. We are very excited to adopt the ERC1400 standard for the security token contract of our ST20 protocol in the 3.0 release of <a href="https://github.com/PolymathNetwork/polymath-core/tree/dev-3.0.0"><strong><em>polymath-core</em></strong></a>. To learn more about the 3.0 release, <a href="https://blog.polymath.network/announcing-polymath-core-v3-0-poho-a71df9cce65b"><strong><em>read the blog post from Polymath’s Head of Technology, Adam Dossa</em></strong></a>.</p><p>For the ease of understanding theERC1400 implementation approach, we will take a look into the 3 key functions that have complex logic whilst being simple in functionality.</p><h3><strong>1. canTransfer() &amp; canTransferFrom()</strong></h3><p>In the ERC20 standard there are two functions calledbalanceOf &amp; allowance() which are used to verify the transaction in terms of whether it will succeed or not before executing on-chain. Similarly, ERC1400 facilitates canTransfer() and canTransferFrom() which verifies the transaction before executing the transaction on-chain. In order to achieve this functionality, we introduced a new stateless function called verifyTransfer() in ITransferManager <a href="https://github.com/PolymathNetwork/polymath-core/blob/ab49ce7b9a3d85c4834134f88f222bcf2956b486/contracts/interfaces/ITransferManager.sol#L19">interface</a> (it is an interface that every transfer restriction module needs to follow in the ST20 protocol).</p><pre>function verifyTransfer(<br>   address _from,<br>   address _to,<br>   uint256 _amount,<br>   bytes calldata _data<br>) <br>external<br>view<br>returns(Result result, bytes32 partition);</pre><p>canTransfer() &amp; canTransferFrom() loops over all the transfer managers attached to a security token and calls the verifyTransfer() function of every attached transfer manager to validate the transfer rule. If any of the transfer managers invalidate the transaction inputs then canTransfer/ canTransferFrom will return the reason for failure, identified by the byte return value and this byte value can be mapped with an <a href="https://github.com/SecurityTokenStandard/EIP-Spec/blob/master/eip/eip-1400.md">off-chain directory</a> (following the ERC-1066 standard). It signifies that if the transaction will be executed on-chain at the same time it will not succeed. To get more insight into the failure causes we are returning application reason code i.e the <em>transfer manager address that causes the failure of the transaction. </em>It is more specific to our developers who will use that address of transfer manager for debugging.</p><h3>2. balanceOfByPartition()</h3><p>This is one of the key functions of ERC1410 that will facilitate the querying of the partition balance. The current implementation of the ST20 security token is not leveraging the partition functionality extensively. We take this decision in favor of avoiding the complexity of the protocol in our upcoming release. Wait!! then <em>how did we implement balanceOfByPartition() if there is not a partitioning functionality?</em></p><p>The answer is that we are trying to make our protocol intelligent enough to automatically understand which partition balance needs to be deducted or which partition balance needs to be increased without giving the partition name explicitly. Moving into the same direction in our upcoming release of <a href="https://github.com/PolymathNetwork/polymath-core/tree/dev-3.0.0"><em>polymath-core</em></a><em> </em>we are introducing two partitions i.e LOCKED &amp; UNLOCKED. A token holder can easily query its balances of the partitions using the balanceOfByPartition() function. It loops through all the transfer managers and queries the balance as per the given partition by using the getTokensByPartition() function, which will be implemented by all transfer managers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fc3bfd929008f2cd4377ab5398be37e/href">https://medium.com/media/8fc3bfd929008f2cd4377ab5398be37e/href</a></iframe><p>All TransferManagers will return the locked and unlocked balances according to their transfer rules. Where UNLOCKED partition value will be the minimum of all the unlocked balances retrieved from different transfer managers while LOCKED partition value will be the maximum of all the locked balances.</p><h3><strong>3. transferByPartition()</strong></h3><p>As per the ERC1410 specs this function is used to transfer the ownership of the tokens from a given partition. <em>How does this function work in our implementation?</em></p><pre>/**<br>* @notice Transfers the ownership of tokens from a specified partition from one address to another address<br>* @param _partition The partition from which to transfer tokens<br>* @param _to The address to which to transfer tokens to<br>* @param _value The amount of tokens to transfer from `_partition`<br>* @param _data Additional data attached to the transfer of tokens<br>* @return The partition to which the transferred tokens were allocated for the _to address<br>*/<br>function transferByPartition(<br>     bytes32 _partition,<br>     address _to,<br>     uint256 _value,<br>     bytes memory _data<br>) public returns (bytes32)</pre><p>The latest release will only support two partitions LOCKED &amp; UNLOCKED. As the literal meaning of LOCKED partition suggests, tokens in the locked partition are locked by nature while UNLOCKED partition tokens are free to transact. It means token holders can only transfer UNLOCKED partition value.</p><p>treansferByPartition() returns the receiving partition of the_to address, which is hard to determine. To resolve this we follow a simplistic approach where the return partition will be LOCKED if the change in LOCKED partition of _to address is equal to the _value transferred otherwise it is UNLOCKED . This solution will give you probabilistic information rather than precise information about the return partition.</p><h4>Summary</h4><p>Polymath’s 3.0 implementation of ST20 is fully compliant with the ERC1400 security token standards i.e Document standard <a href="https://github.com/ethereum/EIPs/issues/1643">ERC1643</a> , Controller standard <a href="https://github.com/ethereum/EIPs/issues/1644">ERC1644</a>, Core security token standard <a href="https://github.com/ethereum/EIPs/issues/1594">ERC1594</a> &amp; Partially fungible token standard <a href="https://github.com/ethereum/EIPs/issues/1410">ERC1410</a>. Full Implementation can be found <a href="https://github.com/PolymathNetwork/polymath-core/blob/dev-3.0.0/contracts/tokens/SecurityToken.sol">here</a> and related getters can be found <a href="https://github.com/PolymathNetwork/polymath-core/blob/dev-3.0.0/contracts/tokens/STGetter.sol">here</a>.</p><p>The ST20 3.0 security token contract is fully upgradable so that additional partitions or other functionality can be easily supported in future releases.</p><h4>Joining Polymath</h4><p>Do you want to join the security token revolution? We are growing rapidly and always looking for high-quality talent. <strong>Check out our careers page at </strong><a href="https://polymath.bamboohr.com/jobs/"><strong>https://polymath.bamboohr.com/jobs/</strong></a><strong> to apply!</strong></p><h4>About Polymath</h4><p><em>Polymath Network (Polymath) is a decentralized platform that makes it easy to create security tokens. The platform simplifies the complex technical challenges of creating a security token and aims to bring the multi-trillion dollar financial securities market to the blockchain.</em></p><h4>Follow us</h4><p>Newsletter: <a href="https://polymath.network/email.html">https://polymath.network/email.html</a><br>Reddit: <a href="https://www.reddit.com/r/PolymathNetwork/?source=post_page---------------------------">https://www.reddit.com/r/PolymathNetwork/</a><br>Twitter: <a href="https://twitter.com/polymathnetwork?source=post_page---------------------------">https://twitter.com/polymathnetwork</a><br>Telegram: <a href="https://t.me/polymathnetwork?source=post_page---------------------------">https://t.me/polymathnetwork</a><br>Facebook: <a href="https://www.facebook.com/polymathnetwork/?source=post_page---------------------------">https://www.facebook.com/polymathnetwork/</a><br>Youtube: <a href="https://www.youtube.com/c/polymathnetwork?source=post_page---------------------------">https://www.youtube.com/c/polymathnetwork</a><br>Website: <a href="https://polymath.network/?source=post_page---------------------------">https://polymath.network</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c668c4fbf40" width="1" height="1" alt=""><hr><p><a href="https://medium.com/polymathnetwork/erc1400-implementation-approach-c668c4fbf40">ERC1400 —  Implementation Approach</a> was originally published in <a href="https://medium.com/polymathnetwork">Polymath Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgradability in an Immutable World]]></title>
            <link>https://medium.com/polymathnetwork/upgradability-in-an-immutable-world-27c76926629b?source=rss-61cd7d3a6004------2</link>
            <guid isPermaLink="false">https://medium.com/p/27c76926629b</guid>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[tech-blog]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Satyam Agrawal]]></dc:creator>
            <pubDate>Wed, 21 Nov 2018 16:46:18 GMT</pubDate>
            <atom:updated>2018-11-21T16:46:18.857Z</atom:updated>
            <content:encoded><![CDATA[<p>Applications always need new features in order to meet the demands of their users. So… all you need to do is deploy the new set of smart contracts with the new features. Easy peasy, right? Not so fast! We are missing some crucial details.</p><ul><li>Shouldn’t old data persist in the new set of smart contracts?</li><li>Will the change in your smart contract addresses affect your dApp integration with various service providers?</li><li>For apps like <a href="https://www.stateofthedapps.com/dapps/polymath">stateofthedapps </a>, <a href="https://etherscan.io/address/polymathnetwork.eth">etherscan</a>, etc., how would you make them aware of the change in your smart contract addresses?</li></ul><p>We also faced similar issues during the creation of the next-generation standard for blockchain based securities called <a href="https://github.com/PolymathNetwork/polymath-core">polymath-core</a>. Since we believe in innovation and creativity, we decided to make our smart contracts (registries) upgradable to solve these problems. It is important to note that many projects have been researching the different techniques to make smart contracts upgradable; we will be presenting our approach in this post.</p><p>Thanks to ZeppelinOS, for putting their time and effort into creating generalized techniques/proxy patterns to build upgradable smart contracts. From all of those proxy patterns, we are going to explore Eternal Storage proxy pattern that we used in our registries contracts to make them upgradable. If you are curious to learn more about the different proxy patterns for upgradability, then read this awesome <a href="https://blog.zeppelinos.org/proxy-patterns/">article</a> by <a href="https://medium.com/u/f36b45fbd36c">Elena</a>.</p><h3>Why are only registries upgradable?</h3><p>In order to update core parts of our protocol while still allowing issuers to retain full control over any issued tokens, we only added upgradability to our registry and control contracts. Tokens generated through the protocol remain immutable although we are looking at innovative ways to tackle updating tokens in a future release of polymath-core.</p><h3>The architectural design of Polymath registries</h3><p>Polymath protocol has three main registries:</p><ol><li><a href="https://github.com/PolymathNetwork/polymath-core/blob/master/contracts/SecurityTokenRegistry.sol">SecurityTokenRegistry.sol</a></li><li><a href="https://github.com/PolymathNetwork/polymath-core/blob/master/contracts/ModuleRegistry.sol">ModuleRegistry.sol</a></li><li><a href="https://github.com/PolymathNetwork/polymath-core/blob/master/contracts/PolymathRegistry.sol">PolymathRegistry.sol</a></li></ol><p>SecurityTokenRegistry(aka STR) and ModuleRegistry(aka MR) are upgradable registries while thePolymathRegistry(aka PR) is not because it doesn’t have complex features like the other ones. It is only a registry for the addresses of different the smart contracts in Polymath ecosystem.</p><h4>Driving contracts for upgradability</h4><ol><li><a href="https://github.com/PolymathNetwork/polymath-core/blob/master/contracts/proxy/OwnedUpgradeabilityProxy.sol">OwnedUpgradeabilityProxy.sol</a></li><li><a href="https://github.com/PolymathNetwork/polymath-core/blob/master/contracts/proxy/Proxy.sol">Proxy.sol</a></li></ol><p>Basically, we picked up those contracts from zeppelin labs which made our lives easier when implementing it for our contracts. Below, I describe some of the most valuable functions of the previously mentioned contracts.</p><h4>fallback()</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7d5f3b76ec3f433f9a0f2c6127dc62a/href">https://medium.com/media/d7d5f3b76ec3f433f9a0f2c6127dc62a/href</a></iframe><p>The key function is the fallback function, which uses function calls to delegate the implementation contract and later affect the storage of the proxy contract. This helps to change the implementation contract without migrating the data, as all of the data resides in the proxy contracts instead of in the implementation contract.</p><p>During the function call, the function selector searches the 4-byte function signature first within the proxy contract functions. If the function signature matches within the proxy contract, the function gets executed or else the fallback function gets executed and performs a linear search on the list of function signatures of the delegate contract (~implementation contract). It would also execute the function once the match gets found. The remaining msg.data value gets copied using calldatacopy(0, 0, calldatasize) and used for the function arguments…</p><pre>switch result</pre><pre>// delegatecall returns 0 on error.</pre><pre>case 0 { revert(0, returndatasize) }</pre><pre>default { return(0, returndatasize) }</pre><p>Lastly, the switch statement returns either the returned data of the function or throws an exception if something went wrong. For a piece with more in-depth knowledge, please refer to this <a href="https://blog.zeppelinos.org/proxy-patterns/">article</a>.</p><h4>upgradeToAndCall()</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/834ef41b87924b32a22e28ceb56668cc/href">https://medium.com/media/834ef41b87924b32a22e28ceb56668cc/href</a></iframe><p>This is one of the key functions used to set the implementation/logic contract and the version of the implementation. The version is specifically used to differentiate from the various logic implementation of the contract.</p><pre>require(address(this).call.value(msg.value)(_data), “Fail in executing the function of implementation contract”);</pre><p>It is calling the contract fallback function with msg.data as _data . _data is the encoded value of the function signature and its argument value. It is variable in size but first 4-bytes are fixed for function signature which helps to decide which function needs to be executed. Mainly this upgradeToAndCall() function is used to set the implementation contract and initialize the value of some state variables. For some reason, the implementation contract has some bugs or may need to add more functionality. In this case, the most suitable function is to set the implementation contract to upgradeTo() because we don’t want to initialize the state variables again.</p><h4>Why we choose Eternal Storage over other proxy patterns?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*d9BayfVlm2pT1AYIl7tqrg.jpeg" /><figcaption>Upgrade the smart contracts</figcaption></figure><p>There may be n possible ways that exist to upgrade a smart contract. Who really knows? Here we focused on three possible proxy patterns:</p><ol><li>Unstructured storage proxy pattern</li><li>Inherited storage proxy pattern</li><li>Eternal storage (aka ES) proxy pattern</li></ol><p>Each proxy pattern has the same way of handling the function call that I’ve described above. The major difference is the techniques to store variables in storage.</p><p>Registries are one of the critical contracts of our ecosystem. We especially didn’t want to mess up the storage for these. We also didn’t want that at the time of writing the smart contract, so we needed to take care of state variable declaration order. We were more centric to our registries functionalities so we choseEternal Storage over the unstructured and inherited storage proxy pattern.</p><p>Eternal storage has its own downsides that I am going to explain one by one below and how exactly we mitigated them.</p><h4>1. Increasing readability of the code</h4><p>Two things that need to be taken care of while adopting ES pattern are the proxy and implementation contracts that inherit the same set of storage. For this, we specifically created a set of mappings where all the state variable values reside and theEternalStorage.sol contract gets inherited by both the proxy and implementation contracts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2fb40416789017a40e4db7cccca59e3/href">https://medium.com/media/d2fb40416789017a40e4db7cccca59e3/href</a></iframe><p>The normal contract storing of variables looks like this:</p><pre>uint256 test;</pre><pre>test = 10000;</pre><p>and the upgradable contract (ES type):</p><pre>uintStorage[keccak256(abi.encodePacked(&quot;test&quot;))] = 1000;</pre><p>You can compare how much readability gets affected for the singleton variable. Think about the struct, mappings, arrays, etc. To resolve this, we created a set of helper functions that increased the readability of the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a310c0d3e25d9a91e9998335ebdd7b7/href">https://medium.com/media/2a310c0d3e25d9a91e9998335ebdd7b7/href</a></iframe><p>When using this variable, it is stored like this:</p><pre>set(keccak256(abi.encodePacked(&quot;test&quot;)), 1000);</pre><p>Above is the gist of some setters and getters that we used in our contracts. Find the full contract <a href="https://github.com/PolymathNetwork/polymath-core/blob/master/contracts/storage/EternalStorage.sol">here</a>.</p><h4>2. Increased Contract Size</h4><p>Contract bytecode size has a limitation of 24 KB as per the <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-170.md">EIP170</a>. While our contract bytecode size reached 23.5 KB we reduced it using libraries to factor out the encoding part of the variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02d679ae1e2de2affd1ae12daceaca46/href">https://medium.com/media/02d679ae1e2de2affd1ae12daceaca46/href</a></iframe><p>Using this library we are able to reduce the contract size by 3.5KB and it also helped to increase the readability of the code.</p><pre>set(getKey(&quot;test&quot;), 1000);</pre><p>There were also some suggestions from our auditors to use the precomputed hash values for the singleton type of variables which helps to reduce the bit size of the contract bytecode.</p><p>Everything above are all things we’ve had to learn while making our smart contract (registries) upgradable. If you want to learn more about Eternal Storage then you can follow this <a href="https://github.com/ethereum/EIPs/issues/930">EIP</a>! If you are curious to develop more robust, unlimited sized, upgradable contracts, I recommend following this <a href="https://github.com/ethereum/EIPs/issues/1538">EIP</a>.</p><h4>Joining Polymath</h4><p>Do you want to join the security token revolution? We are growing rapidly and always looking for high quality talent. <strong>Check out our careers page at </strong><a href="https://polymath.bamboohr.com/jobs/"><strong>https://polymath.bamboohr.com/jobs/</strong></a><strong> to apply!</strong></p><h4>About Polymath</h4><p><em>Polymath Network (Polymath) is a decentralized platform that makes it easy to create security tokens. The platform simplifies the complex technical challenges of creating a security token and aims to bring the multi-trillion dollar financial securities market to the blockchain.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27c76926629b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/polymathnetwork/upgradability-in-an-immutable-world-27c76926629b">Upgradability in an Immutable World</a> was originally published in <a href="https://medium.com/polymathnetwork">Polymath Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>