Intelligent Onchain Apps with AI & Coinbase Smart Wallet

TLDR;

  • Your goto guide to building next-generation onchain apps with AI and Coinbase Developer Platform

Description

Most blockchain execution environments, like the EVM, have very limited computation capacity. This means decentralized apps and protocols are limited in their complexity of interaction. Now with the AI Oracle, smart contracts can use AI inference within their own execution logic. This means that smart contracts can use AI to evaluate data, and improve their decision making.

Combined with Coinbase Smart Wallets and OnchainKit, we can enable better UX for users and abstract away the complex logic of the smart contracts, creating next-generation experiences onchain. CDP SDK makes the development job easier for builders.

Key Benefits

  • Give smart contracts the ability to subjectively evaluate information

  • Build intelligent and reactive protocols

  • Decentralized, verifiable AI inference is credibly neutral and secure for use in smart contracts

  • Improved user experience and more complex computation facilitates new use cases

Example Use-Cases

  • Decentralized Grant Protocol: Using AI Oracle, smart contracts can evaluate user input for completion of grant requirements with AI and distribute rewards accordingly.

  • Content Moderation for DeSocial: Using AI Oracle, decentralized content platforms can evaluate and moderate content in a way that is transparent and credibly neutral.

  • Permissionless Audit Protocol: Using AI Oracle to provide a preliminary security evaluation of user submitted smart contracts.

Explore more use-cases for inspiration here: https://github.com/ora-io/awesome-ora

Overview

To implement an AI-powered onchain application with a good UX, developers should

  1. Understand the following concepts:

  2. Execute the following steps:

Using AI to Score a User’s Essay and Distribute a Payout

Here we walk you through a simple use-case example in which we set up a smart contract that can evaluate user’s essay submissions and distribute payouts based on an AI model’s scoring of that essay in line with pre-determined criteria.

Developing a Prompt Contract

First you need to implement a function that will interact with AI Oracle. The user input will be forwarded to aiOracle.requestCallback method. AI Oracle nodes will then use that input to prompt the selected model and return the verifiable result back to the smart contract.

function calculateAIResult(uint256 modelId, string calldata prompt) payable external {
    bytes memory input = bytes(prompt);
    bytes memory callbackData = bytes("");
    address callbackAddress = address(this);
    uint256 requestId = aiOracle.requestCallback{value: msg.value}(
        modelId, input, callbackAddress, callbackGasLimit[modelId], callbackData
    );
    AIOracleRequest storage request = requests[requestId];
    request.input = input;
    request.sender = msg.sender;
    request.modelId = modelId;
    emit promptRequest(requestId, msg.sender, modelId, prompt);
}

Next you need to implement a callback function, so that AI Oracle can return the result to your contract.

function aiOracleCallback(uint256 requestId, bytes calldata output, bytes calldata callbackData) external override onlyAIOracleCallback() {
    AIOracleRequest storage request = requests[requestId];
    require(request.sender != address(0), "request does not exist");
    request.output = output;
    prompts[request.modelId][string(request.input)] = string(output);
    emit promptsUpdated(requestId, request.modelId, string(request.input), string(output), callbackData);
}

In the callback function use the score of an essay, returned by AI Oracle, to determine if the reward should be sent to the writer.

uint256 score = uint256(bytes32(output));
if (score > 5){
    rewardToken.transfer(request.sender, transferAmount);
}

You can check the prompt contract implementation here: https://github.com/ora-io/Interaction_With_OAO_Template/blob/main/src/Prompt.sol

Creating User Interface

Once you have created and deployed the contracts, you should create a client application with a good user experience. To do that, first clone the template repository that supports Coinbase Smart Wallet.

git clone <https://github.com/coinbase/onchain-app-template.git>

Insert the necessary environment variables and start an app. If you’re facing issues, check out this guide: https://docs.cdp.coinbase.com/learn/docs/ai-wallets.

Next, add the code for interaction with your contract. Go to src/components/TransactionWrapper.tsx component and modify the following code with proper data.

{
    address: contract_address,
    abi: contract_abi,
    functionName: 'foo',
    args: [],
},

Now, you should be able to interact with your contract through this web application.

Finally you can add custom UI components to cover every aspect of your business logic.

OnchainKit can also be used to integrate more, engaging, front-end components in your application.

Interact with Smart Contract Through CDP SDK

You can deploy and interact with your smart contracts by using the CDP SDK. In the example above, we interact with a prompt contract that will invoke AIOracle and return the verifiable essay evaluation.

import { Coinbase, Wallet } from "@coinbase/coinbase-sdk";
import os from "os"; 

const coinbase = Coinbase.configureFromJson({ filePath: `${os.homedir()}/Downloads/cdp_api_key.json`, useServerSigner: true }); 

const wallet = await Wallet.create({ networkId: Coinbase.networks.EthereumMainnet });
const calculateAIResultArgs = {
prompt: "essay_prompt", 
 	modelId: 11
}; 

const contractInvocation = await wallet.invokeContract({
contractAddress: "prompt_address", 
method: "calculateAIResult", 
args: calculateAIResultArgs
});

await contractInvocation.wait();

For a detailed explanation on contract deployment and interaction through CDP’s SDK, refer to this guide.

Conclusion

With the use of AI Oracle, you were able to leverage complex AI compute in your smart contract. The addition of Coinbase Smart Wallet allowed for the simple onboarding of users to be paid by your web app. Together, these two functions expand on the capabilities of your application development in Web3.

About ORA

ORA is chain-agnostic infrastructure that bridges the gap between AI and blockchain.

We empower developers with the tools necessary to build end-to-end trustless and decentralized applications enhanced by verifiable AI.

ORA is live today, offering the capability to verify and run inference on the largest and most sophisticated AI models without limitations.

www.ora.io | x.com/oraprotocol | discord.gg/ora-io

Subscribe to ORA
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.