diff --git a/blog/2026-02-23.md b/blog/2026-02-23.md deleted file mode 100644 index bd3a340387c..00000000000 --- a/blog/2026-02-23.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Shade Agent Framework 2.0 -authors: [pivortex] -slug: shade-agent-framework-2.0 -tags: [updates, ai, shade-agents] -hide_table_of_contents: true ---- - -The biggest update to the Shade Agent Framework has been released since launch. It aims to enable more production-ready builds, a more flexible developer experience, and it comes with significant architectural changes. - -:::danger Upgrade immediately -The previous version of the Shade Agent Framework has **known critical vulnerabilities**. You should upgrade your agent to 2.0 as soon as possible. -::: - - - -## A Shift in Mental Model - -Shade Agent 2.0 is not a small iteration. It reflects a different way of building and deploying Shade Agents. - -**Previously**, the framework leaned on global, abstract agent contracts and a separate API service. That made early development straightforward but production use harder: you had less control over contract behavior, deployment was split across env vars and flags, and the API lived in its own Docker image. - -**In Shade Agent Framework 2.0**, the **Shade Agent API** is a single TypeScript library that runs **inside your agent’s codebase** instead of a separate service. The **agent contract** is included in your repo so you can change and extend it for your use case. The **CLI** is built around a single config file and has built-in credential management, making deploy and whitelist flows are predictable and easier to script. - -The result is a framework that’s easier to reason about, easier to customize, and better suited to production. Below is a summary of the main changes for the API, CLI, and agent contract, with links to the docs so you can get started. - ---- - -## Shade Agent API - -The Shade Agent API no longer offers multi-language support. It has been consolidated into a single **TypeScript/JavaScript** library (`@neardefi/shade-agent-js`) that runs within your agent’s codebase instead of a separate Docker image. - -### How the API Has Changed - -Previously, the API was a separate Docker image (and HTTP service); you called standalone functions that talked to that service. In 2.0, you create a client in your code and use it for everything. Registration and funding now explicit methods instead of automatic on boot. - -**Before (1.x):** No client—you installed the package and called functions that hit the API internally (or HTTP in other languages): - -```ts -import { agentAccountId, agent, agentCall, agentView } from '@neardefi/shade-agent-js'; -// API assumed to be running (Docker / localhost:3140); env vars for config -``` - -**After (2.0):** One client, created once with your config: - -```ts -import { ShadeClient } from "@neardefi/shade-agent-js"; - -const agent = await ShadeClient.create({ - networkId: "testnet", - agentContractId: process.env.AGENT_CONTRACT_ID, - sponsor: { accountId: process.env.SPONSOR_ACCOUNT_ID, privateKey: process.env.SPONSOR_PRIVATE_KEY }, - rpc: provider, -}); -// Then: await agent.register(), await agent.fund(0.3), etc. -``` - -**Account ID:** Same idea, different shape, you now use the client instance and get the value directly (no response object). - -```ts -// Before: const res = await agentAccountId(); const accountId = res.accountId -const accountId = agent.accountId(); -``` - -**Balance:** Balance is now a method on the client and returns human-readable NEAR (e.g. `1` = one NEAR), not yoctoNEAR. - -```ts -// Before: const res = await agent("getBalance"); const balance = res.balance // yoctoNEAR -const balance = await agent.balance(); // human-readable, e.g. 0.3 -``` - -**Call and view:** Call and view have stayed the same but are accessible via the client instance instead of a standalone function. - -```ts -// Before: agentCall({ methodName, args, gas }) / agentView({ methodName, args }) -const result = await agent.call({ - methodName: "example_call_function", - args: { arg1: "value1", arg2: "value2" }, - gas: BigInt("300000000000000"), - deposit: "0", -}); -const viewResult = await agent.view({ - methodName: "example_view_function", - args: { arg1: "value1" }, -}); -``` - -**Request signature:** The old API had a dedicated `requestSignature({ path, payload, keyType })` helper. In 2.0, this has been deprecated, now if you want to call a function of the contract called `request_signature`, call it like any other function: - -```ts -// Before: requestSignature({ path, payload, keyType }) -const result = await agent.call({ - methodName: "request_signature", - args: { path, payload, key_type }, - deposit: "1", -}); -``` - -New methods include `agent.register()`, `agent.fund()`, `agent.isWhitelisted()`, and `agent.getAttestation()` for explicit control over registration, funding, and attestation; see the API reference for details. - -To learn how to install, configure, and use the API, see the **[Shade Agent API reference](/ai/shade-agents/reference/api)**. - ---- - -## Shade Agent CLI - -The Shade Agent CLI had a **total revamp**. Instead of being configured with a mix of environment variables and flags, it now centers on a **single `deployment.yaml` file**, with built-in credential management and command routing, taking inspiration from the NEAR CLI. - -You run `shade auth` to configure NEAR and Phala credentials, then use the commands `shade deploy` to deploy your Shade Agent, `shade plan` to preview the deployment, and `shade whitelist` to whitelist an agent's account ID. The `deployment.yaml` file drives contract deployment (including from source or WASM), measurement and PPID approval, Docker image build and publish, and deployment to Phala Cloud, so all deployment options live in one place. - -To learn how to install the CLI, use each command, and configure `deployment.yaml`, see the **[Shade Agent CLI reference](/ai/shade-agents/reference/cli)**. - ---- - -## Agent Contract - -Previously, the framework used **global agent contracts** that were abstract and easy to start with, but made production development and customization difficult. In 2.0, by default, a reference agent contract is included in the `shade-agent-template` repo, so you can edit and extend it to your needs (e.g. custom agent-gated functions, guardrails, and initialization). - -The reference agent contract also now uses a more robust external library for attestation verification (the [shade-attestation crate](https://github.com/NearDeFi/shade-agent-framework/tree/main/shade-attestation)). Instead of approving the codehash of a single Docker image, the contract now requires you to approve a set of measurements for more in-depth verification and a list of PPIDs that set the physical hardware the agent can run on. Local mode now requires you to whitelist the account ID of the agent you want to run locally, blocking any other account ID from controlling the contract for more consistent behavior when testing. - -To walk through the contract flow, initialization, attestation verification, and how to add your own agent-gated functions, see the **[Agent Contract reference](/ai/shade-agents/reference/agent-contract)**. - ---- - -## Next Steps - -Start your migration by **cloning the template** in the [quickstart](/ai/shade-agents/getting-started/quickstart/deploying) to explore the new setup. diff --git a/docs/ai/introduction.md b/docs/ai/introduction.md index 7fa6522a302..e0a4d144bd3 100644 --- a/docs/ai/introduction.md +++ b/docs/ai/introduction.md @@ -2,11 +2,10 @@ id: introduction title: AI and NEAR sidebar_label: Introduction -description: "Introduction to NEAR's User-Owned AI vision, featuring Shade Agents and NEAR AI." +description: "Introduction to building AI agents on NEAR with multi-chain capabilities." --- -Building AI agents that control accounts and assets on all blockchains has never been easier. NEAR enables AI agents to transact on any chain, while -our **Shade Agent Framework** allows to create verifiable and trustless AI agents with multi-chain capabilities out of the box. +Building AI agents that control accounts and assets on all blockchains has never been easier. NEAR enables AI agents to transact on any chain through features like multi-key management and Chain Signatures. ![img](/assets/docs/welcome-pages/9.near-nodes.png) @@ -21,40 +20,16 @@ Searching for how to use AI to help you build NEAR dApps, check [Tools for AI Ag ## Let Your Agent use NEAR -AI Agents can easily control account and assets on all blockchains thanks to NEARs unique features. You simply need to give them access to a NEAR account and they can start interacting with smart contracts, sending transactions, and managing assets everywhere. +AI Agents can easily control accounts and assets on all blockchains thanks to NEAR's unique features. You simply need to give them access to a NEAR account and they can start interacting with smart contracts, sending transactions, and managing assets everywhere. Check [Tools for AI Agents](./tools-for-ai.md) to get started. --- -## Build Trustless Multi-Chain Agents - -The [Shade Agent Framework](./shade-agents/getting-started/introduction.md) enables to build **verifiable** **multi-chain AI agents**. These agents operate in Trusted Execution Environments (TEEs) and leverage NEAR features such as multi-key management and Chain Signatures to securely manage assets and sign transactions across multiple blockchains. - -Shade agents can autonomously sign transactions on any chain, interact with AI models and external data sources, and perform privacy-preserving, verifiable computations. - -:::info -Shade Agents power [Agentic Protocols](./shade-agents/concepts/what-can-you-build#agentic-protocols): a new type of decentralized application designed to be autonomous, proactive, and intelligent. -::: - ---- - -## Which Docs Should I Use? - -| Docs | Best if you... | -|--------------------------------------------------------------------------------|------------------------------------------------------------------------------------------| -| [Tools for AI Agents](./tools-for-ai.md) | Want one practical guide for docs context, agent skills, and NEAR on-chain tooling | -| [Trustless Multi-chain Agents](./shade-agents/getting-started/introduction.md) | Are building an agent from zero and need to securely handle funds across multiple chains | - ---- - ## Common Questions -### Can Trustless Agents lose access to their wallets? -Not with Shade Agents. They use decentralized key management—any instance of the agent with the same code can access the same accounts. - ### Do I need to know blockchain development? Our tools and resources help to abstract away the complexity of blockchain development. ### What chains can my agent interact with? -NEAR accounts allow to transact on all chains, including Bitcoin, Ethereum and Solana thanks to Chain Signatures. +NEAR accounts allow to transact on most chains, including Bitcoin, Ethereum and Solana thanks to Chain Signatures. diff --git a/docs/ai/shade-agents.md b/docs/ai/shade-agents.md new file mode 100644 index 00000000000..98de37a97a1 --- /dev/null +++ b/docs/ai/shade-agents.md @@ -0,0 +1,10 @@ +--- +id: shade-agents +title: Shade Agent Framework (deprecated) +sidebar_label: Shade Agents (deprecated) +description: "The Shade Agent Framework is deprecated." +--- + +After April 19th, 2026, the Shade Agent Framework will no longer maintained as standalone developer tooling. Its documentation has been moved to the Shade Agent monorepo and is available here: https://github.com/NearDeFi/shade-agent-framework/tree/main/docs. + +While the framework remains open source, it will no longer be actively maintained. Teams that choose to use it should plan to assume responsibility for maintenance, updates, and any necessary fixes. diff --git a/docs/ai/shade-agents/concepts/framework-overview.md b/docs/ai/shade-agents/concepts/framework-overview.md deleted file mode 100644 index cf3426a0d75..00000000000 --- a/docs/ai/shade-agents/concepts/framework-overview.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -id: framework-overview -title: Framework Overview -sidebar_label: Framework Overview -description: "Learn about the core components of the Shade Agent Framework with a high-level overview of each of its parts." ---- - -import { SigsSupport } from '@site/src/components/sigsSupport'; - -The **Shade Agent Framework** is a platform for creating Web3 agents and off-chain services that are **verifiable**, **trust-minimized**, and **decentralized**. It leverages **on-chain signing** to allow agents to hold assets and sign transactions on most blockchains and implement strict **guardrails** to prevent unauthorized actions. - -It includes the **Shade Agent API**, the **Shade Agent CLI**, and an **agent contract reference implementation**. The framework aims to abstract most of the underlying TEE and blockchain interactions so you can focus on building your application. - ---- - -## Architecture Overview - -A **Shade Agent** has two main parts: the **agent** (off-chain) and the **agent contract** (on-chain). The agent is a backend service that runs in a TEE (or locally in dev) and holds your business logic; it uses the Shade Agent API to register and interact with the agent contract. The agent contract is a NEAR smart contract that decides who can act as an agent (via attestations, approved measurements, and PPIDs), enforces guardrails, and gives valid agents access to on-chain signing via chain signatures (MPC signing). One agent contract can have many registered agents - for example, several instances running the same code for redundancy, or different agents for different tasks. - -By default, agents are deployed to Phala Cloud, but you can deploy them to other TEE providers that support Dstack. - ---- - -## Shade Agent API - -The Shade Agent API is a **TypeScript/JavaScript** library that connects your agent to the Shade Agent Framework. It abstracts TEE complexity and simplifies calls to the agent contract. You can learn more about the Shade Agent API on the [API page](../reference/api.md). - ---- - -## Shade Agent CLI - -The Shade Agent CLI makes it easy to deploy a Shade Agent. Including building and deploying your agent contract, building and publishing your agent's Docker image, and deploying the agent to Phala Cloud. You can learn more about the Shade Agent CLI on the [CLI page](../reference/cli.md). - ---- - -## Agent Contract Reference Implementation - -A walkthrough of the agent contract reference implementation is available on the [Agent Contract Reference Implementation page](../reference/agent-contract.md). It contains the fundamental agent contract logic which you can use as a starting point for your own agent contract. - ---- - -Now that you have an overview of the framework, here are some great sections to explore next: -1. Framework components: [API](../reference/api.md), [CLI](../reference/cli.md), and [Agent Contract Reference Implementation](../reference/agent-contract.md). -2. [Tutorials and Templates](../tutorials/tutorials-overview.md) - get up and running with different Shade Agent architectures and use cases as quickly as possible, and learn how to build apps in full. -3. [What can you build?](../concepts/what-can-you-build.md) - learn about the different types of applications you can build with Shade Agents. -4. [Terminology](../concepts/terminology.md) - learn the key terms and concepts used in the Shade Agent Framework. -5. [Security Considerations](../concepts/security.md) - check your agent abides by best practices. - - \ No newline at end of file diff --git a/docs/ai/shade-agents/concepts/security.md b/docs/ai/shade-agents/concepts/security.md deleted file mode 100644 index 12056a5d642..00000000000 --- a/docs/ai/shade-agents/concepts/security.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -id: security -title: Security Considerations -sidebar_label: Security Considerations -description: "Learn key security practices when deploying Shade Agents, including preventing duplicate actions, handling failed or unsent transactions, restricting API routes, removing agent contract keys, removing local deployment, approved measurements limits, public logs, storing agent keys, public PPIDs, fixed Docker images, trusting RPCs, and verifying the state." ---- - -import { SigsSupport } from '@site/src/components/sigsSupport'; - -:::warning -The Shade Agent Framework has not yet undergone a formal audit. - -No representations or warranties are made regarding security, correctness, or fitness for any purpose. Use of this software is entirely at your own risk. -::: - ---- - -## Restricting Actions - -While TEEs are considered trusted and tamper-resistant, implementing tight restrictions or **guardrails** on agent actions within the agent contract is recommended so that even in the event a TEE is compromised and the private key to an agent is extracted, funds can't be withdrawn. You can read more about guardrails [here](terminology.md#on-chain-guardrails). - ---- - -## Preventing Duplicate Actions - -To ensure liveness, a Shade Agent should consist of multiple identical agents hosted by different providers/on different hardware. When multiple agents are running, all agents will respond to triggers (user inputs, cron jobs, API calls, etc.). You must ensure that the Shade Agent collectively performs the desired action only **once** in response to each update. - -Consider a mindshare trading agent as an example. If Solana's mindshare increases relative to NEAR, the agent would swap SOL for NEAR. With two agents running, you must ensure this swap doesn't occur twice. - -This logic is typically best implemented within the agent contract by only allowing one agent to perform the action at a time. - ---- - -## Handling Failed or Unsent Transactions - -A successful MPC signature on a transaction payload doesn't guarantee the transaction's success or transmission. Transactions may fail for various reasons, such as network congestion, incorrect nonce, or insufficient gas. - -It's suggested you build your agent in such a way that if the transaction fails, then a new signature can be requested without allowing for more signing for the same action when the transaction is successful. - -For some use cases, it may be beneficial to emit signed transactions from your agent contract, allowing anyone or an indexer to relay them if your agent fails to retrieve the result. Signed transactions can be built using [omni-transactions-rs](https://github.com/near/omni-transaction-rs). Exercise caution with unsent signatures. - ---- - -## Restricting API Routes - -In the quickstart, the agent can take an API request from anyone, allowing someone to drain the funds from the agent's account and the Ethereum Sepolia account through gas expenditure. If using API routes, you need to design your agent to only perform the action when the desired condition is met or implement authentication inside the route, for example, a user has signed an action with their wallet or they are logged in from their Google account. - ---- - -## Removing Agent Contract Keys - -Before deploying your agent contract to production, you should ensure that all **access keys** to the agent contract account have been removed. Otherwise, this would allow the access key owner to withdraw the funds held by the Shade Agent. This can be done using the CLI. - -In the agent contract reference implementation, the contract code, approved measurements, and PPID can be updated by the owner. It's recommended that the owner be a **multisig**. - ---- - -## Removing Local Deployment - -When deploying to production, it's recommended to remove the **local deployment flow** from the agent contract entirely. Strip out the code that supports local mode (whitelist checks, default measurements, and PPID for local, and any `requires_tee: false` branches) so the contract only accepts TEE attestations. That way, there is no way to misconfigure or re-enable local mode, and no code path that trusts a whitelist instead of attestation. - ---- - -## Approved Measurements Limits - -The attestation verification process iterates over all approved measurements and verifies that the TEE's measurements match the approved measurements. If the approved measurements list grows too large, registration could fail due to the function call running into the **gas limit**. It's recommended to limit the number of approved measurements to a reasonable number. - ---- - -## Public Logs - -By default, the Shade Agent CLI deploys the agent with **public logs** enabled. You should not emit any sensitive information in the logs when this is enabled. - ---- - -## Storing Agent Keys - -The agent's **ephemeral keys should not be stored** anywhere, including on the host machine. This could lead to code that is not approved in the contract accessing keys that are approved in the contract. - ---- - -## Public PPIDs - -All PPIDs that are approved in the agent contract are made **public**. If you are using your own hardware, consider whether you are comfortable with its PPID being public since it could be used to track your hardware. - ---- - -## Fixed Docker Images - -Never reference Docker images by `latest` (e.g. pivortex/my-first-agent:latest) in your **Docker Compose** file; this can lead to different images being loaded in the TEE for the same measurements. Always reference versions of the image you want to use via **hash** (e.g. pivortex/my-first-agent@sha256:bf3faac9793f0fb46e89a4a4a299fad69a4bfd1e26a48846b9adf43b63cb263b). - ---- - -## Trusting RPCs - -Inside an agent, it's common to want to query the state of the blockchain and perform actions based on the state. Since **RPCs can lie** about the state of the blockchain and do not have crypto-economic security, it's suggested you design your agent to defend against this. Below are some solutions, which solution you use will differ depending on your use case and the design of your agent: - -### Verifying the State - -In some cases, you will be able to submit the state back to the smart contract from which the state was queried and verify that it matches the actual state. For example, the verifiable DAO example submits a hash of the proposal back to the DAO, so the DAO can verify that the decision was made based on the true state of the blockchain. - -### Trustless Providers - -You can use RPC providers that leverage cryptographic proofs or run in TEEs themselves to know that the result mirrors the true state of the blockchain. - -### Multiple Reputable Providers - -You can use multiple reputable RPC providers and check the result across each provider to make sure they match. - - - - diff --git a/docs/ai/shade-agents/concepts/terminology.md b/docs/ai/shade-agents/concepts/terminology.md deleted file mode 100644 index 968b24494ef..00000000000 --- a/docs/ai/shade-agents/concepts/terminology.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -id: terminology -title: Terminology -sidebar_label: Terminology -description: "Learn the key terms and concepts used in the Shade Agent Framework." ---- - -Below are the main terms and concepts used in the Shade Agent Framework. - ---- - -## Shade Agent Framework - -The **Shade Agent Framework** is a platform for creating Web3 agents and off-chain services that are **verifiable**, **trust-minimized**, and **decentralized**. It leverages **on-chain signing** to allow agents to hold assets and sign transactions on most blockchains and implement strict **guardrails** to prevent unauthorized actions. - -It includes the **Shade Agent API**, the **Shade Agent CLI**, and an **agent contract reference implementation**. The framework aims to abstract most of the underlying TEE and blockchain interactions so you can focus on building your application. - -### Shade Agent - -A **Shade Agent** is an application built using the Shade Agent Framework. See [What can you build?](./what-can-you-build.md) for some examples. - -### Agent - -In the Shade Agent Framework, an agent is a single instance of the off-chain code running inside a **TEE** (or locally in development) that uses the Shade Agent API. One agent contract can have many registered agents: they may run the same code for redundancy or different code for different tasks. - -### Agent's Account - -The agent’s account is the NEAR account ID that represents that agent on-chain. It is an **implicit account** (64-character hex) derived from the agent's **ephemeral private key**, meaning the private key and account ID are unique to the agent, and change each time the agent reboots. In local mode, you can set the agent's account ID to be **deterministic** to avoid re-whitelisting or re-funding the agent on each run. - -### Agent Contract - -The agent contract is the on-chain **NEAR smart contract** that authorizes agents via attestations and approved measurements and PPIDs, enforces guardrails, and gives valid agents access to on-chain signing. - - -### On-Chain Guardrails - -On-chain guardrails are restrictions that are enforced on the agent contract to **prevent unauthorized actions** even if the TEE is compromised. Examples include limiting transactions to specific functions, smart contracts, blockchains, or amounts. Guardrails are usually implemented using the [omni-transaction-rs](https://github.com/Omni-rs/omni-transaction-rs) library. - -### On-Chain Signing - -The agent contract can sign transactions for **most chains** via NEAR's [Chain Signatures](../../../chain-abstraction/chain-signatures.md) service, which is accessed by making cross-contract calls to the **MPC contract**. All assets and state of the Shade Agent should be tied to the agent contract, not the agent's account, since agent keys are ephemeral. - ---- - -## Environment - -### TEE - -A **Trusted Execution Environment** (TEE) is a secure part of a CPU that runs code in an isolated and protected way. Execution and state stay private, including from the host. TEEs produce cryptographic attestations that prove it's running certain code inside a genuine TEE. - -### Local - -Local mode means the agent runs on your machine (or any non-TEE environment) instead of inside a TEE. There is no real attestation, and the contract uses a whitelist of allowed account IDs instead. Use local mode for development and testing only, not for production. - ---- - -## Registration - -### Registering an Agent - -An agent **registers** with an agent contract by calling the `register_agent` method, which verifies that it has a valid attestation. On successful registration, the agent will be stored in the contract's state with its **measurements**, **PPID**, and **validity period**. - -### Whitelisted Accounts - -The whitelist is a set of **NEAR account IDs** that are allowed to register when the agent contract is in **local mode**. Because the contract cannot verify code or hardware in local mode, it instead restricts access to specific account IDs. - -### Valid Agent - -A valid agent is one that is registered with the agent contract and still has measurements and a PPID that are approved, and its registration has not expired. Valid agents can call agent-gated methods. - -### Attestation - -An attestation is a cryptographic proof produced by a TEE that the application is running inside a genuine TEE. The agent submits its attestation when registering with the agent contract, and the contract verifies that it's a genuine attestation and checks that the attestation contains a set of approved measurements and an approved PPID. - -### Measurements - -The measurements are hashes that uniquely identify the code running in the TEE, and the platform it's running on. The agent contract stores a list of approved measurements, which can be updated by the owner of the contract. There are 6 measurements: -- **MRTD**: Measures the initial setup of the trusted domain. This is constant. -- **RTMR0**: Measures the virtual hardware. This is constant for a given number of vCPUs and memory allocation. -- **RTMR1**: Measures the kernel. This is constant. -- **RTMR2**: Measures the Dstack image version. This is constant for a given Dstack image version. -- **Key Provider Digest**: Measures the key provider of the TEE. By default, Shade Agents contain Phala's key providers but don't actually use it since it uses a Chain Signatures for decentralized key management instead. This is constant for Phala's key provider. -- **App Compose Hash**: Measures the application. This is constant for a given Docker Compose file and app layer configurations. - -### PPID - -The PPID (Provisioning Platform ID) is a unique identifier of a **physical TEE machine**. Recent exploits of TEEs have been due to attackers having physical access to the machine, revealing that the physical location of the machine is important in TEE security. By setting approved PPIDs, the agent contract can ensure that only agents running on specific machines can register. You should approve PPIDs for machines known to be located in secure data centers. By default, the CLI approves all PPIDs for Phala Cloud. - -Note that on Phala Cloud, two different deployments can have the same PPID if they are running on the same server, since resources are virtualized. - ---- - -## Docker - -Docker is used in the Shade Agent Framework to deploy agents to TEEs. - -- The **Dockerfile** defines how to build a single image for your agent (dependencies, entrypoint, etc.). The CLI uses it when building the image. -- The **Docker image** is a single packaged application for your agent. -- The **Docker Compose file** defines the full application stack of the agent that runs in the TEE. It defines the images for the agent, the allowed environment variables, ports, volumes, etc. - ---- - -## Phala Cloud - -Phala Cloud is a cloud provider for hosting applications inside Trusted Execution Environments. The Shade Agent Framework uses it as its default hosting provider for agents. - -### DStack - -DStack is a framework for running and proving applications inside of Trusted Execution Environments that Phala Cloud uses. The Shade Agent Framework only supports Dstack environments either on Phala Cloud, your own hardware, or other providers. \ No newline at end of file diff --git a/docs/ai/shade-agents/concepts/using-ai.md b/docs/ai/shade-agents/concepts/using-ai.md deleted file mode 100644 index 7620f15bbda..00000000000 --- a/docs/ai/shade-agents/concepts/using-ai.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -id: ai-inference -title: AI Inference -sidebar_label: AI Inference -description: "Learn how to use AI with Shade Agents." ---- - -Your agent can call AI inference in two main ways; they have different trust assumptions and privacy guarantees. - ---- - -### NEAR AI Cloud - -NEAR AI Cloud provides **verifiable private inference** using TEEs. You get cryptographic proof that inputs stayed private and that the output was produced by the intended model. If you use NEAR AI Cloud, you should verify the TEE attestations in your agent. - -You can learn more about NEAR AI Cloud [here](https://docs.near.ai/cloud/private-inference). - ---- - -### Other Inference Providers - -You can use other inference providers like OpenAI, Anthropic, etc. However, you need to place a certain level of trust in the provider that the inputs remain private and the output was produced by the intended model. diff --git a/docs/ai/shade-agents/concepts/what-can-you-build.md b/docs/ai/shade-agents/concepts/what-can-you-build.md deleted file mode 100644 index 720851bedbc..00000000000 --- a/docs/ai/shade-agents/concepts/what-can-you-build.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -id: what-can-you-build -title: What can you Build? -sidebar_label: What can you Build? -description: "Explore the features of Shade Agents and what they enable you to build, including Agentic Protocols, autonomous yield optimizers, and verifiable oracles." ---- - -With their extensive list of features, Shade Agents unlock a wide range of new use cases, enable many previously centralized apps to become decentralized, and change how blockchain applications are designed. - -## Shade Agent Features - -Shade Agents are: -- **Non-custodial** - No one entity controls the private keys of the agent (MPC signing). - -- **Verifiable** - Agent code is known and executes as expected; no one can tamper with the agent. - -- **Multichain** - Can hold any crypto asset and sign transactions on most chains. - -- **AI Powered** - Can verifiably access LLMs. - -- **Confidential** - Inputs and state of the agent can be private. - -- **Flexible** - Interact with off-chain data and APIs beyond blockchain VM limits. - -- **Low cost** - Run intensive computation cheaply without gas limits (~20% TEE overhead compared to standard servers). - ---- - -## Agentic Protocols - -Shade Agents enable a new paradigm of decentralized applications where a component of the logic for a protocol is run in a verifiable off-chain environment. This allows for more flexibility in terms of computation, cost, privacy, and the data you have access to. Agentic Protocols are designed to be autonomous, proactive, and intelligent. - -- A Yield Optimizer that earns optimal yield on assets across various DeFi protocols on different chains and autonomously rebalances according to a verifiable algorithm to get users the best rate, always. -- A staking protocol that can implement complex reward mechanics. -- A private DAO agent on Ethereum Mainnet that takes votes confidentially and publishes the end result in a single transaction. -- A smart contract that can verifiably book users' plane tickets by calling the contract with funds and passing secrets (passport information and email address) to the agent directly. - ---- - -## Flexible Oracles - -Since Shade Agents can access off-chain data and APIs, they make great cheap, flexible, quick-to-spin-up oracles. - -- A custom data oracle where app developers list a number of different sources, a consensus mechanism (4 of 5 sources state the same data), and the frequency with which data is pushed (or on demand), which allows smart contracts to access any data verifiably. -- A prediction market resolver agent that uses an LLM to interpret multiple webpages and APIs to resolve markets quickly and accurately. -- Verifiable randomness oracle. - ---- - -## Smart Contracts Using LLMs - -Shade Agents allow you to access LLMs from a smart contract that lives on any chain. The LLM and agent are both running in a TEE, so one can verify that the response from the agent is actually from an LLM and its response is a function of the provided inputs. - -There are two main flows: - -1) The smart contract emits an event during a function call, the agent indexes this, uses the LLM to make a decision, and the agent calls a function on the contract with the result that is restricted to the agent's address. -2) Users interact with the agent which makes decisions via the LLM and carries out certain on-chain actions based upon the decision (transfers, function calls, swaps, etc.). - -With this, you could create: -- A DAO with an AI President that makes decisions based on aggregate user opinions, historical context, and user reputation formulated from on-chain and off-chain data. -- A decentralized social platform that uses an LLM to moderate content. -- A treasury that trades assets according to news, sentiment, and historical price. - ---- - -## Custom Authentication - -Shade agents allow users to control accounts through ways other than a private key and have it be non-custodial. - -- A prediction market that lets you create new markets and place bets all from Twitter (X). -- A more secure social onboarding experience where you can log in via Google, Email, etc. -- A Telegram bot for trading within a group chat. \ No newline at end of file diff --git a/docs/ai/shade-agents/getting-started/introduction.md b/docs/ai/shade-agents/getting-started/introduction.md deleted file mode 100644 index 4aa42a45824..00000000000 --- a/docs/ai/shade-agents/getting-started/introduction.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -id: introduction -title: Shade Agents -sidebar_label: What are Shade Agents? -description: "Learn about Shade Agents - decentralized and trustless AI agents that control accounts and assets across multiple blockchains using TEEs and NEAR's decentralized key management." ---- - -import { SigsSupport } from '@site/src/components/sigsSupport'; - -:::warning -The Shade Agent Framework has not yet undergone a formal audit. - -No representations or warranties are made regarding security, correctness, or fitness for any purpose. Use of this software is entirely at your own risk. -::: - -The **Shade Agent Framework** is a platform for creating Web3 agents and off-chain services that are **verifiable**, **trust-minimized**, and **decentralized**. It leverages **on-chain signing** to allow agents to hold assets and sign transactions on most blockchains and implement strict **guardrails** to prevent unauthorized actions. - -Previous Web3 agents fall into one of two categories: -1. They are trustless and verifiable by using a **trusted execution environment (TEE)**, but if the TEE goes down, the private keys and funds of the agent are lost. -2. The agent’s accounts are persistent, but the agents are centralized. - -Shade Agents provide verifiability and non-custody by operating in **TEEs**, but also persistent control of accounts by using NEAR's **decentralized key management**. Any instance of an agent running the same code inside a TEE can access the same accounts, meaning you don't need to worry about private keys being lost or exposed. - -Thanks to combining TEEs with the NEAR tech stack, Shade Agents can sign transactions across most chains, interact with AI models and external data sources, manage assets, and perform privacy-preserving, verifiable computations, offering the flexibility and performance of Web2 with the verifiability of Web3. - -:::info -Shade Agents power [Agentic Protocols](../concepts/what-can-you-build.md#agentic-protocols): a new type of decentralized application designed to be autonomous, proactive, and intelligent. -::: - ---- - -## How Do Shade Agents Work? - -Shade Agents consist of two main components: the **agent** and the **agent smart contract**. - -![Shade Agent Architecture](/assets/docs/ai/shade-agent-stack-diagram.png) - -When an agent is booted up in a TEE, it generates a random **ephemeral private key** and **NEAR account**. This private key is exclusively used to call the agent contract, not for storing funds. - -
- -What is a TEE? - -A trusted execution environment is a secure part of a CPU that runs code in an isolated and protected way. Execution and state stay private, including from the host. TEEs produce cryptographic attestations that prove it's running certain code inside a genuine TEE. - -
- -The agent calls the `register_agent` function on the **agent smart contract**, providing its **attestation**. The attestation contains: -- A proof that it's running inside a **genuine TEE**. -- The [measurements](../concepts/terminology.md#measurements) of the code running in the TEE (which uniquely identifies the code and platform it's running on). - -If the attestation is valid, the measurements fit the approved measurements in the contract, and it's running on a certain machine (identified by a [PPID](../concepts/terminology.md#ppid)), then the agent's account is registered inside the agent contract. - -Once registered, the **agent** can call the agent-gated functions on the agent contract. An example of this is the `request_signature` function, enabling it to sign transactions on behalf of the Shade Agent. `request_signature` leverages [chain signatures](../../../chain-abstraction/chain-signatures.md) for decentralized key management, allowing the Shade Agent to hold assets and sign transactions on nearly any chain. - -If **anyone** deploys the same code to a different TEE with the same measurements and PPID, it can also register in the contract, and thus gain access to signing transactions using the Shade Agent's accounts. This means the accounts are persisted across different TEE instances. To facilitate this functionality, agents are designed to be stateless. - ---- - -## Agent Contract Functions - -The Agent Contract has four main functions: - -#### Approve Measurements - -After the contract is deployed, a set of **measurements** is set to ensure that only agents running the correct code (i.e. it has the same measurements) can be registered in the agent contract. - -Developers or protocols may need to modify the code running inside agents over time. Because of this, when the contract is initialized, an **owner** account ID is set. Only the owner can approve a new set of **measurements**. - -The **Shade Agent CLI** handles the deployment of the agent contract and automatically approves the measurements of your agent. - -:::tip -Upgradeability can be designed for the specific use case. Common upgrade methods include approving a new set of measurements through DAO voting or implementing a grace period or cool down, allowing users to withdraw funds if they're uncomfortable with the incoming measurements for the new agent. -::: - -#### Approve PPIDs - -Similar to how measurements are approved, the owner also approves a set of **PPIDs** to ensure that only agents running on specific machines can register. - -#### Register Agent - -The `register_agent` function verifies that the agent is running in a TEE, is executing the expected code (as defined by the approved measurements), and is running on a certain machine (as defined by the approved PPIDs). Upon successful verification, the agent's account ID becomes registered and gains access to agent-gated functions. - -The **Shade Agent API** makes it easy to register; just use the `agent.register()` method. - -#### Request Signature - -The `request_signature` function serves as the gateway to access the Shade Agent's multichain accounts and sign transactions. It employs **method access control** so that only registered agents can use this function. - -:::tip -Developers should not sign transactions from the agents themselves (except for functions on the agent contract), as these accounts will be lost if the agent goes down. The magic of Shade Agents is that the multichain accounts are tied to the agent contract, which are persistent and accessible by any instance of a valid agent. -::: - -The `request_signature` function accepts three arguments: -- The transaction `payload` - a hash of the transaction to be signed. -- The derivation `path` - a string that modifies the address on the target chain being used. Shade Agents can access a near-unlimited number of accounts, and the account being used can be changed by modifying the path. The same path will always map to the same account for a given agent contract. -- The `key_type` - sets the signature scheme required for the transaction. Shade Agents can sign transactions for any blockchain using the `secp256k1` and `ed25519` signature schemes (EVM, Bitcoin, Solana, Sui, XRP, etc.). - -The **Shade Agent API** exposes the `agent.call()` method to sign transactions on behalf of the Shade Agent within your agent. - -:::tip -`request_signature` is only an example of an agent-gated function. You can implement any function you want on the agent contract. It's recommended to implement [on-chain guardrails](../concepts/terminology.md#on-chain-guardrails) to prevent unauthorized actions even in the case of a compromised TEE. -::: - ---- - -## Languages and Frameworks - -The agent is just a backend service that runs inside a TEE instead of a centralized server. You can run the agent on an internal cron job, respond to actions, or it can expose API routes that can be called. - -Agents are written in TypeScript/JavaScript using the **Shade Agent API**, and agent contracts are written in Rust. - ---- - -## Next Steps - -Now that you've learned what Shade Agents are and why they're powerful, head to the [quickstart](./quickstart/deploying.md) to deploy your first agent and see how to build them. - - \ No newline at end of file diff --git a/docs/ai/shade-agents/getting-started/quickstart/components.md b/docs/ai/shade-agents/getting-started/quickstart/components.md deleted file mode 100644 index b82847b8621..00000000000 --- a/docs/ai/shade-agents/getting-started/quickstart/components.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -id: components -title: Key Components -sidebar_label: Key Components -description: "Learn about the components of a simple Shade Agent." ---- - -import {Github} from "@site/src/components/UI/Codetabs" -import { SigsSupport } from '@site/src/components/sigsSupport'; - -In this section, we'll explore the main components of the [quickstart template](https://github.com/NearDeFi/shade-agent-template) to understand how to develop a Shade Agent. We'll also look at how to modify the template to build an agent for your use case. - ---- - -## Template Structure - -The template we're using is a simple Shade Agent built with Hono and written in **TypeScript** that acts as a verifiable ETH price oracle. It takes prices from two different APIs, takes the average, and then pushes the price to an Ethereum contract. - -The agent has three main files: -1) [**index.ts**](https://github.com/NearDeFi/shade-agent-template/tree/main/src/index.ts) - This is the entry point that sets up the **Shade Agent Client**, **registers** the agent and defines the routes for the agent. We'll review this file in more detail in the next section. -2) [**transaction**](https://github.com/NearDeFi/shade-agent-template/tree/main/src/routes/transaction.ts) - This is where the core logic of the agent is defined. When this API is called, the agent will build a transaction payload and request a signature from the agent contract. We'll look deeper into this API route later on this page. -3) [**agentInfo**](https://github.com/NearDeFi/shade-agent-template/tree/main/src/routes/agentInfo.ts) - This API simply fetches the agent's NEAR account ID and its balance by using the `agent.accountId()` and `agent.balance()` methods from the `shade-agent-js` library. -4) [**ethAccount**](https://github.com/NearDeFi/shade-agent-template/tree/main/src/routes/ethAccount.ts) - This API returns the **Ethereum Sepolia account** that the Shade Agent uses to update the price of Ethereum in the Sepolia contract. This API is used so the user knows which account to fund for gas. - -The repo also contains an **agent contract**. We won't review the agent contract as it's the same as the reference implementation [featured here](../../reference/agent-contract.md), but we encourage you to review the reference implementation after this section. - ---- - -## Registering the Agent - -First, in the [index.ts](https://github.com/NearDeFi/shade-agent-template/tree/main/src/index.ts) file, the **Shade Agent Client** is **initialized**. - -The client is initialized with the following arguments: -- `networkId` is set to `testnet` since the agent contract was deployed to testnet. -- `agentContractId` is set to the agent contract ID and is fetched from the environment variables. -- `sponsor` is set to the sponsor account details from the environment variables. It is used later to fund the agent. -- `derivationPath` is set to the sponsor's private key from the environment variables. For local deployment, this derives a deterministic account ID for the agent, making testing easier (for TEE deployment, this does nothing as ignored). The derivation path needs to be random and private; a private key fulfills this criterion well. - - - -Next, the agent is **funded** with 0.3 NEAR via the `sponsor` account using the `agent.fund()` method. This is done to ensure the agent has enough NEAR to pay for gas when sending transactions. - - - -After this, the agent **registers** itself with the agent contract. To make it easier for local deployment, a loop is started that checks if the agent is whitelisted; if not, it will wait for 10 seconds and try again until it's whitelisted, at which point the agent will register. - - - -Since registrations expire (every 7 days by default), an interval is set to **re-register** the agent every 6 days. - - - -The agent is now registered and ready to sign transactions. - ---- - -## Signing Transactions - -In the [transaction API Route](https://github.com/NearDeFi/shade-agent-template/tree/main/src/routes/transaction.ts), the `agent.call()` method from the `shade-agent-js` library is used to call a function on the agent contract. - -In this example, the agent is calling the `request_signature` function on the agent contract. This function takes a transaction payload for nearly any blockchain and requests a signature via [Chain Signatures](../../../../chain-abstraction/chain-signatures/implementation.md). Here, we're signing a transaction to call an Ethereum contract to update the stored price of ETH. First, we retrieve the price of ETH (in this example, the function queries two different APIs and calculates the average). - - - -Next, we build the **transaction payload** to be signed. To do this, we're using the `chainsig.js` library. -Using this library, we: -1. **Derive the Ethereum address** that will be sending the transaction. This function takes the agent contract account ID since this is the predecessor account that is calling the Chain Signatures [MPC contract](https://github.com/Near-One/mpc/tree/main/libs/chain-signatures/contract), and a path. The path can be whatever string you like; different paths will derive different addresses. -2. Create the `data`. This is what action we're performing, in this case, a function call to update the price in the contract. -3. **Build the transaction and the transaction payload** by inputting the derived address, the target Ethereum smart contract, and the data. - - - -Once we have the payload (also known as the hash), we can call the `request_signature` function on the agent contract to sign the transaction. We specify the `keyType` as `Ecdsa` as we're signing for a blockchain that uses the **secp256k1** signature scheme. - - - -The result is the **signature**. - -We then attach the signature to the Ethereum transaction and broadcast it to the target network. - - - ---- - -## Modifying This Template - -### Using Different Chains - -We set up a **chain adapter** for Ethereum Sepolia in the [Ethereum.ts](https://github.com/NearDeFi/shade-agent-template/tree/main/src/utils/ethereum.ts) file using the `chainsig.js` library. This library allows us to easily construct transaction payloads to be signed by the agent. - - - -You can set up chain adapters for a variety of chains, including NEAR, EVM, Bitcoin, Solana, SUI, XRP, and Cosmos, to allow your agent to interact with multiple different chains. You can see a full list of the chains currently supported [here](https://github.com/NearDeFi/chainsig.js/tree/main?tab=readme-ov-file#supported-chains), but feel free to contribute any chain that is not yet supported. - -Implementation details differ slightly from chain to chain; as such, we recommend you review our [chain signature docs](../../../../chain-abstraction/chain-signatures/implementation.md). Note that step 3 of requesting a signature is different; we use the `agent.call()` method from `shade-agent-js` instead. - -If you are using a chain that uses the **ed25519** signature scheme (NEAR, Solana, SUI, Aptos, etc.), you should specify the `keyType` as `Eddsa` when calling `request_signature`. - -### Implementing Guardrails - -As you move into production, it's recommended to implement on-chain guardrails in your agent contract to prevent malicious actions even if the TEE is compromised. You can read more about guardrails [here](../../concepts/terminology.md#on-chain-guardrails). - ---- - -## Next Steps - -Now that you've explored the basics of Shade Agents, we recommend diving deeper into the [framework overview](../../concepts/framework-overview.md) to understand the core components for building production-ready Shade Agents. - - \ No newline at end of file diff --git a/docs/ai/shade-agents/getting-started/quickstart/deploying.md b/docs/ai/shade-agents/getting-started/quickstart/deploying.md deleted file mode 100644 index 34f708d95dc..00000000000 --- a/docs/ai/shade-agents/getting-started/quickstart/deploying.md +++ /dev/null @@ -1,208 +0,0 @@ ---- -id: deploying -title: Deploying an Agent -sidebar_label: Deploying an Agent -description: "Learn how to quickly deploy your first Shade Agent." ---- - -import { TryDemo } from '@site/src/components/TryDemo'; -import { SigsSupport } from '@site/src/components/sigsSupport'; -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -:::warning -The Shade Agent Framework has not yet undergone a formal audit. - -No representations or warranties are made regarding security, correctness, or fitness for any purpose. Use of this software is entirely at your own risk. -::: - -In this section, we'll walk you through **deploying** a Shade Agent. - -The [template](https://github.com/NearDeFi/shade-agent-template) we're using is a simple Shade Agent built with Hono and written in **TypeScript** that acts as a verifiable ETH price oracle. It fetches the price of Eth from two different APIs, takes the average, and then pushes the price to an Ethereum contract. - -We'll cover two deployment scenarios: -1. **Local Development**: Running the agent locally for rapid testing and development. -2. **TEE Deployment**: Running the agent in a real Trusted Execution Environment (TEE). - -On the [next page](./components.md), you'll see how the key components of the agent work and how to edit this agent for your specific use case. - ---- - -## Prerequisites - -- Install the **Shade Agent CLI**: - - ```bash - npm i -g @neardefi/shade-agent-cli - ``` - -- Set up **Docker** if you have not already: - - - **Install** Docker for [Mac](https://docs.docker.com/desktop/setup/install/mac-install/) or [Linux](https://docs.docker.com/desktop/setup/install/linux/) and create an account. - - - **Log in** to Docker, using `docker login` for Mac or `sudo docker login` for Linux. - -- Set up a free **Phala Cloud** account at https://cloud.phala.network/register, then get an API key from https://cloud.phala.network/dashboard/tokens. - -
- - What is a Phala Cloud - -Phala Cloud is a cloud service that supports hosting applications in TEEs. It makes it easy to run an agent in TEE. - -
- ---- - -## Set Up - -- First, **clone** the [template](https://github.com/NearDeFi/shade-agent-template): - - ```bash - git clone https://github.com/NearDeFi/shade-agent-template - cd shade-agent-template - ``` - -- Set up **NEAR** and **Phala** credentials in the CLI: - - ```bash - shade auth set all testnet create-new - ``` - -- Set a unique `agent_contract.contract_id` (e.g. example-contract-123.testnet) and fill in your `build_docker_image.tag` (e.g. pivortex/my-first-agent) in the `deployment.yaml` file. - -- Create a `.env` file and configure your environment variables. - -```env -AGENT_CONTRACT_ID= Set this to the agent contract ID you set in the deployment.yaml file -SPONSOR_ACCOUNT_ID= Set this to the NEAR account ID generated by the CLI -SPONSOR_PRIVATE_KEY= Set this to the private key generated by the CLI -``` - -- Start up Docker: - - - - - - ```bash - sudo systemctl start docker - ``` - - - - - - Simply open the Docker Desktop application or run: - - ```bash - open -a Docker - ``` - - - - - -- Install dependencies: - - ```bash - npm i - ``` - ---- - -## Local Development - -- Make sure `environment` is set to `local` in the `deployment.yaml` file. - -- In one terminal, run the Shade Agent CLI: - - ```bash - shade deploy - ``` - - On Linux, the CLI may prompt you to enter your **sudo password**. - -- Then, start your app: - - ```bash - npm run dev - ``` - - Your app will start on http://localhost:3000 - -- Lastly, you need to **whitelist** the agent in the agent contract (only needed for local development). In another terminal, run: - - ```bash - shade whitelist - ``` - - Enter the agent account ID displayed when starting the app. - ---- - -## TEE Deployment - -- Change the `environment` to `TEE` in the `deployment.yaml` file. - -- Run the Shade Agent CLI - - ```bash - shade deploy - ``` - - The CLI on Linux may prompt you to enter your **sudo password**. - -The CLI will output the URL of your app. - -After deploying to Phala Cloud, monitor your deployments and delete unused ones to avoid unnecessary costs. You can manage your deployments from the[dashboard](https://cloud.phala.network/dashboard). - ---- - -## Interacting with the Agent - -You can interact with your agent via the APIs directly or via the frontend contained in this repo. - -### Direct - -For Phala deployments, swap localhost:3000 for your deployment URL. - -- Get information about the agent: - - ``` - http://localhost:3000/api/agent-info - ``` - -- Get the derived Ethereum Sepolia price pusher account ID and its balance (you will need to fund this account): - - ``` - http://localhost:3000/api/eth-info - ``` - -- Request the agent to update the price of Eth: - - ``` - http://localhost:3000/api/transaction - ``` - -### Frontend - -To start the frontend, run: - -```bash -cd frontend -npm i -npm run dev -``` - -To use the frontend with your Phala deployment, change the `API_URL` to the Phala URL in your [config.js](https://github.com/NearDeFi/shade-agent-template/tree/main/frontend/src/config.js) file. - -In the frontend, you can review the approved **measurements** and **PPID** in the contract and details of the registered agents. - ---- - -## Next Steps - -Now that you've successfully deployed your first Shade Agent, proceed to the [key components page](./components.md) to understand how agents work and learn how to customize it for your specific use case. - - \ No newline at end of file diff --git a/docs/ai/shade-agents/reference/agent-contract.md b/docs/ai/shade-agents/reference/agent-contract.md deleted file mode 100644 index 08aa988c285..00000000000 --- a/docs/ai/shade-agents/reference/agent-contract.md +++ /dev/null @@ -1,301 +0,0 @@ ---- -id: agent-contract -title: Agent Contract -sidebar_label: Agent Contract -description: "Review the agent contract template for the Shade Agent Framework." ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import { Github } from "@site/src/components/UI/Codetabs"; - -The **agent contract** is the on-chain component of the Shade Agent Framework. It handles agent registration, measurement, and PPID approval, and enforces that only valid agents can call specific methods. - -On this page, you'll walk through the key components of the reference agent contract and how to implement your own **agent-gated functions**. You may need to change other parts of the contract depending on your use case. The full source lives in the [shade-agent-template](https://github.com/NearDeFi/shade-agent-template/tree/2.0/agent-contract) repo. - ---- - -## Flow - -High-level flow: -- The owner deploys and initializes the contract. -- The owner approves measurements and PPIDs. -- Each agent calls `register_agent` with a valid attestation. -- Valid agents can then call agent-gated methods. - ---- - -## Initialization - -The `new` method initializes the contract and takes four arguments (the CLI can initialize the contract with defaults): -- **`requires_tee`**: Whether the contract runs in local or TEE mode. This switches the behavior of the contract so you can move easily between local and TEE deployments. -- **`attestation_expiration_time_ms`**: How long a registration stays valid for after an agent registers. -- **`owner_id`**: The account ID allowed to call owner-only methods. The owner should usually be a multisig. -- **`mpc_contract_id`**: The Chain Signatures MPC contract that the agent contract will call for multichain signing. - -On initialization, the rest of the contract state is set to empty. - - - -If your contract needs additional state, add it in the init method and extend the `Contract` struct accordingly. - ---- - -## Measurements, PPID, Whitelist, and Agent Management - -The **owner** of the contract can manage the approved measurements, PPIDs, whitelist, and agents. - -### Measurements - -The `approved_measurements` decide what code an agent is allowed to run. The CLI will approve a set of measurements for your agent when run. You can learn more about measurements [here](../concepts/terminology.md#measurements). - -The owner controls which measurements are approved and can add or remove them over time. A typical agent code upgrade flow is: approve a new set of measurements, allow a transition period (e.g. a week) so operators can update agents to run the new code, then remove the old measurements. - - - -### PPID - -The `approved_ppids` decide which physical TEE CPUs an agent may run on. The CLI will approve a list of default PPIDs when run. You can learn more about PPID [here](../concepts/terminology.md#ppid). - - - -### Agent - -Agents become authorized by calling `register_agent`; the owner can also remove an agent at any time. Use removal to clean up invalid agents or to revoke access if a TEE were to become compromised. - - - -:::note -A removed agent can re-register by calling `register_agent` with a valid attestation. -::: - -### Whitelist - -The **whitelist** applies only in **local mode**. It defines which account IDs may call **agent-gated methods**, since in local mode, the contract cannot verify that an agent is running approved code. Use `shade whitelist` in the CLI to add an account. You can learn more about whitelisting [here](../concepts/terminology.md#whitelisted-accounts). - - - ---- - -## Register Agent - -Agents register by calling `register_agent`. The method checks that the agent has a valid attestation via `verify_attestation`; if it passes, the agent is stored with its measurements, PPID, and validity period (determined by `attestation_expiration_time_ms`). - -An agent must attach 0.00486 NEAR to cover its own storage cost in the contract. If you change how much data is stored per agent, update the `STORAGE_BYTES_TO_REGISTER` constant accordingly. - - - -By default, an agent that provides a valid attestation can register. Meaning that anyone may be able to run an agent and register. Depending on your use case, you may want to add additional restrictions to an agent, for example, an allow-list of accounts, proof of a shared secret, or a limit of one agent per contract. - -### Verify Attestation - -`verify_attestation` decides if an agent is allowed to register. Its behavior depends on whether the contract is in TEE or local mode. - -#### TEE Mode - -In TEE mode (`requires_tee = true`), the method accepts the agent only if it supplies a valid attestation, which is checked using the `verify` function provided by the [shade-attestation crate](https://github.com/NearDeFi/shade-agent-framework/tree/main/shade-attestation), which takes the list of approved measurements and PPIDs, the current timestamp (in seconds), and the expected `report_data`. - - - -The attestation’s **report data** must contain the NEAR account ID of the agent. This binds the attestation to the same TEE where the agent’s key was created to prevent replay of valid attestations. Report data is passed as **bytes**. - - - -#### Local Mode - -In local mode (`requires_tee = false`), the method approves the agent if the caller is whitelisted and the mock measurements and PPID are approved in the contract. No real attestation is verified. - - - ---- - -## Require Valid Agent - -You can restrict methods so only valid agents can call them using the helper `require_valid_agent`. An agent that registered earlier may no longer be valid. To gate a method: call `require_valid_agent`, and if it returns `Some(promise)`, execute the promise. - - - -:::caution Handle the promise -You must execute the promise returned by `require_valid_agent` when it is `Some(promise)`; otherwise, the invalid agent can still call the function. -::: - -`require_valid_agent` first loads the agent from storage; if the caller is not registered, it panics. - - - -It then checks whether the agent is still valid. It's valid if its registration has not expired (determined by `attestation_expiration_time_ms`), its measurements are still in the approved set, and its PPID is still approved. - - - - - - - - - - - - - - - -If the agent is valid, then the function will return `None`. If the agent is invalid, it will be removed from the map of agents, an event will be emitted detailing the reasons for removal, and a promise will be returned from the function that will call `fail_on_invalid_agent` in the next block. - - - -The promise calls `fail_on_invalid_agent`, which panics in the next block. Panicking in the next block (rather than the current one) ensures the agent is removed from storage; panicking in the current block would revert that removal. - - - ---- - -## Your Functions - -The template includes an example `request_signature` function. It allows a **valid agent** to request a signature for a transaction payload from the MPC contract, so you can sign transactions for most chains. You can learn more about singing transactions for different chains in the [chain signatures documentation](../../../chain-abstraction/chain-signatures/implementation). - - - -You should implement your own **agent-gated functions** in this `your_functions.rs` file, following the same pattern: call `require_valid_agent`, then run your logic. - -:::tip On chain guardrails -A key part of the Shade Agent Framework is the ability to implement **on-chain guardrails**. This gives protection against unauthorized actions - even if the TEE is compromised. It's strongly recommended that you build actions within the agent contract rather than in the agent itself, for example, using the [omni-transaction-rs](https://github.com/Omni-rs/omni-transaction-rs) library. -::: - ---- - -## Building the Contract - -Usually, you build and deploy with the **Shade Agent CLI**: `shade deploy`. To build the contract manually, use the following command: - - - - - - For Linux, you can compile the contract directly with [cargo near](https://github.com/near/cargo-near/releases/latest). - - - ```bash - cargo near build non-reproducible-wasm --no-abi - ``` - - - - - - Because of a required dependency in the shade-attestation crate, agent contracts cannot be built on Mac machines. You can build the contract inside a Docker container using the following command: - - ```bash - docker run --rm -v "$(pwd)":/workspace pivortex/near-builder@sha256:cdffded38c6cff93a046171269268f99d517237fac800f58e5ad1bcd8d6e2418 cargo near build non-reproducible-wasm --no-abi - ``` - - If you would like to build the image yourself, you can use [this Dockerfile](https://github.com/NearDeFi/shade-agent-framework/blob/main/contract-builder/Dockerfile). - - - - - -:::note -The `--no-abi` flag is used to build the contract without an ABI. This is required because the shade-attestation crate currently doesn't support ABI generation. -::: - ---- - -## Calling Methods - -The **Shade Agent CLI** calls the main contract methods when you run `shade deploy`, but it does not cover every method. For methods the CLI doesn’t support, use the [NEAR CLI](../../../../tools/near-cli) or create scripts using the [NEAR API](../../../../tools/near-api). \ No newline at end of file diff --git a/docs/ai/shade-agents/reference/api.md b/docs/ai/shade-agents/reference/api.md deleted file mode 100644 index 72212828bb5..00000000000 --- a/docs/ai/shade-agents/reference/api.md +++ /dev/null @@ -1,207 +0,0 @@ ---- -id: api -title: Shade Agent API -sidebar_label: Shade Agent API -description: "Use the Shade Agent API (TypeScript/JavaScript) to connect your agent to the Shade Agent Framework" ---- - -## API Overview - -**Shade Agent API** is a **TypeScript/JavaScript** library that connects your agent to the Shade Agent Framework. It abstracts TEE complexity and simplifies calls to the agent contract. The same API works locally and inside a TEE; its behavior differs slightly by environment, but the interface stays the same. - ---- - -## Installation - -```bash -npm install @neardefi/shade-agent-js -``` - ---- - -## Initializing the Client - -Sets up the client with the desired configuration. - -```ts -import { ShadeClient } from "@neardefi/shade-agent-js"; - -const agent = await ShadeClient.create({ - networkId: "testnet", // or "mainnet" - agentContractId: process.env.AGENT_CONTRACT_ID, // example-agent-contract.testnet - sponsor: { - accountId: process.env.SPONSOR_ACCOUNT_ID, // example-sponsor.testnet - privateKey: process.env.SPONSOR_PRIVATE_KEY, // ed25519:4vKz... - }, - rpc: provider, - numKeys: 10, - derivationPath: process.env.SPONSOR_PRIVATE_KEY, // ed25519:4vKz... -}); -``` - -### **Arguments** - -All arguments are optional. Omitting some makes certain methods unavailable. - -| Argument | Description | -|----------|-------------| -| `networkId` | The NEAR network: `mainnet` or `testnet` (defaults to testnet). | -| `agentContractId` | The account ID of your agent contract that your agent will interact with. | -| `sponsor` | The account details of a sponsor account to fund the agent. | -| `rpc` | A [near-api-js provider](https://near.github.io/near-api-js/modules/providers.html) object used by the client (defaults to a basic RPC provider based on the network). | -| `numKeys` | The number of key pairs the agent has (1–100, defaults to 1). More keys increase transaction throughput; the client rotates through them when signing transactions. | -| `derivationPath` | A string used to derive deterministic agent account IDs when running locally. Lets you avoid re-whitelisting and re-funding the agent on each run. Use a unique secret (e.g. a private key). If two agents share the same derivation path, they get the same account ID and could control contracts they are not authorized for. | - ---- - -## Agent Account ID - -Returns the ephemeral NEAR account ID of the agent. - -```ts -const accountId = agent.accountId(); -``` - ---- - -## Agent Balance - -Returns the NEAR balance of the agent's account in human-readable units (e.g. 1 = one NEAR). If the account does not exist, it returns 0. - -```ts -const balance = await agent.balance(); -``` - ---- - -## Fund Agent - -Transfers NEAR from the configured sponsor account to the agent's account. - -```ts -await agent.fund(0.3); // 0.3 NEAR -``` - -Requires `sponsor` in config. - ---- - -## Check Whitelist - -Checks whether the agent's account is whitelisted for local mode. - -```ts -const whitelisted = await agent.isWhitelisted(); -``` - -**TEE vs local:** -- TEE: Always returns `null`. -- Local: Returns `true` if the agent is whitelisted, `false` otherwise. - -Requires `agentContractId` in config. - ---- - -## Register Agent - -Registers the agent's account in the agent contract. Returns `true` on success, throws on failure. - -```ts -await agent.register(); -``` - -**TEE vs local:** -- TEE: Registers with a real attestation. -- Local: Registers with a mock attestation. - -Requires `agentContractId` in config. - ---- - -## Call Agent Contract - -Calls a **change function** on the agent contract (uses gas, can change state). Returns the call result or throws. - -```ts -const result = await agent.call({ - methodName: "example_call_function", - args: { arg1: "value1", arg2: "value2" }, - gas: BigInt("300000000000000"), // Optional - deposit: "0", // Optional -}); -``` - -Requires `agentContractId` in config. - ---- - -## View Agent Contract - -Calls a **view function** on the agent contract (no gas, read-only). Returns the call result or throws. - -```ts -const result = await agent.view({ - methodName: "example_view_function", - args: { arg1: "value1", arg2: "value2" }, -}); -``` - -Requires `agentContractId` in config. - ---- - -## Get Attestation - -Returns the attestation in the format the agent contract expects. - -```ts -const attestation = await agent.getAttestation(); -``` - -**TEE vs local:** -- TEE: Returns a real attestation. -- Local: Returns a mock attestation. - ---- - -## Get Private Keys - -Returns the agent's ephemeral private keys. Useful for when wanting to use other NEAR tooling (e.g. near-api-js) or for other operations like encrypting messages. - -:::danger -Never log, expose, or store these keys. Doing so allows registered keys to be used outside of verified code (the keys can execute any operation not authorized by the measurements). Do not hold funds or important state with these keys — they are ephemeral and lost if the TEE reboots. -::: - -```ts -const keys = agent.getPrivateKeys({ acknowledgeRisk: true }); -``` - ---- - -## Utilities - -### sanitize - -Aims to redact private keys from strings, objects, or Errors. Use before logging. - -```ts -import { sanitize } from "@neardefi/shade-agent-js"; -console.error(sanitize(someError)); -``` - -:::warning -Sanitize redacts common key patterns, but can't catch every case or other sensitive data. Add your own sanitization where needed so no sensitive data is emitted from the TEE. -::: - -### toThrowable - -Returns an error with a sanitized message. Use when rethrowing. - -```ts -import { toThrowable } from "@neardefi/shade-agent-js"; -try { - await client.register(); -} catch (e) { - throw toThrowable(e); -} -``` \ No newline at end of file diff --git a/docs/ai/shade-agents/reference/cli.md b/docs/ai/shade-agents/reference/cli.md deleted file mode 100644 index 6fd2fa02a0a..00000000000 --- a/docs/ai/shade-agents/reference/cli.md +++ /dev/null @@ -1,217 +0,0 @@ ---- -id: cli -title: Shade Agent CLI -sidebar_label: Shade Agent CLI -description: "Use the Shade Agent CLI to deploy your Shade Agent." ---- - -The **Shade Agent CLI** makes it easy to deploy a Shade Agent. It includes building and deploying your agent contract, building and publishing your agent's Docker image, and deploying the agent to Phala Cloud. The CLI revolves around a `deployment.yaml` file that configures how your Shade Agent will be deployed. - ---- - -## Installation - -```bash -npm install -g @neardefi/shade-agent-cli -``` - ---- - -## Commands - -### Deploy - -Deploys your Shade Agent with the configuration as defined by the `deployment.yaml` file. - -```bash -shade deploy -``` - -Must be executed in the same directory as your `deployment.yaml` file. - -### Plan - -Generates a preview of how your Shade Agent will be deployed as defined by the `deployment.yaml` file. - -```bash -shade plan -``` - -Must be executed in the same directory as your `deployment.yaml` file. - -### Whitelist - -Whitelists a specified agent's account ID in the agent contract as defined by the `deployment.yaml` file. This is only relevant for local mode. - -```bash -shade whitelist -``` - -Must be executed in the same directory as your `deployment.yaml` file. - -### Auth - -Configure **NEAR** and **Phala** credentials required for deploying your Shade Agent. Must be run before using the `deploy` or `whitelist` commands. - -```bash -shade auth -``` - ---- - - -## deployment.yaml Reference - -CLI configurations are read from a single `deployment.yaml` file in the project root. The following sections describe what each key configures. - -### Top-Level Keys - -| Key | Required | Description | -|-----|----------|-------------| -| **environment** | Yes |`local` or `TEE`. Controls whether the agent runs locally or in a Phala TEE. | -| **network** | Yes | `testnet` or `mainnet`. Controls whether the agent contract is on NEAR testnet or mainnet. | -| **docker_compose_path** | Yes if TEE | Path to the Docker Compose file (e.g. `./docker-compose.yaml`). Used for building the Docker image and deploying your application to a TEE. | -| **agent_contract** | Yes | Agent contract configuration. See [agent_contract](#agent_contract) for more details. | -| **approve_measurements** | No | If enabled, sets allowed measurements in the agent contract. | -| **approve_ppids** | No | If enabled, sets allowed PPIDs in the agent contract.| -| **build_docker_image** | No (TEE only) | If enabled and environment is TEE, builds a new Docker image for your agent, publishes it, and updates the Docker Compose with the new image. | -| **deploy_to_phala** | No (TEE only) | If enabled and environment is TEE, deploys the Docker Compose to Phala Cloud. | -| **whitelist_agent_for_local** | No | Config for the `shade whitelist` command to whitelist an agent's account ID whilst in local mode (not used by the shade deploy command). | -| **os** | No | Override OS for tooling: `mac` or `linux`. If omitted, the CLI auto-detects from the current platform. | - -### agent_contract - -| Key | Required | Description | -|-----|----------|-------------| -| **contract_id** | Yes | NEAR account ID for the agent contract (e.g. `example-contract-123.testnet`). Must be unused if you are deploying a new contract. | -| **deploy_custom** | No | If enabled, the CLI creates the contract account with the same private key as the account set up via `shade auth`, and deploys a new contract. If the contract account already exists, it will be deleted and recreated to remove the old contract. | - -#### deploy_custom - -`agent_contract.deploy_custom` - -| Key | Required | Description | -|-----|----------|-------------| -| **enabled** | No | If `false`, deploy_custom is skipped. | -| **funding_amount** | Yes | NEAR amount to fund the new contract account with, used to fund the deployment of the contract (number between 0 and 100). | -| **delete_key** | No | If `true`, the key for the contract account is deleted after deployment, locking the contract (defaults `false`). | -| **deploy_from_source** | One of three | Build the contract from source and deploy: set `enabled: true` and `source_path` to the contract directory. | -| **deploy_from_wasm** | One of three | Deploy a pre-built WASM file: set `enabled: true` and `wasm_path` to the `.wasm` file. | -| **use_global_by_hash** | One of three | Deploy using a global contract: set `enabled: true` and `global_hash` to the contract hash. | -| **init** | No | If enabled, initializes the contract via a function call. | - -#### init - -`agent_contract.deploy_custom.init` - -| Key | Required | Description | -|-----|----------|-------------| -| **enabled** | No | If `false`, init is skipped. | -| **method_name** | Yes | Contract method to call (e.g. `new`). | -| **args** | Yes | Arguments to call the method with. | -| **tgas** | No | Gas for the call (default 30). | - -Placeholders in args: - -- `` — Resolves to `true` or `false` depending on `environment`. -- `<7_DAYS>` — Resolves to 7 days in milliseconds (604800000). -- `` — Resolves to the NEAR account ID from `shade auth`. -- `` — Resolves to the default MPC contract for the selected `network` (testnet/mainnet). - -### approve_measurements - -| Key | Required | Description | -|-----|----------|-------------| -| **enabled** | No | If `false`, measurements are not approved. | -| **method_name** | Yes | Contract method to call (e.g. `approve_measurements`). | -| **args** | Yes | Arguments to call the method with. | -| **tgas** | No | Gas for the call (default 30). | - -Placeholders in args: - -- `` — Resolves to real calculated measurements for the application for TEE and mock measurements for local. - -### approve_ppids - -| Key | Required | Description | -|-----|----------|-------------| -| **enabled** | No | If `false`, PPIDs are not approved. | -| **method_name** | Yes | Contract method to call (e.g. `approve_ppids`). | -| **args** | Yes | Arguments to call the method with. | -| **tgas** | No | Gas for the call (default 30). | - -Placeholders in args: - -- `` — Resolves to a list of all PPIDs of devices on Phala Cloud for TEE and a mock PPID for local. - -### build_docker_image (TEE Only) - -| Key | Required | Description | -|-----|----------|-------------| -| **enabled** | No | If `false`, the Docker image is not built. If disabled, the CLI will use the existing Docker Compose file. | -| **tag** | Yes | Docker image tag (e.g. `username/my-first-agent`) for building and pushing. | -| **cache** | Yes | Boolean; whether to use caching in the build process. | -| **dockerfile_path** | Yes | Path to the Dockerfile to use for the build process (e.g. `./Dockerfile`). | - -### deploy_to_phala (TEE Only) - -| Key | Required | Description | -|-----|----------|-------------| -| **enabled** | No | If `false`, deployment to Phala Cloud is skipped. | -| **app_name** | Yes | Phala Cloud app (CVM) name. | -| **env_file_path** | Yes | Path to the environment variables file loaded when deploying to Phala (e.g. `./.env`). | - -### whitelist_agent_for_local (local only) - -Used by `shade whitelist`. No `enabled` flag; if the section is present, the command is available. - -| Key | Required | Description | -|-----|----------|-------------| -| **method_name** | Yes | Contract method to call (e.g. `whitelist_agent_for_local`). | -| **args** | Yes | Arguments to call the method with. | -| **tgas** | No | Gas for the call (default 30). | - -Placeholders in args: - -- `` — Replaced with the agent account ID you provide when running `shade whitelist`. - -:::info -Currently, the CLI only supports measurement calculation and Phala Cloud deployment for fixed configurations on DStack. If you need to deploy with different configurations, you can calculate the measurements and deploy to Phala by other means; you can ask for assistance with this in our [support group](https://t.me/+mrNSq_0tp4IyNzg8). - -
- Fixed Dstack configurations - -- Dstack Version: dstack-0.5.5 -- Hardware: 1vCPU and 2GB RAM (tdx.small on Phala) -- Key Provider: Phala Key Provider - -**App compose configs** -- Pre Launch Script: v0.0.12 - -... - -- features: ["kms", "tproxy-net"], -- gateway_enabled: true, -- kms_enabled: true, -- local_key_provider_enabled: false, -- manifest_version: 2, -- name: "", -- no_instance_id: false, -- public_logs: true, -- public_sysinfo: true, -- public_tcbinfo: true, -- runner: "docker-compose", -- secure_time: false, -- storage_fs: "zfs", -- tproxy_enabled: true, - -
-::: - ---- - - - -## Example deployment.yaml Configurations - -You can view a list of [example deployment.yaml configurations here](https://github.com/NearDeFi/shade-agent-framework/tree/main/shade-agent-cli/example-deployment-files). \ No newline at end of file diff --git a/docs/ai/shade-agents/tutorials/ai-dao/dao-agent-contract.md b/docs/ai/shade-agents/tutorials/ai-dao/dao-agent-contract.md deleted file mode 100644 index f4e9a8dfc14..00000000000 --- a/docs/ai/shade-agents/tutorials/ai-dao/dao-agent-contract.md +++ /dev/null @@ -1,215 +0,0 @@ ---- -id: dao-agent-contract -title: DAO Agent Contract -sidebar_label: DAO Agent Contract -description: "Learn about the key parts of the agent contract as part of the Verifiable AI DAO Shade Agent tutorial, including how to create a custom agent contract and create a yield and resume-based Shade Agent." ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import {Github} from "@site/src/components/UI/Codetabs" - -On this page, you'll look at the DAO smart contract that uses the yield and resume pattern to enable the Shade Agent to vote on proposals within a `single transaction` flow. - -The AI DAO contract is a fork of the [default agent contract](https://github.com/NearDeFi/shade-agent-js/tree/main/contracts/sandbox), modified to remove the `request_signature` function and implement DAO-specific functionality. This page focuses on the DAO-specific code, as agent registration follows the default contract. - ---- - -## Contract Structure - -The DAO agent contract extends the default contract with additional state: -- The DAO's manifesto -- A map of pending proposals -- A map of finalized proposals -- The current proposal ID - - - -### Manifesto - -The manifesto consists of two components: the `manifesto text` that defines the DAO's decision-making principles and a `hash` of the manifesto for verifying that the agent uses the correct manifesto when voting. - - - -The manifesto and its hash are initialized as empty strings. - -### Pending Proposals - -This stores all proposals that are awaiting a vote from the agent. Each proposal request includes the `proposal text` and `yield ID` - a unique identifier for each yielded promise (each active pending proposal request). - - - -The map is initialized as empty. - -### Finalized Proposals - -This stores all proposals that the agent has voted on. Each finalized proposal contains the `proposal text`, `proposal result` (enum of `Approved` or `Rejected`), and `reasoning` for the vote. The result and reasoning are provided by the agent. - - - - - - - - - - - - - - -The map is initialized as empty. - -### Current Proposal ID - -The current proposal ID is an integer identifier that increments with each proposal request and is used to identify different proposals. If a proposal is not voted on by the agent, then the proposal ID will still increment, leading to `non-consecutive proposal IDs` within the finalized proposals map. Note that the proposal ID is different to the yield ID. - ---- - -## Setting the Manifesto - -The contract provides a function to set the manifesto, which only the contract `owner` can call. The owner provides the manifesto text, which is `hashed` and stored along with the text in the contract's state. In production, the owner would typically be a `multisig` contract. - - - ---- - -## Creating a Proposal - -When a user calls `create_proposal` with the proposal text, the function creates a `yielded promise`. The promise will call the specified function,`return_external_response`, with the arguments of `proposal_id` and `proposal_text` when the promise resolves. The promise resolves when the agent produces a valid response or the promise times out - after 200 blocks (~2 minutes). - - - -The function then reads the `yield ID` from the `register` for the created promise. The `yield ID` is a unique hash identifier that ensures responses are matched to the correct pending proposal. The yield ID is generated by the `register`, which takes an integer identifier that specifies which register is being used, since there is just one yield-resume register here, it's set to zero. - - - -A new proposal request is created and inserted into the pending proposals map, allowing the agent to fetch proposals that it needs to respond to. - - - -Lastly, the function `returns the yielded promise` making it ready to be resumed. - - - ---- - -## Agent Response and Validation - -Once the agent makes its decision, it calls the `agent_vote` function. This function checks whether the response is valid and resumes the yielded promise if so. - -The agent responds with the `yield ID` for the promise it intends to resume, the `proposal ID` it's voting on, the `hash of the proposal`, the `hash of the manifesto`, the `vote`, and the `reasoning` behind the vote. - - - - - - - - - - - - - - -Most importantly, the function checks if the caller is a `valid registered agent`, ensuring the DAO only makes decisions through the expected process (that's defined by the verifiable agent). - - - -The function verifies that the `manifesto hash` and `proposal hash` submitted by the agent match those stored in the contract. This verification ensures the agent used the correct manifesto and proposal when voting, `removing trust in the RPC` used to fetch proposals and manifesto data. Otherwise, there could be a bug in the RPC causing it to fetch the wrong details and the RPC or a malicious intermediary could intentionally provide the wrong details to try to corrupt the vote. - - - -If any of these checks fail then the function panics and the promise is not be resumed (it could be resumed later with valid arguments before timeout). If all checks pass, then the function resumes the promise with the specified yield ID and the agent's response as an argument. - - - ---- - -### Proposal Finalization - -When the yielded promise resolves (either resumed or timed out), the `return_external_response` function is called. This function is private and can only be called by the yielded promise, not by external accounts. - -The function receives arguments from both when the promise was created and when it was resumed. - - - -The function first removes the proposal being responded to from the pending proposals map, regardless of whether the promise was resumed or timed out. - - - -If the response is valid, i.e. the yielded promise was successfully resumed, the proposal and the result are added to the map of finalized proposals, and a response is returned to the caller within the same transaction that the proposal was submitted in. - - - -If the response is invalid, i.e. the yielded promise timed out, the function returns a promise to call `fail_on_timeout`, which panics and produces a failed [receipt](../../../../protocol/transaction-execution) in a separate block to provide a clear error to the user (the return_external_response receipt is still successful). - - - - - - - - - - - - - - -:::tip -Visit the [yield and resume section](../../../../smart-contracts/anatomy/yield-resume.md) of the docs for a deeper look into this pattern. -::: - ---- - -## View Functions - -The contract exposes [view functions](https://github.com/NearDeFi/verifiable-ai-dao/blob/main/contract/src/dao.rs#L188-L223) to retrieve the manifesto text, pending proposals, and finalized proposals. - ---- - -## Next Steps - -Now that you understand the DAO agent contract implementation, continue to the [agent page](./dao-agent.md) to learn about the verifiable agent that queries the contract for pending requests and casts a vote using an LLM. \ No newline at end of file diff --git a/docs/ai/shade-agents/tutorials/ai-dao/dao-agent.md b/docs/ai/shade-agents/tutorials/ai-dao/dao-agent.md deleted file mode 100644 index c9741d31d92..00000000000 --- a/docs/ai/shade-agents/tutorials/ai-dao/dao-agent.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -id: dao-agent -title: DAO Agent -sidebar_label: DAO Agent -description: "Learn about the key parts of the agent as part of the Verifiable AI DAO Shade tutorial that walks through how to index the agent contract, using verifiable AI, and interacting with the custom agent contract." ---- - -import {Github} from "@site/src/components/UI/Codetabs" - -On this page, you'll examine the agent component of the DAO. The agent continuously monitors for new proposals, uses an LLM to evaluate them, and submits its vote along with reasoning back to the smart contract. - ---- - -## Starting the Agent - -Before an agent can execute any actions on-chain, it must first be `registered`. When in production (running on Phala Cloud, not locally), the agent runs a loop to check its registration status. An agent can see if it's registered using the `agentInfo` function provided by `shade-agent-js`; once registered, `agentInfo` will return a checksum. - -After the agent is registered, it starts the `responder`, which contains the core logic of the agent. - - - ---- - -## Indexing Proposals - -Once started, the responder begins a continuous loop to check for pending proposals by calling `get_pending_proposals` on the contract using the `agentView` function provided by `shade-agent-js`. The `agentView` function makes a view call (a gasless transaction that does not change the contract's state) to the selected function on the agent contract. - - - -If proposals are found, the agent extracts the `proposal text` and `yield ID` from the oldest pending proposal , then fetches the current manifesto from the DAO by calling `get_manifesto`. - - - -Having retrieved both the proposal and manifesto, the agent is ready to make its decision using an LLM. - ---- - -## Voting with an LLM - -To make a decision on the proposal, the agent uses an LLM provided by [NEAR AI](https://docs.near.ai/cloud/get-started/). NEAR AI provides verifiable and private inference by running LLMs in GPU TEEs. In this tutorial, the DAO uses NEAR AI for its `verifiable` component. This allows the agent verify that no one is interfering with the LLM response, as could happen with centralized model hosting. The agent knows the response from the LLM is actually a function of the input, and comes from the expected model. - -:::note -In this tutorial, the agent does not actually verify the attestation from the LLM. Full verification will be added in a future update to the tutorial. -::: - -The DAO uses the `Open AI SDK` to interact with the model. First, the agent sets up the client passing the `base URL` for NEAR AI and an `API key` for the Cloud (we'll explain how to obtain a key in the next section). - - - - -A request to an LLM typically takes two prompts: -- **The System Message** sets the `behavior and role` of the LLM. In this tutorial, the message explains to the model that it's acting as a DAO and needs to vote Approved or Rejected on proposals, making its decisions based on the manifesto. -- **The User Message** is the `input` that the LLM responds to. In typical chat applications, this would be any message you type to the assistant. In this tutorial, the user message is a combination of the proposal and the DAO's manifesto. - - - -Next, the agent constructs the `JSON request` to send to the model. There are several important aspects of this request: -- The request specifies the `model` to call - in this tutorial, DeepSeek V3 0324. You can find a full list of [available models here](https://cloud.near.ai/models). -- The request is using `non-streaming` mode. This means the model waits until the full response is ready before returning it, rather than streaming, where the response is sent piece by piece while the model is still generating it. Non-streaming is simpler here as the agent doesn't need to display the response or take any action until the whole response is ready. -- The request uses `tool calling` to ensure that the model responds with a vote of exactly `Approved` or `Rejected` and `reasoning` for its choice. If the model fails to conform to the required output, it will return an error. You can read more on [tool calling/function calling here](https://platform.openai.com/docs/guides/function-calling). - - - -The agent then sends the request to the model, extracts the vote and reasoning from the response, and performs a double check to ensure the response is in the expected format. - - - ---- - -## Submitting the Vote - -Once the agent receives the response from the LLM, it's nearly ready to submit the vote to the agent contract. Before sending the vote, the agent `hashes` both the proposal it's voting on and the manifesto it's using to make it's decision. This is done so the DAO can verify that the agent used the correct proposal and manifesto to vote and that the query wasn't corrupted by the RPC or intercepted and modified on transit to the agent. - - - -The agent then calls `agent_vote` on the agent contract using the `agentCall` function provided by `shade-agent-js` to cast its vote. It includes the yield ID of the proposal's yielded promise that it's resuming, along with all required response fields. - - - ---- - -## Next Steps - -That completes the overview of the DAO system as a whole! You can now fork the [repository](https://github.com/NearDeFi/verifiable-ai-dao/tree/main) to create your own yield and resume-based Shade Agent. On the [final page](./deploying.md) of this tutorial, you'll learn how to deploy the AI DAO yourself. \ No newline at end of file diff --git a/docs/ai/shade-agents/tutorials/ai-dao/deploying.md b/docs/ai/shade-agents/tutorials/ai-dao/deploying.md deleted file mode 100644 index b7ab0780148..00000000000 --- a/docs/ai/shade-agents/tutorials/ai-dao/deploying.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -id: deploying -title: Deploying the AI DAO -sidebar_label: Deploying the AI DAO -description: "Learn how to deploy the Verifiable AI DAO Shade Agent which includes how to deploy a custom agent contract." ---- - -:::warning -The Verifiable AI DAO tutorial uses an old version of the Shade Agent Framework, which contains known critical vulnerabilities and has a different architecture. - -No representations or warranties are made regarding security, correctness, or fitness for any purpose. Use of this software is entirely at your own risk. - -The tutorial will be updated to use the latest version of the Shade Agent Framework in the future. -::: - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import {Github} from "@site/src/components/UI/Codetabs" - -On this page we'll guide you through deploying your own instance of the AI DAO. - ---- - -## Prerequisites - -- First please make sure you have all the [prerequisites from our quickstart](../../getting-started/quickstart/deploying.md#prerequisites). - -- Additionally, you'll need to set up an account on `NEAR AI`, fund it, and obtain an API key. This can be done through the [NEAR AI Dashboard](https://cloud.near.ai/dashboard/overview). - ---- - -- First, `clone` the [repo](https://github.com/NearDeFi/verifiable-ai-dao/tree/main). - - ```bash - git clone https://github.com/NearDeFi/shade-agent-template - cd shade-agent-template - ``` - -- Rename the `.env.development.local.example` file name to `.env.development.local` and configure your `environment variables`. - -- Start up Docker: - - - - - - ```bash - sudo systemctl start docker - ``` - - - - - - Simply open the Docker Desktop application or run: - - ```bash - open -a Docker - ``` - - - - - -- Install dependencies - - ```bash - npm i - ``` - ---- - -## Local Development - -In this tutorial, the AI DAO uses a `custom agent contract`. Because of this, you need to manually switch the contract deployed depending on whether you're developing locally or deploying the agent to a TEE. - -- For local development, you need to comment out the [require approved code hash line](https://github.com/NearDeFi/verifiable-ai-dao/blob/main/contract/src/dao.rs#L114) within the `agent_vote` function. This allows anyone to call the function, not just a registered agent. By design, it's impossible for an agent to register when running locally, as it can't provide a valid TEE attestation. - - - -- Since the AI DAO uses a custom agent contract, you need to compile it yourself. - - - - - - ```bash - cargo near build non-reproducible-wasm - ``` - - - - - - ```bash - docker run --rm -v "$(pwd)":/workspace pivortex/near-builder@sha256:cdffded38c6cff93a046171269268f99d517237fac800f58e5ad1bcd8d6e2418 cargo near build non-reproducible-wasm - ``` - - - - - -- Make sure that the NEXT_PUBLIC_contractId prefix is set to `ac-proxy.` followed by your NEAR account ID so the CLI is configured for local deployment. - -- Run the Shade Agent CLI with the `wasm` and `funding` flags. The wasm flag tells the CLI the path to the wasm file of the agent contract you're deploying, and the funding flag tells the CLI how much NEAR to fund the deployment with. 7 NEAR is sufficient for the size of the DAO contract. - - ```bash - shade-agent-cli --wasm contract/target/near/contract.wasm --funding 7 - ``` - - The CLI may prompt you to enter your sudo password. - ---- - -## TEE Deployment - -- Re-introduce the [require approved code hash line](https://github.com/NearDeFi/verifiable-ai-dao/blob/main/contract/src/dao.rs#L114) so it requires an agent to be registered, meaning it's running in a genuine TEE and executing the expected agent code. - - - -- Because the contract has changed since you last deployed it, you need to compile it again. - - - - - - ```bash - cargo near build non-reproducible-wasm - ``` - - - - - - ```bash - docker run --rm -v "$(pwd)":/workspace pivortex/near-builder@sha256:cdffded38c6cff93a046171269268f99d517237fac800f58e5ad1bcd8d6e2418 cargo near build non-reproducible-wasm - ``` - - - - - -- Change the NEXT_PUBLIC_contractId prefix to `ac-sandbox.` followed by your NEAR account ID so the CLI is configured for TEE deployment. - -- Run the Shade Agent CLI with the `wasm` and `funding` flags. - - ```bash - shade-agent-cli --wasm contract/target/near/contract.wasm --funding 7 - ``` - - The CLI may prompt you to enter your sudo password. - - After deploying to Phala Cloud, monitor your deployments and delete unused ones to avoid unnecessary costs. You can manage your deployments from the[dashboard](https://cloud.phala.network/dashboard). - ---- - -### Interacting with the AI DAO - -- Set the DAO manifesto in the contract. Since the `NEAR_ACCOUNT_ID` in your environment variables is automatically assigned the `owner` of the agent contract, you need to sign this transaction using its `SEED_PHRASE`. - - ```bash - near contract call-function as-transaction YOUR_CONTRACT_ID set_manifesto json-args '{"manifesto_text": "This DAO only approves gaming-related proposals and rejects everything else"}' prepaid-gas '100.0 Tgas' attached-deposit '0 NEAR' sign-as YOUR_ACCOUNT_ID network-config testnet sign-with-seed-phrase 'YOUR_SEED_PHRASE' --seed-phrase-hd-path 'm/44'\''/397'\''/0'\''' send - ``` - - Make sure to replace `YOUR_CONTRACT_ID`, `YOUR_ACCOUNT_ID`, and `YOUR_SEED_PHRASE` with the appropriate values before executing the command. You can optionally change the manifesto_text as well. - -- Set your `NEXT_PUBLIC_contractId` in the frontend's [config.js](https://github.com/NearDeFi/verifiable-ai-dao/blob/main/frontend/src/config.js) file. - -- Start the frontend - - ```bash - cd frontend - npm i - npm run dev - ``` \ No newline at end of file diff --git a/docs/ai/shade-agents/tutorials/ai-dao/overview.md b/docs/ai/shade-agents/tutorials/ai-dao/overview.md deleted file mode 100644 index 30d4024ac61..00000000000 --- a/docs/ai/shade-agents/tutorials/ai-dao/overview.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -id: overview -title: Overview -sidebar_label: Overview -description: "A brief overview of the Verifiable AI DAO tutorial built using the Shade Agent Framework that walks through NEAR native deployments, using yield and resume with Shade Agents and leveraging verifiable AI." ---- - -import { TryDemo } from '@site/src/components/TryDemo'; - -:::warning -The Verifiable AI DAO tutorial uses an old version of the Shade Agent Framework, which contains known critical vulnerabilities and has a different architecture. - -No representations or warranties are made regarding security, correctness, or fitness for any purpose. Use of this software is entirely at your own risk. - -The tutorial will be updated to use the latest version of the Shade Agent Framework in the future. -::: - -In this tutorial, you'll explore how to build a `fully verifiable AI DAO` using the Shade Agent Framework. The Verifiable AI DAO is a DAO smart contract that uses a Shade Agent with a verifiable LLM to vote on governance proposals according to its predefined manifesto, to create transparent, AI-driven governance that is decentralized and auditable from end-to-end. - -This tutorial also serves as a `template` for building `yield and resume-based Shade Agents`. This is a smart contract that, when called, halts its execution for the verified agent to complete some logic and resume the transaction when it has a result, enabled by NEAR's asynchronous design. This pattern allows the agent and LLM become a part of the contract, enabling smart contracts with extended capabilities of a backend server that can make API calls and use LLM inference. This is especially useful when making cross-contract calls to smart contracts that use yield and resume, allowing you to receive the result in the callback - for example, an on-demand oracle. - ---- - -## What You'll Learn - -This tutorial demonstrates how key components of the Shade Agent Framework work together with NEAR's broader tech stack to create a product that is `decentralized and verifiable throughout the entire stack`. The tutorial covers: -- **NEAR-native Shade Agent**: How to develop a Shade Agent that operates exclusively on the NEAR blockchain -- **Yield and Resume Pattern**: Building a Shade Agent that uses the yield and resume pattern -- **Verifiable AI Integration**: Implementing a Shade Agent that uses NEAR AI's verifiable/private inference - ---- - -## Required Knowledge - -To understand this tutorial, you should have familiarity with these concepts: -- [Shade Agents](../../getting-started/introduction.md) -- [NEAR Smart Contracts](../../../../smart-contracts/what-is.md) - ---- - -## Getting Started - -The complete source code for this tutorial is available in the [verifiable-ai-dao repository](https://github.com/NearDeFi/verifiable-ai-dao). - -Continue to the [Agent Contract section](./dao-agent-contract.md) to get started and learn about implementing yield and resume-based agent contracts. \ No newline at end of file diff --git a/docs/ai/shade-agents/tutorials/tutorials-overview.md b/docs/ai/shade-agents/tutorials/tutorials-overview.md deleted file mode 100644 index 23f78b42262..00000000000 --- a/docs/ai/shade-agents/tutorials/tutorials-overview.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -id: tutorials-overview -title: Tutorials and Templates -sidebar_label: Overview -description: "Review the list of our Shade Agent tutorials and templates." ---- - -import { TryDemo } from '@site/src/components/TryDemo'; - -This section provides tutorials and templates to help you build Shade Agents faster and learn key concepts. - ---- - -## Quickstart - -Explore the [Quickstart docs](../getting-started/quickstart/deploying.md) - -### Summary - -The Quickstart features a verifiable Oracle secured by the Shade Agent Framework that pushes the price of ETH to a smart contract on Ethereum. - -### Template - -The Quickstart provides a basic template for building your first multichain Shade Agent. This is the recommended starting point for developers new to Shade Agents. - -### Learning Outcomes - -- Learn how to get started building with Shade Agents -- Learn the key components of a Shade Agent -- Learn to deploy a Shade Agent -- Learn how to sign transactions for different chains - ---- - -## Verifiable AI DAO - -Explore the [Verifiable AI DAO docs](./ai-dao/overview.md) - -### Summary - -The Verifiable AI DAO is a DAO smart contract that uses a Shade Agent with a verifiable LLM to vote on governance proposals according to its predefined manifesto, ensuring transparent and auditable AI-driven governance decisions. - -### Template - -The Verifiable AI DAO is a template for building yield and resume-based Shade Agents. - -### Learning Outcomes - -- Learn to build a Shade Agent that uses the yield and resume pattern -- Learn to develop a Shade Agent that operates exclusively on the NEAR blockchain -- Learn to use NEAR AI's verifiable/private inference within a Shade Agent \ No newline at end of file diff --git a/docs/index.md b/docs/index.md index 57da9a93899..76cfd5407b6 100644 --- a/docs/index.md +++ b/docs/index.md @@ -37,7 +37,7 @@ import AIBadges from '@site/src/components/AIBadges'; > diff --git a/website/scripts/copy-md-to-static.mjs b/website/scripts/copy-md-to-static.mjs index 6ffe0dedf6a..b2c3c971e45 100644 --- a/website/scripts/copy-md-to-static.mjs +++ b/website/scripts/copy-md-to-static.mjs @@ -40,7 +40,7 @@ const JSX_COMPONENTS = [ 'Language', 'Block', 'Quiz', 'Progress','MultipleChoice', 'Option', 'LantstoolLabel', 'TryOutOnLantstool', - 'MovingForwardSupportSection', 'SigsSupport', 'TryDemo', + 'MovingForwardSupportSection', 'ExplainCode', 'CodeBlock', 'LandingHero', 'Faucet', 'AIBadges', 'CreateTokenForm', 'MintNFT', diff --git a/website/sidebars.js b/website/sidebars.js index adda9d43814..e68b589448d 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -192,50 +192,7 @@ const sidebar = { items: [ 'ai/introduction', 'ai/tools-for-ai', - { - "Shade Agents": [ - { - "Getting Started": [ - "ai/shade-agents/getting-started/introduction", - { - "Quickstart": [ - "ai/shade-agents/getting-started/quickstart/deploying", - "ai/shade-agents/getting-started/quickstart/components", - ] - }, - ] - }, - { - "Concepts": [ - "ai/shade-agents/concepts/framework-overview", - "ai/shade-agents/concepts/what-can-you-build", - "ai/shade-agents/concepts/ai-inference", - "ai/shade-agents/concepts/terminology", - "ai/shade-agents/concepts/security", - ] - }, - { - "Tutorials": [ - "ai/shade-agents/tutorials/tutorials-overview", - { - "AI DAO": [ - "ai/shade-agents/tutorials/ai-dao/overview", - "ai/shade-agents/tutorials/ai-dao/dao-agent-contract", - "ai/shade-agents/tutorials/ai-dao/dao-agent", - "ai/shade-agents/tutorials/ai-dao/deploying", - ] - } - ] - }, - { - "Reference": [ - "ai/shade-agents/reference/api", - "ai/shade-agents/reference/cli", - "ai/shade-agents/reference/agent-contract", - ] - }, - ] - }, + 'ai/shade-agents' ], }, { diff --git a/website/src/components/LandingHero/options.js b/website/src/components/LandingHero/options.js index 03ad2f9cb7b..9a60b189040 100644 --- a/website/src/components/LandingHero/options.js +++ b/website/src/components/LandingHero/options.js @@ -76,29 +76,4 @@ Start using your new NEAR app: * npm run dev `, }, - { - name: "AI Agents", - label: "ai.js", - description: "Build agents that anyone can verify and trust, with seamless cross-chain capabilities", - buttonText: "Build an AI Agent", - buttonLink: "/ai/introduction", - language: "js", - code: `import { Hono } from "hono"; -import { agentAccountId, agent } from "@neardefi/shade-agent-js"; - -const app = new Hono(); - -app.get("/", async (c) => { - const accountId = await agentAccountId(); - const balance = await agent("getBalance"); - - return c.json({ - accountId, - balance, - }); -}); - - -export default app;`, - }, ]; diff --git a/website/src/components/TryDemo.jsx b/website/src/components/TryDemo.jsx deleted file mode 100644 index 8bec811d65c..00000000000 --- a/website/src/components/TryDemo.jsx +++ /dev/null @@ -1,67 +0,0 @@ -import React from 'react'; - -/** - * Generic demo button component for linking to live demos - * - * @param {string} url - The URL to the live demo - * @param {string} text - Optional custom text (defaults to "Try the live demo") - * @param {boolean} newTab - Whether to open in new tab (defaults to true) - */ -export const TryDemo = ({ - url, - text = "Try the live demo", - newTab = true -}) => { - - return ( - - ); -}; - -export default TryDemo; diff --git a/website/src/components/sigsSupport.js b/website/src/components/sigsSupport.js deleted file mode 100644 index 32ba4d56112..00000000000 --- a/website/src/components/sigsSupport.js +++ /dev/null @@ -1,120 +0,0 @@ -import React from 'react'; - -export function SigsSupport() { - return ( -
-
-
Office Hours
-

