A Beginner's Guide to Molecules: Smart Contract Integrations for MEM

Smart contracts, despite being a groundbreaking technological innovation, have limitations that stem from their design and operational principles. One of the most significant constraints is their confinement to the specific blockchain they are deployed to. This imposes challenges on developers, restricting their ability to interact with the broader digital world, hindering the development of web2-like features, and effectively locking them into a single ecosystem.

What is the solution to this?

MEM is a flexible multichain smart contract layer that offers a unique solution to this problem: deterministicFetch(). This feature empowers MEM contracts to read from and write to external APIs, allowing them to query data from on-chain or web2 sources, validate fiat payments, and manage token holdings.

API wrappers designed to function within MEM contracts are referred to as molecules. With the use of molecules, MEM can call any arbitrary data source for its contracts instead of being limited to it's own siloed data.In this article, we will explore the fundamentals of molecules and how they are leveraged with deterministicFetch().

What are molecules?

Much like the role of Solidity libraries like OpenZeppelin play in Ethereum contracts, molecules are the building blocks that form the core of MEM's offerings. These molecules aren't ordinary functions; they're standardized and battle-tested functions that are readily importable into any MEM contract.

molecule.sh stands as an indispensable library and API designed exclusively for MEM developers. It serves as a versatile bridge, facilitating straightforward integration between MEM contracts and any RESTful service available. Molecules simplify the intricate process of creating MEM smart contracts. How does it achieve this? By offering a repository of reusable components tailored for common patterns and integrations.

Developers can trust these building blocks to work exactly as intended in their projects, and leverage tried-and-true patterns and integrations, reducing the risk of vulnerabilities and errors. Going beyond just simplifying development, it also extends support for a wide range of networks, allowing MEM contracts to effortlessly interact with multiple network

One of the features of molecule.sh is its ability to serve as a bridge between MEM contracts and RESTful services. This facilitates easy integration with other data sources, making it possible for MEM contracts to access and interact with real-world information.

Expanding network compatibility

With MEM, network compatibility is a vital factor that can impact the scalability and versatility of smart contracts. MEM breaks free from the constraints of being confined to a single blockchain and offers compatibility with a wide range of networks. These supported networks include EVM, Arweave, Solana, Fuel, Zilliqa, Tron, Stacks, Substrate, Ton, Massa, Tezos, Aptos, Nostr and Dfinity. See here for a list of all available network endpoints.

Example

Below is a MEM contract that uses EVM signatures and deterministicFetch to verify the user, (action.caller or similar to msg.sender), before registering them. This authentication mechanism is provided by the signer atom of the evm molecule. Once authenticated, the contract will update the state of names and reflect the new user profile in the system.

export async function handle(state, action) {
  const input = action.input;

  const names = state.names;
  const signatures = state.signatures;
  const verification_message = state.verification_message;
  const evm_molecule_endpoint = state.evm_molecule_endpoint;

  if (input.function === "register") {
    const name = input.name;
    const caller = input.caller;
    const signature = input.signature;

    ContractAssert(name.trim().length, "error invalid name");
    ContractAssert(!(name in names), "name already registered");
    ContractAssert(caller && signature, "missing required arguments");
    ContractAssert(
      !signatures.includes(signature),
      "error signed message used"
    );

    const message = btoa(verification_message);
    await _moleculeSignatureVerification(caller, message, signature);
    state.names[caller] = name.trim();
    signatures.push(signature);

    return { state };
  }

  async function _moleculeSignatureVerification(caller, message, signature) {
    try {
      const isValid = await EXM.deterministicFetch(
        `${evm_molecule_endpoint}/signer/${caller}/${message}/${signature}`
      );
      ContractAssert(isValid.asJSON()?.result, "unauthorized caller");
    } catch (error) {
      throw new ContractError("molecule res error");
    }
  }
}

The use of EVM signatures have zero costs and MEM contracts operate in a gasless manner, eliminating the need for users to pay transaction fees. This introduces various ways for developers to create flexible, user friendly and cost efficient dApps and still inherit the transparent nature of blockchains.

Bridging MEM Contracts with Real-World Data

In conjunction with the molecule.sh library, MEM introduces ways to integrate with systems that can be used to interact with blockchains. For instance, payment API functions provided by Stripe, Square, Everpay (coming soon) or similar can be called from the contract to validate that a user made a payment that the contract requires.

Although the contract itself doesn't directly handle payments, third party entities can initiate transactions and provide necessary data. The resulting values on the contract can then be used to determine the subsequent course of logic within the contract. Using external API sources in your contract's design can increase flexibility, functionality and additional security, overall enhancing a users experience.

With deterministicFetch enabling REST API calls in contracts, along with the supported programming languages MEM provides, the development process becomes a more streamlined effort given the familiar standards developers are accustomed to.

Example

In this pseudocode snippet, you can envision the use of deterministicFetch integrating your own payment API solution. The simplicity of using deterministicFetch allows developers to efficiently use external data sources into their smart contracts, opening up endless possibilities for interaction and functionality.

export async function handle(state, action) {
  // input is typically a JSON object from server or client side
  const input = action.input;

  if (input.function === "YOUR_FUNCTION") {
    const req = await EXM.deterministicFetch("API_ENDPOINT");

    const res = req.asJSON();
    // do some logic
    // change state
    return { state };
  }
}

Into the future

The MEM team is working on a variant named xMEM, which is a fork of MEM that implements privacy-focused features, such as encrypted states and interactions, and support for secrets. It facilitates the use of confidential information (similar to .env files) and offers a separate node to guarantee that execution doesn't compete for the 4k/tps limit with other contracts. The function code, input, and output data can all be encrypted by default using xMEM.

Combining these secrets with molecules adds versatility and expanded possibilities to your applications. For more details, refer to this documentation.

The MEM team remains dedicated to solving challenges and delivering solutions that continuously improve the the overall functionality and security of the platform. Stay updated on our progress as we work towards making MEM even more powerful and user-friendly.

MEM is in private beta, which you can apply for here.

Subscribe to Decent Land Labs
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.