### Local Development Setup Source: https://github.com/near/intents/blob/main/crates/outlayer/README.md Copy the local environment example file and start the worker using Docker Compose for local development. ```sh cd crates/outlayer/worker cp env.local.example .env # first time only docker compose up --build ``` -------------------------------- ### Example Usage of Sha256 Digest Source: https://github.com/near/intents/blob/main/_autodocs/utility-crates.md Provides a concrete example of using the `Sha256` hasher from the `defuse-digest` crate. It shows how to initialize a hasher, update it with data, and finalize it to get the resulting digest. ```rust use defuse_digest::{Digest, Sha256}; let mut hasher = Sha256::new(); hasher.update(b"data"); let digest = hasher.finalize(); ``` -------------------------------- ### Create Swap Example Source: https://github.com/near/intents/blob/main/_autodocs/additional-contracts.md Example of creating a new swap request with specified tokens, amounts, and a timeout. Requires both parties to deposit tokens before acceptance. ```rust let swap_id = contract.create_swap( "bob.near".parse()?, TokenId::Nep141("usdc.near".parse()?), 1_000_000, TokenId::Nep141("dai.near".parse()?), 950_000, 1000, // 1000 blocks timeout ); ``` -------------------------------- ### Example of Creating a Deterministic Account Intent Source: https://github.com/near/intents/blob/main/_autodocs/nep-standards-integration.md Provides a concrete example of constructing the StateInit structure and an AuthCall intent to deploy code and initialize storage on a deterministic account. ```rust let state_init = StateInit { global_code_hash: [/* code_hash */; 32], initial_storage: borsh::to_vec(&InitArgs { /* ... */ })?, }; let intent = AuthCall { state_init: Some(state_init), contract_id: "factory.near".parse()?, msg: "init_and_verify".to_string(), }; ``` -------------------------------- ### Execute Intents Example Source: https://github.com/near/intents/blob/main/_autodocs/defuse-contract-interface.md Example of calling the `execute_intents` function from an off-chain context, signing with a private key and handling the resulting promise. ```rust // Call from off-chain, signing with Alice's key let signed_intent = SignedIntent { payload: ..., // Signed NEP-413 payload public_key: alice_pub_key, }; contract.execute_intents(vec![signed_intent]).then(/* handle result */) ``` -------------------------------- ### Accept Swap Example Source: https://github.com/near/intents/blob/main/_autodocs/additional-contracts.md Example of accepting an existing swap request. This action triggers the atomic exchange of tokens if conditions are met. ```rust contract.accept_swap(swap_id)?; ``` -------------------------------- ### Deploy Deterministic Contract Example Source: https://github.com/near/intents/blob/main/_autodocs/additional-contracts.md Example of deploying a contract using a registered code hash and initialization arguments. This derives a predictable account ID for the new contract instance. ```rust let account_id = deployer.deploy_deterministic( code_hash, borsh::to_vec(&InitArgs { /* ... */ })?, )?; // Returns: "0s" + hex(keccak256(StateInit)[12..32]) ``` -------------------------------- ### Multi-Contract Integration Example Source: https://github.com/near/intents/blob/main/_autodocs/additional-contracts.md Demonstrates a complete workflow involving escrow swaps, token deposits, intent execution, and treasury logging. ```rust // 1. Create escrow swap let swap_id = escrow.create_swap( "bob.near".parse()?, token1_id, 1_000_000, token2_id, 950_000, 1000 )?; // 2. Both parties deposit tokens intents.deposit(token1_id, 1_000_000)?; // 3. Partner accepts via intent let intent = Intent::AuthCall(AuthCall { contract_id: escrow_id, msg: format!("accept_swap:{}", swap_id), attached_deposit: NearToken::ZERO, ..Default::default() }); intents.execute_intents(vec![signed_intent])?; // 4. Tokens swapped atomically // 5. Log in treasury logger logger.log_transfer( alice, bob, amounts, format!("Swap {} completed", swap_id) )?; ``` -------------------------------- ### Install near-oa CLI Tool Source: https://github.com/near/intents/blob/main/contracts/outlayer-app/README.md Install the `near-oa` command-line tool, an extension for `near-cli-rs`, to compute StateInit for an outlayer-app contract instance. ```bash cargo install --path contracts/outlayer-app --example near-oa ``` -------------------------------- ### Register Code Example Source: https://github.com/near/intents/blob/main/_autodocs/additional-contracts.md Example of registering contract code with the GlobalDeployer. The returned code hash can be used for subsequent deployments. ```rust let code_hash = deployer.register_code(contract_code)?; ``` -------------------------------- ### Install Phala CLI Source: https://github.com/near/intents/blob/main/crates/outlayer/README.md Install the Phala CLI globally for managing deployments on Phala Cloud. Alternatively, use `npx phala ` for ad-hoc execution. ```sh npm install -g phala ``` -------------------------------- ### Engine Execution Example Source: https://github.com/near/intents/blob/main/_autodocs/execution-engine.md Demonstrates how to create and use the `Engine` to execute signed intents. It shows the basic flow of initializing the engine with state and an inspector, executing intents, and handling potential errors. ```rust use defuse_core:: engine::{Engine, Inspector}, intents::DefuseIntents; // Create engine with state and inspector let mut engine = Engine::new(my_state, my_inspector); // Execute signed intents match engine.execute_signed_intents(vec![signed_payload]) { Ok(transfers) => { // Process transfers println!("Executed {} transfers", transfers.len()); } Err(DefuseError::InvalidSignature) => { // Handle signature failure } Err(e) => { // Handle other errors } } ``` -------------------------------- ### TokenId Creation Examples Source: https://github.com/near/intents/blob/main/_autodocs/types-primitives.md Demonstrates how to create TokenId instances for fungible (Nep141) and non-fungible (Nep171) tokens. ```rust let ft_token: TokenId = TokenId::Nep141( Nep141TokenId::new("usdc.near".parse()?) ); let nft_token: TokenId = TokenId::Nep171( Nep171TokenId::new( "nft.near".parse()?, "token_id_1" ) ); ``` -------------------------------- ### Install Rust Nightly and Cargo Fuzz Source: https://github.com/near/intents/blob/main/crates/primitives/decimal/fuzz/README.md Installs the Rust nightly toolchain and the cargo-fuzz utility, which are prerequisites for running fuzz tests. ```sh rustup install nightly cargo install cargo-fuzz ``` -------------------------------- ### Contract Composition Example Source: https://github.com/near/intents/blob/main/_autodocs/additional-contracts.md Illustrates how a contract can implement multiple traits to combine various functionalities. ```rust pub struct DefuseContract; impl Defuse for DefuseContract {} // Automatically implements: // - Intents (intent execution) // - RelayerKeys (relayer management) // - AccountManager (account state) // - FungibleTokenReceiver (NEP-141) // - MultiTokenReceiver (NEP-245) // - AccessControllable (roles) // - Pausable (pause/unpause) // - ControllerUpgradable (upgrades) ``` -------------------------------- ### Amounts Usage Example Source: https://github.com/near/intents/blob/main/_autodocs/types-primitives.md Illustrates creating an Amounts instance and adding token amounts. The `add` method performs checked arithmetic. ```rust let mut amounts = Amounts::default(); amounts.add("nep141:usdc.near".parse()?, 1_000_000)?; amounts.add("nep141:near.near".parse()?, 500_000?); ``` -------------------------------- ### Install near-gds CLI Extension Source: https://github.com/near/intents/blob/main/contracts/global-deployer/README.md Installs the `near-gds` command-line tool using Cargo. This tool is an extension for `near-cli-rs`. ```bash cargo install --path . --example near-gds ``` -------------------------------- ### Rust Type Signatures Example Source: https://github.com/near/intents/blob/main/_autodocs/README.md Demonstrates the standard Rust syntax used for type signatures in the documentation, including structs, traits, and enums. ```rust pub struct Example { pub field: Type, } pub trait Trait { fn method(&self, param: Type) -> ReturnType; } pub enum Enum { Variant(Type), } ``` -------------------------------- ### Simulate Intents for Fee Estimation Source: https://github.com/near/intents/blob/main/_autodocs/defuse-contract-interface.md Example of simulating intents to estimate gas costs and potential outcomes before actual execution. ```rust // Query simulation for fee estimation let sim_result = contract.simulate_intents( vec![alice_intent.clone()] ); println!("Would succeed: {}", sim_result.success); println!("Gas estimate: {:?}", sim_result.transfers); ``` -------------------------------- ### Execute Intents with Deposit Source: https://github.com/near/intents/blob/main/_autodocs/defuse-contract-interface.md Example of signing intents off-chain and then executing them on the contract with an attached NEAR deposit. ```rust // Sign intents off-chain let alice_intent = SignedIntent { /* ... */ }; let bob_intent = SignedIntent { /* ... */ }; // Call contract with attached NEAR deposit contract.execute_intents( vec![alice_intent, bob_intent], /* attached_deposit: 10 NEAR */ ) ``` -------------------------------- ### Deploy Global Account ID using StateInit JSON Source: https://github.com/near/intents/blob/main/contracts/global-deployer/README.md Deploys a global account ID using the `state-init` command with data obtained from the `near gds --quiet` command. This example demonstrates piping the output of `near gds` into `near contract state-init`. ```bash near contract state-init \ use-global-account-id 0s384bfa53f1718c7f53eaaa1b43c55e2aea3ef309 \ data-from-json "$(near gds \ --owner-id intents.sputnik-dao.near --index 42 \ --approve 0x6c71114931fe91153b868f2cb29c5db70e59677d6d2e40404b3b9044d8052266 \ --quiet)" ``` -------------------------------- ### Intent with Global Code Hash Example Source: https://github.com/near/intents/blob/main/_autodocs/additional-contracts.md Example of constructing an AuthCall intent that utilizes a global code hash for contract deployment. This allows for sharded and cost-effective contract instantiation. ```rust let intent = AuthCall { state_init: Some(StateInit { global_code_hash: code_hash, initial_storage: init_args, }), contract_id: deployer_id, msg: "".to_string(), }; ``` -------------------------------- ### Logging Inspector Implementation Example Source: https://github.com/near/intents/blob/main/_autodocs/execution-engine.md An example implementation of the Inspector trait that logs intent execution and events to the console. Useful for debugging and observing engine behavior. ```rust struct LoggingInspector; impl Inspector for LoggingInspector { fn on_intent_executed(&mut self, signer: &AccountIdRef, hash: CryptoHash, nonce: Nonce) { println!("Intent {:?} by {} committed", hex::encode(hash), signer); } fn on_event(&mut self, event: DefuseEvent) { println!("Event: {:?}", event); } } ``` -------------------------------- ### TokenId Serialization Example Source: https://github.com/near/intents/blob/main/_autodocs/types-primitives.md Demonstrates serializing a TokenId to both JSON and Borsh formats using standard NEAR SDK libraries. ```rust use near_sdk::{serde_json, borsh}; let token: TokenId = "nep141:usdc.near".parse()?; // JSON let json = serde_json::to_string(&token)?; // Output: "nep141:usdc.near" // Borsh let binary = borsh::to_vec(&token)?; ``` -------------------------------- ### UD128 Creation and Normalization Example Source: https://github.com/near/intents/blob/main/_autodocs/types-primitives.md Demonstrates creating a UD128 decimal value and shows how normalization works. `UD128::new(2, 1200)` is equivalent to `UD128::new(1, 120)`. ```rust let price = UD128::new(6, 1_500_000)?; assert_eq!(price.decimals(), 6); assert_eq!(price.digits(), 1_500_000); ``` -------------------------------- ### Configure Defuse Crypto for Full Feature Set (Testing) Source: https://github.com/near/intents/blob/main/_autodocs/utility-crates.md Example TOML configuration for the `defuse-crypto` crate enabling the full feature set, suitable for testing. Includes serde, borsh, ed25519, secp256k1, p256, and abi. ```toml [dependencies] defuse-crypto = { version = "0.1", features = ["serde", "borsh", "ed25519", "secp256k1", "p256", "abi"] } ``` -------------------------------- ### Complete NEP-413 Payload Example Source: https://github.com/near/intents/blob/main/_autodocs/payload-framework.md An example of a complete NEP-413 payload, including the nested message structure and the corresponding signature details. This format is used for standard message signing on NEAR. ```json { "message": "{\"signer_id\": \"alice.near\", \"verifying_contract\": \"intents.near\", \"deadline\": {\"block_height\": 100000}, \"nonce\": \"AAAA...\", \"message\": {\"intents\": [{\"intent\": \"transfer\", \"receiver_id\": \"bob.near\", \"tokens\": {\"nep141:usdc.near\": \"1000000\"}}]}}", "nonce": "8e2iKL2+3x8iKvVRc8y+FQ==", "recipient": "intents.near", "callback_url": null } ``` ```json { "payload": { /* above */ }, "public_key": "6j2h3... (Ed25519 base58)", "signature": "5iKV9... (Ed25519 base58)" ``` -------------------------------- ### Cancel Swap Example Source: https://github.com/near/intents/blob/main/_autodocs/additional-contracts.md Example of canceling a swap request, typically after a timeout period has passed. This refunds the deposited tokens to the respective parties. ```rust contract.cancel_swap(swap_id)?; ``` -------------------------------- ### Configure Defuse Crypto for Off-Chain/SDK Target Source: https://github.com/near/intents/blob/main/_autodocs/utility-crates.md Example TOML configuration for the `defuse-crypto` crate when targeting off-chain or SDK usage. Includes features for serde, ed25519, secp256k1, and p256. ```toml [dependencies] defuse-crypto = { version = "0.1", features = ["serde", "ed25519", "secp256k1", "p256"] } ``` -------------------------------- ### Get Nonce View Method Source: https://github.com/near/intents/blob/main/contracts/treasury-logger/README.md Retrieves the current nonce value, which will be used for the next emitted event. The nonce is returned as a decimal string. ```rust pub fn get_nonce(&self) -> U128 ``` -------------------------------- ### Configure Defuse Crypto for Smart Contract Target Source: https://github.com/near/intents/blob/main/_autodocs/utility-crates.md Example TOML configuration for the `defuse-crypto` crate when targeting a NEAR smart contract. Includes features for NEAR contract, ed25519, secp256k1, and borsh. ```toml [dependencies] defuse-crypto = { version = "0.1", features = ["near-contract", "ed25519", "secp256k1", "borsh"] } ``` -------------------------------- ### Wrap and Unwrap NEAR Tokens Source: https://github.com/near/intents/blob/main/_autodocs/utility-crates.md Provides functions for converting NEAR tokens to wrapped NEAR (wNEAR) and vice versa. Requires appropriate setup for token conversions. ```rust pub fn wrap_near(amount: NearToken) -> Result<()> pub fn unwrap_wnear(amount: U128) -> Result<()> ``` -------------------------------- ### Initialize and Use Wallet SDK Source: https://github.com/near/intents/blob/main/_autodocs/utility-crates.md Provides a high-level SDK for wallet integration. Use the `Wallet` struct to create and execute intents, facilitating interactions with NEAR wallets. ```rust pub struct Wallet { contract_id: AccountId, } impl Wallet { pub fn new(contract_id: AccountId) -> Self pub fn create_intent(&self, ...) -> Result pub fn execute_intents(&self, ...) -> Result<()> } ``` -------------------------------- ### Basic Deployment Architecture Source: https://github.com/near/intents/blob/main/_autodocs/architecture-overview.md A simplified diagram showing the interaction between a user, relayer, wallet, and the Verifier contract. ```text User ─┐ ├─→ Relayer ─→ Verifier (intents.near) Bob ──┤ └─→ Wallet ────┘ ``` -------------------------------- ### Build All Contracts Source: https://github.com/near/intents/blob/main/README.md Builds all smart contracts within the repository simultaneously. ```shell make ``` -------------------------------- ### Build Contracts Command Source: https://github.com/near/intents/blob/main/_autodocs/additional-contracts.md Shows the make commands used to build specific smart contracts, outputting artifacts to the 'res/' directory. ```bash make CONTRACT=defuse REPRODUCIBLE=1 make CONTRACT=poa/factory make CONTRACT=escrow-swap ``` -------------------------------- ### Get Owner ID Source: https://github.com/near/intents/blob/main/contracts/global-deployer/README.md Returns the current owner's account ID. This is a view method. ```rust pub fn gd_owner_id(&self) -> AccountId { self.owner_id.clone() } ``` -------------------------------- ### Compute StateInit for Global Deployer Source: https://github.com/near/intents/blob/main/contracts/global-deployer/README.md Computes the `StateInit` for a global-deployer contract, outputting a JSON map of base64-encoded key-value pairs. This command requires the owner account ID. ```bash near gds --owner-id test.near --index 1 ``` -------------------------------- ### Escrow Swap Initialization Parameters Source: https://github.com/near/intents/blob/main/contracts/escrow-swap/README.md Defines the fixed and immutable parameters for an escrow swap contract. These include maker, source and destination tokens, price, deadline, and optional configurations for partial fills, refunds, receiving destinations, whitelists, and fees. ```json { // The only maker authorized to fund the contract with `src_token` "maker": "maker.near", // The token the maker wants to sell. Supported variants: // * `nep141:` // * `nep245::` "src_token": "nep245:intents.near:nep141:usdt.tether-token.near", // The token the maker expects to receive in return. Supported variants: // * `nep141:` // * `nep245::` "dst_token": "nep245:intents.near:nep141:wrap.near", // The minimum price, expressed as decimal floating-point number // representing the amount of raw units of `dst_token` per 1 raw unit // of `src_token`, i.e. dst per 1 src. "price": "0.0000001667", // Deadline for taker(s) to fill the escrow, in RFC3339 format. // After deadline has exceeded, anyone can close the escrow (permissionless). "deadline": "2024-07-09T00:01:00Z", // (optional) Whether partial fills are allowed. "partial_fills_allowed": true, // (optional) Override where to refund `src_token` after escrow is closed. "refund_src_to": { // (optional) Receiver's account_id, `maker` otherwise. "receiver_id": "vault.maker.near", // (optional) memo for `ft/mt_transfer[_call]()` "memo": "", // (optional) Message for `ft/mt_transfer_call()`. // If not specified, `ft/mt_transfer()` will be used by default. "msg": "", // (optional) Minimum amount of gas that should be attached // to `ft/mt_transfer[_call]()` "min_gas": "50000000000000" }, // (optional) Override where to receive `dst_token` on each fill. "receive_dst_to": { // (optional) Receiver's account_id, `maker` otherwise. "receiver_id": "treasury.maker.near", // (optional) memo for `ft/mt_transfer[_call]()` "memo": "", // (optional) Message for `ft/mt_transfer_call()`. // If not specified, `ft/mt_transfer()` will be used by default. "msg": "", // (optional) Minimum amount of gas that should be attached // to `ft/mt_transfer[_call]()`. "min_gas": "50000000000000" }, // (optional) Whitelist for takers that allowed to fill the escrow. // // Empty whitelist means anyone can fill. // // If consists of a single taker, then he has a permission to close // the escrow even before the deadline. "taker_whitelist": ["solver-bus-proxy.near"], // (optional) Protocol fees (collected on on `dst_token`) "protocol_fees": { // The fee that is taken on `taker_dst_used` on every fill. // // Fees are measured in "pips", where: // 1 pip == 1/100th of bip == 0.0001%. "fee": 2000, // 0.2% // The fee that is taken on surplus, i.e. price improvement // above maker's `price` (see above), i.e. difference between // `taker_dst_used` and `maker_want_dst = src_out * price`. // // Fees are measured in "pips", where: // 1 pip == 1/100th of bip == 0.0001%. "surplus": 50000, // 5% // Recipient of protocol fees. "collector": "protocol.near" }, // (optional) Integrator fees: mapping between fee collector // and corresponding fee taker on `taker_dst_used`. // // Fees are measured in "pips", where: // 1 pip == 1/100th of bip == 0.0001%. "integrator_fees": { "front-end.near": 3000, // 0.3% "partner.near": 1000 // 0.1% }, // (optional) Contract that's allowed to forward `on_auth()` calls "auth_caller": "intents.near", // 32 bytes of entropy encoded in hex, used for address derivation. "salt": "9e3779b97f4a7c1552d27dcd1234567890abcdef1234567890abcdef1234" } ``` -------------------------------- ### Off-Chain Message Construction: Create Intent Sequence Source: https://github.com/near/intents/blob/main/_autodocs/payload-framework.md Demonstrates the first step in the off-chain signing workflow: creating an `DefuseIntents` sequence containing various `Intent` types. ```rust let intents = DefuseIntents { intents: vec![ Intent::Transfer(transfer), Intent::AddPublicKey(add_key), ], }; ``` -------------------------------- ### Get Current Code Hash Source: https://github.com/near/intents/blob/main/contracts/global-deployer/README.md Returns the SHA-256 hash of the currently deployed code. Returns a zero hash if no code is deployed. This is a view method. ```rust pub fn gd_code_hash(&self) -> [u8; 32] { self.code_hash.unwrap_or([0u8; 32]) } ``` -------------------------------- ### Get Approved Code Hash Source: https://github.com/near/intents/blob/main/contracts/global-deployer/README.md Returns the currently approved SHA-256 hash for the next deployment. Returns a zero hash if no hash is approved. This is a view method. ```rust pub fn gd_approved_hash(&self) -> [u8; 32] { self.approved_hash.unwrap_or([0u8; 32]) } ``` -------------------------------- ### Run All Tests Source: https://github.com/near/intents/blob/main/README.md Executes all tests for the smart contracts. ```shell make test ``` -------------------------------- ### Initialize and Deploy Contracts in Sandbox Source: https://github.com/near/intents/blob/main/_autodocs/utility-crates.md Defines a Sandbox environment for local testing, allowing for contract deployment and initialization. Use this for integration tests. ```rust pub struct Sandbox { /* */ } impl Sandbox { pub fn new() -> Result pub fn deploy_contract(&mut self, ...) -> Result<()> } ``` -------------------------------- ### Compute StateInit for Outlayer App Contract Source: https://github.com/near/intents/blob/main/contracts/outlayer-app/README.md Use the `near oa` CLI tool to compute the `StateInit` JSON for a given set of parameters, including admin ID, code URL, and optionally code hash. ```bash near oa \ --admin-id alice.near \ --code-hash faf9e8500fdf8021ed8b3390580bbc86faf9e8500fdf8021ed8b3390580bbc86 \ --code-url https://example.com/contract.wasm ``` -------------------------------- ### Example JSON Error Response Source: https://github.com/near/intents/blob/main/_autodocs/errors-exceptions.md A sample JSON structure representing an error response from the NEAR Intents system. It includes a `success` flag, and an `error` object with `type` and `message` fields. ```json { "success": false, "error": { "type": "PublicKeyNotExist", "message": "public key 'ed25519:...' doesn't exist for account 'alice.near'" } } ``` -------------------------------- ### Compute StateInit with Quiet Output Source: https://github.com/near/intents/blob/main/contracts/global-deployer/README.md Computes the `StateInit` for a global-deployer contract, suppressing stderr and emitting only JSON. This is useful for piping the output to other tools like `near-cli`. ```bash near gds --owner-id intents.sputnik-dao.near --index 42 --approve 0x6c71114931fe91153b868f2cb29c5db70e59677d6d2e40404b3b9044d8052266 --quiet ``` -------------------------------- ### AuthCall Intent with Deterministic Account Initialization Source: https://github.com/near/intents/blob/main/_autodocs/nep-standards-integration.md Illustrates how an AuthCall intent can be configured to deploy code and initialize storage on a newly derived deterministic account ID as per NEP-616. ```rust pub struct AuthCall { pub state_init: Option, pub contract_id: AccountId, pub msg: String, } ``` -------------------------------- ### gd_deploy Source: https://github.com/near/intents/blob/main/contracts/global-deployer/README.md Deploys WASM code as a global contract on the current account. This is a permissionless operation requiring a sufficient deposit to cover storage. The provided `code` (raw WASM binary) must have a SHA-256 hash matching the `approved_hash`. Upon successful deployment, the `code_hash` state is updated, `approved_hash` is reset, and events for `Deploy` and `Approve` are emitted. Any unused deposit is refunded. ```APIDOC ## gd_deploy(code) ### Description Deploys WASM code as a global contract on the current account. This is a permissionless operation requiring a sufficient deposit to cover storage. The provided `code` (raw WASM binary) must have a SHA-256 hash matching the `approved_hash`. Upon successful deployment, the `code_hash` state is updated, `approved_hash` is reset, and events for `Deploy` and `Approve` are emitted. Any unused deposit is refunded. ### Method `FUNCTION_CALL` ### Parameters #### Function Call Parameters - **code** (`bytes`) - Required - Raw WASM binary. `sha256(code)` must equal `approved_hash`. ### State Change - `code_hash = sha256(code)` - `approved_hash = 0x000...000` ### Events - `Deploy { code_hash }` - `Approve { code_hash: 0x000...000, reason: Deploy(code_hash) }` ### Refund Unused deposit is returned to the caller. ``` -------------------------------- ### Create a Token Transfer Intent Source: https://github.com/near/intents/blob/main/_autodocs/defuse-core-intents.md Demonstrates how to construct a `Transfer` intent, specifying receiver, tokens, and an optional memo. This is useful for initiating token transfers within the Defuse Core system. ```rust use defuse_core:: intents::{DefuseIntents, Intent, Transfer, AddPublicKey}, amounts::Amounts, public_key::PublicKey; use near_sdk::{AccountId, json_types::U128}; use std::collections::BTreeMap; let mut amounts = BTreeMap::new(); amounts.insert("nep141:usdc.near".parse()?, U128(1_000_000)); let transfer = Transfer { receiver_id: "alice.near".parse()?, tokens: Amounts::new(amounts), memo: Some("Payment".to_string()), notification: None, }; let intents = DefuseIntents { intents: vec![Intent::Transfer(transfer)], }; ``` -------------------------------- ### Engine Constructor Source: https://github.com/near/intents/blob/main/_autodocs/execution-engine.md Creates a new engine instance with initial state and an event inspector. ```rust pub fn new(state: S, inspector: I) -> Self ``` -------------------------------- ### Base64 Serialization with Serde Source: https://github.com/near/intents/blob/main/_autodocs/utility-crates.md Demonstrates how to use the `Base64` struct with `serde_with` for base64-encoding byte arrays during serialization and deserialization. This is useful for handling binary data in JSON or other text-based formats. ```rust use serde_with::serde_as; use defuse_serde_utils::base64::Base64; #[serde_as] #[derive(Serialize, Deserialize)] pub struct Message { #[serde_as(as = "Base64")] pub data: Vec, } ``` -------------------------------- ### Construct Transaction with Pre-approved Hash Source: https://github.com/near/intents/blob/main/contracts/outlayer-app/README.md Construct a NEAR transaction to deploy an Outlayer App contract with a pre-approved hash using the `near-oa` tool to generate the `StateInit` JSON. ```bash near transaction construct-transaction \ state-init use-global-hash \ data-from-json "$(near-oa \ --admin-id \ --code-url \ --code-hash \ --quiet)" \ deposit 0NEAR \ skip \ network-config testnet \ sign-with-keychain ``` -------------------------------- ### Off-Chain Message Construction: Sign with Private Key Source: https://github.com/near/intents/blob/main/_autodocs/payload-framework.md Details the process of signing the prehashed NEP-413 message using a private key and constructing a `SignedNep413Payload` with the public key and signature. ```rust let signature = sign_with_key(nep413_message.prehash(), private_key)?; let signed = SignedNep413Payload { payload: nep413_message, public_key: derive_public_key(private_key), signature, }; ``` -------------------------------- ### StateInit Structure for Deterministic Accounts Source: https://github.com/near/intents/blob/main/_autodocs/nep-standards-integration.md Defines the structure required for initializing state when creating deterministic accounts using NEP-616. This includes the global code hash and initial storage. ```rust pub struct StateInit { pub global_code_hash: [u8; 32], pub initial_storage: Vec, } ``` -------------------------------- ### Replicate CVM to New Node Source: https://github.com/near/intents/blob/main/crates/outlayer/README.md Create a replica of an existing CVM on a specified target node. The replica inherits the environment variables from the source CVM. ```sh phala cvms replicate app_ --node-id -e .env ``` -------------------------------- ### Global Deployer Deployment Flow Source: https://github.com/near/intents/blob/main/contracts/global-deployer/README.md Illustrates the sequence of interactions between Owner, Caller, Global Deployer, and the Global Contracts Namespace during contract deployment. ```mermaid sequenceDiagram box Contracts participant Owner participant Caller participant GD as 0s1234..1234
(Global Deployer) end Note over NS: 0s1234..1234 => None box rgb(80, 120, 180) NEAR Protocol participant NS as Global Contracts
Namespace end Owner->>GD: gd_approve(old_hash, new_hash) Caller->>GD: gd_deploy(code) + deposit GD->>NS: deploy_global_contract_by_account_id Note over NS: 0s1234..1234 => code GD->>Caller: refund unused deposit ``` -------------------------------- ### Simulate Intents Source: https://github.com/near/intents/blob/main/_autodocs/defuse-contract-interface.md Simulates the execution of a list of signed intents without actually executing them. Useful for estimating fees and gas costs. ```APIDOC ## simulate_intents ### Description Simulates the execution of intents for fee estimation. ### Method `contract.simulate_intents(intents: Vec) -> SimulationOutput` ### Parameters #### Path Parameters - `intents` (Vec) - A vector of signed intents to simulate. ### Response #### Success Response (200) - `SimulationOutput` - An object containing simulation results, including success status, potential errors, state changes, and transfers. ``` -------------------------------- ### Wallet Contract Interface Source: https://github.com/near/intents/blob/main/_autodocs/additional-contracts.md Defines methods for managing user sessions, keys, and executing intents for account abstraction. ```rust pub trait WalletContract { fn add_session_key(&mut self, public_key: PublicKey, allowance: NearToken); fn remove_session_key(&mut self, public_key: PublicKey); fn execute_intent( &mut self, signer_id: AccountId, intent: Intent, ) -> Promise; } ``` -------------------------------- ### Wallet Integration Flow Source: https://github.com/near/intents/blob/main/_autodocs/architecture-overview.md Illustrates the sequence of actions when a user interacts with a wallet to create and approve an intent for transmission to a relayer. ```text User creates intent ↓ Wallet signs with NEP-413 / ERC-191 / TIP-191 ↓ User approves transaction ↓ Wallet transmits to relayer ↓ Relayer submits to Verifier contract ``` -------------------------------- ### Sign and Verify NEP-413 Payload Source: https://github.com/near/intents/blob/main/_autodocs/cryptographic-signatures.md Demonstrates how to create and verify a signed NEP-413 payload using the defuse_nep413 crate. Ensure the necessary public key and signature are correctly provided. ```rust use defuse_nep413::{Nep413Payload, SignedNep413Payload}; use defuse_crypto::SignedPayload; // Create a signed NEP-413 message let payload = Nep413Payload::new("Hello NEAR".to_string()) .with_nonce([0u8; 32]) .with_recipient("contract.near"); let signed = SignedNep413Payload { payload, public_key: [1u8; 32], // Ed25519 public key signature: [0u8; 64], // Ed25519 signature }; // Verify signature if let Some(recovered_pubkey) = signed.verify() { println!("Signature valid, public key: {:?}", recovered_pubkey); } ``` -------------------------------- ### Incremental Nonce Generation for Single Signer Source: https://github.com/near/intents/blob/main/contracts/wallet/README.md Use this algorithm for a single signer to generate nonces incrementally. This is recommended for reducing storage consumption. ```rust let nonce = self.next_nonce; self.next_nonce += 1; ``` -------------------------------- ### Key Rotation Sequence Diagram Source: https://github.com/near/intents/blob/main/contracts/wallet/README.md Visualizes the sequence of operations involved in rotating a wallet key using extensions. This process involves interactions between the signer, the new wallet extension, and the old wallet. ```mermaid sequenceDiagram actor signer participant new_wallet as new wallet: 0s456.. participant old_wallet as old wallet: 0s123.. signer -->>+ old_wallet: w_execute_signed(old_msg, old_proof) Note over old_wallet: ops: [add_extension: new_wallet]
out: new_wallet.state_init().w_execute_signed(new_msg, new_proof) old_wallet ->>- new_wallet: state_init +
w_execute_signed(new_msg, new_proof) activate new_wallet new_wallet ->>- old_wallet: w_execute_extension(request) activate old_wallet Note over old_wallet: ops: [signature: disable] deactivate old_wallet Note over signer: Key was rotated! signer -->>+ new_wallet: w_execute_signed() new_wallet ->>- old_wallet: w_execute_extension() ``` -------------------------------- ### First Deploy Outlayer CVM Source: https://github.com/near/intents/blob/main/crates/outlayer/README.md Deploy the outlayer application as a new CVM, specifying resources, image, and KMS. ```sh phala deploy \ --name outlayer \ --compose compose.yaml \ --vcpu 4 \ --memory 4G \ --disk-size 1G \ --image dstack-0.5.9 \ --kms phala ``` -------------------------------- ### Run Decimal Fuzz Tests Source: https://github.com/near/intents/blob/main/crates/primitives/decimal/fuzz/README.md Executes the 'parse' and 'roundtrip' fuzz tests using the cargo fuzz command with the nightly toolchain. ```sh cargo +nightly fuzz run parse ``` ```sh cargo +nightly fuzz run roundtrip ``` -------------------------------- ### Off-Chain Message Construction: Wrap in DefusePayload Source: https://github.com/near/intents/blob/main/_autodocs/payload-framework.md Shows how to wrap the `DefuseIntents` sequence within a `DefusePayload` structure, including essential metadata like signer ID, verifying contract, deadline, and nonce. ```rust let defuse_payload = DefusePayload { signer_id: "alice.near".parse()?, verifying_contract: "intents.near".parse()?, deadline: Deadline::from_block_height(deadline_block), nonce: generate_nonce()?, message: intents, }; ``` -------------------------------- ### TokenId String Parsing Source: https://github.com/near/intents/blob/main/_autodocs/types-primitives.md Shows how to parse a string representation into a TokenId object. Ensure the string format is correct. ```rust let token: TokenId = "nep141:usdc.near".parse()?; ``` -------------------------------- ### Explicit Match Pattern for Signature Verification Source: https://github.com/near/intents/blob/main/_autodocs/errors-exceptions.md Shows how to use a `match` statement to explicitly handle the result of a signature verification. This allows for specific actions based on whether the signature is valid or not. ```rust match signed_payload.verify() { Some(pubkey) => { // Continue execution } None => { return Err(DefuseError::InvalidSignature); } } ``` -------------------------------- ### Run Integration Tests Source: https://github.com/near/intents/blob/main/README.md Executes integration tests for specific contracts like defuse, poa, or escrow-swap. Use 'cargo integration-tests' for this purpose. ```shell cargo integration-tests ``` -------------------------------- ### NEAR SDK Utility Functions Source: https://github.com/near/intents/blob/main/_autodocs/utility-crates.md Includes utility functions for interacting with the NEAR blockchain, such as retrieving the current block height, timestamp, and account balance. These functions simplify common NEAR development tasks. ```rust pub fn current_block_height() -> u64 pub fn current_timestamp_ms() -> u64 pub fn account_balance(account: &AccountId) -> NearToken ``` -------------------------------- ### Semi-Sequential Nonce Generation for Concurrent Signers Source: https://github.com/near/intents/blob/main/contracts/wallet/README.md For concurrent, non-coordinated signers (e.g., multiple devices signing with the same key), use this semi-sequential nonce generation algorithm. It randomizes the nonce after every 32 sequential ones to maintain efficiency. ```rust const BIT_POS_MASK: u32 = 0b11111; if self.next_nonce & BIT_POS_MASK == 0 { self.next_nonce = random_u32() & !BIT_POS_MASK; } let nonce = self.next_nonce; self.next_nonce += 1; ``` -------------------------------- ### GlobalDeployer Contract Interface Source: https://github.com/near/intents/blob/main/_autodocs/additional-contracts.md Defines methods for registering contract code, deploying contracts with deterministic account IDs, and retrieving code by hash. Facilitates efficient and scalable contract deployment. ```rust pub trait GlobalDeployer { fn register_code(&mut self, code: Vec) -> [u8; 32]; // Returns code_hash fn deploy_deterministic( &mut self, code_hash: [u8; 32], init_args: Vec, ) -> AccountId; // Returns derived account ID fn get_code(&self, code_hash: [u8; 32]) -> Option>; } ``` -------------------------------- ### Intent Execution Model Source: https://github.com/near/intents/blob/main/_autodocs/architecture-overview.md Illustrates the execution flow for an intent within the NEAR Intents system. It involves validating preconditions, updating engine state, emitting events, and scheduling promises. ```rust Intent.execute_intent(signer_id, engine, intent_hash) └─ Validate preconditions └─ Update engine state └─ Emit events └─ Schedule promises if needed ``` -------------------------------- ### TIP-191 Signing for NEAR Intents Source: https://github.com/near/intents/blob/main/_autodocs/payload-framework.md Constructs a TIP-191 signed payload for NEAR intents, enabling TRON wallets to sign NEAR transactions. Requires a JSON-serialized Defuse payload and a TRON private key for signing. ```rust let message = Tip191Payload(json_serialized_defuse_payload); let signed = SignedTip191Payload { payload: message, signature: sign_tron_style(message.prehash(), tron_private_key), }; let multi = MultiPayload::Tip191(signed); ``` -------------------------------- ### Global Contract Hierarchy Diagram Source: https://github.com/near/intents/blob/main/contracts/global-deployer/README.md Visualizes the hierarchical structure of global contracts, including the Global Contract Namespace, Mutable Controllers, and individual contract instances. ```mermaid %%{init: {"flowchart": {"wrappingWidth": 600}}}%% flowchart TD GD["GLOBAL CONTRACT NAMESPACE
CodeHash(0x123..123) => GLOBAL DEPLOYER WASM
GlobalHash(0s..aaa) => GLOBAL DEPLOYER WASM
GlobalAccountId(0s..bbb) => GLOBAL CONTRACT 1 WASM
GlobalAccountId(0s..ccc) => GLOBAL CONTRACT 2 WASM"] C["MUTABLE CONTROLLER · 0s..aaa
ref: CodeHash(0x123..123)
state_init: { owner: alice.near, code_hash: 0x00..00, approved_hash: 0x00..00 }"] C --> GC1C["GLOBAL CONTRACT 1 CONTROLLER · 0s..bbb
ref: GlobalAccountId(0s..aaa)
state_init: { owner: alice.near, code_hash: 0x00..01, approved_hash: 0x00..00 }"] C --> GC2C["GLOBAL CONTRACT 2 CONTROLLER · 0s..ccc
ref: GlobalAccountId(0s..aaa)
state_init: { owner: alice.near, code_hash: 0x00..02, approved_hash: 0x00..00 }"] GC1C --> GC1I1["GLOBAL CONTRACT 1 · INSTANCE 1 · 0s..ddd
ref: GlobalAccountId(0s..bbb)
state_init: { owner: alice.near, code_hash: 0x00..01, approved_hash: 0x00..00 }"] GC1C --> GC1I2["GLOBAL CONTRACT 1 · INSTANCE 2 · 0s..eee
ref: GlobalAccountId(0s..bbb)
state_init: { owner: alice.near, code_hash: 0x00..02, approved_hash: 0x00..00 }"] GC2C --> GC2I1["GLOBAL CONTRACT 2 · INSTANCE 1 · 0s..fff
ref: GlobalAccountId(0s..ccc)
state_init: { owner: alice.near, code_hash: 0x00..01, approved_hash: 0x00..00 }"] style GD fill:#e0e0e0,stroke:#999,color:#000 style C fill:#bbdefb,stroke:#1976d2,color:#000 style GC1C fill:#c8e6c9,stroke:#388e3c,color:#000 style GC2C fill:#ffe0b2,stroke:#f57c00,color:#000 style GC1I1 fill:#c8e6c9,stroke:#388e3c,color:#000 style GC1I2 fill:#c8e6c9,stroke:#388e3c,color:#000 style GC2I1 fill:#ffe0b2,stroke:#f57c00,color:#000 ``` -------------------------------- ### Run Treasury Logger Tests Source: https://github.com/near/intents/blob/main/contracts/treasury-logger/README.md Executes the unit tests for the Treasury Logger contract, located in the `defuse-treasury-logger` crate. These tests verify the exact event JSON output. ```bash cargo test -p defuse-treasury-logger ``` -------------------------------- ### Define StorageDeposit Structure Source: https://github.com/near/intents/blob/main/_autodocs/defuse-core-intents.md Defines the structure for making a storage deposit on a token contract for an account. Use this to ensure an account has sufficient storage for token interactions. ```rust pub struct StorageDeposit { pub token: AccountId, pub account_id: Option, pub registration_only: Option, } ``` -------------------------------- ### AddPublicKey Source: https://github.com/near/intents/blob/main/_autodocs/defuse-core-intents.md Adds a public key to an account, enabling it to sign intents on behalf of the account. This is useful for managing access and permissions for automated operations. ```APIDOC ## AddPublicKey ### Description Adds a public key to an account. The added key can sign intents on behalf of the account, including adding new public keys. Warning: Implicit account IDs have their corresponding public keys automatically added. ### Fields - **public_key** (`PublicKey`) - Required - The public key to add (Ed25519, Secp256k1, or P256) ``` -------------------------------- ### Build Verifier Smart Contract Source: https://github.com/near/intents/blob/main/README.md Builds the Verifier smart contract individually. Reproducible builds can be enabled by setting REPRODUCIBLE=1. ```shell make CONTRACT[/VARIANT] [REPRODUCIBLE=1] ``` -------------------------------- ### Simulate Intents Function Source: https://github.com/near/intents/blob/main/_autodocs/defuse-contract-interface.md Performs a dry-run of intent execution without state changes. Useful for estimating fees and validating intents before submission. ```rust fn simulate_intents(&self, signed: Vec) -> SimulationOutput ``` -------------------------------- ### Off-Chain Compute Integration Flow Source: https://github.com/near/intents/blob/main/_autodocs/architecture-overview.md Describes the workflow for intents that reference off-chain computation, involving scheduling, execution by a worker, and proof submission. ```text Intent references Outlayer ↓ AuthCall schedules computation ↓ Worker performs off-chain logic ↓ Proof submitted to Verifier ↓ Contract verifies and executes ``` -------------------------------- ### Promise Yield Creation Function Source: https://github.com/near/intents/blob/main/_autodocs/nep-standards-integration.md Implements the `promise_yield_create` function from NEP-519, which allows a smart contract to suspend a promise and obtain a resumption token. ```rust pub fn promise_yield_create(promise: Promise) -> Vec ``` -------------------------------- ### ControllerUpgradable Source: https://github.com/near/intents/blob/main/_autodocs/defuse-contract-interface.md Facilitates contract upgrades and migrations using the controller pattern. Allows migrating the contract state and querying its code hash. ```APIDOC ## ControllerUpgradable ### Description Contract upgrade and migration via controller pattern. ### Methods - `migrate(args: MigrationArgs) -> Self`: Migrates the contract to a new version. - `code_hash(&self) -> [u8; 32]`: Returns the code hash of the current contract. ```