- Join our weekly 1-on-1, 15 minute sessions for personalized developer support and guidance for Chain Signatures and Shade Agents. -

- -
- -
-
Developer Support Groups
-

- Access async support and connect with other builders in our Telegram Communities. -

- -
- -
-
Reach Out
-

- If your team is building or considering building a production application using Chain Signatures or Shade Agents, please fill our our interest form. -

- -
- - -
- ); -} \ No newline at end of file diff --git a/website/src/pages/office-hours.jsx b/website/src/pages/office-hours.jsx index d52ece9f8f3..61d6f44d733 100644 --- a/website/src/pages/office-hours.jsx +++ b/website/src/pages/office-hours.jsx @@ -3,7 +3,6 @@ import Card from '@site/src/components/UI/Card' // Are you a developer building on NEAR? Do you have questions about the NEAR protocol, tools, or best practices? Join our weekly office hours to connect with technical experts and get your questions answered. -// Building a Shade Agent? Using chain signatures? Book a session with Owen: https://calendly.com/owen-proximity/office-hours // Building a Smart Contract? A general question about the NEAR protocol? Book a session with Guille: https://calendar.app.google/6q2ssGUmvFcMoJk97 @@ -24,23 +23,18 @@ export default function OfficeHours() { Book Support -
- - Book Support - -
- - +
Book Support diff --git a/website/static/llms.txt b/website/static/llms.txt index 74180e9236e..a127316cb45 100644 --- a/website/static/llms.txt +++ b/website/static/llms.txt @@ -33,9 +33,6 @@ NEAR is a blockchain platform designed for building scalable, user-friendly dece - **NEAR AI**: /ai/introduction Build AI agents that can execute on-chain actions, manage wallets, and interact with smart contracts. -- **Shade Agents**: /ai/shade-agents/getting-started/introduction - Framework for creating autonomous AI agents with on-chain identity and capabilities. - ### Developer Tools - **NEAR CLI**: /tools/cli Command-line interface for deploying contracts, managing accounts, calling functions.