Library

The Mimic Protocol Library (@mimicprotocol/lib-ts) is a lightweight standard library for building blockchain automation tasks. It provides typed primitives and safe bindings to create deterministic tasks to interact with multiple blockchain networks.

Why AssemblyScript?

Tasks are written in AssemblyScript (which compiles to WebAssembly) to ensure:

  • Deterministic execution: Same inputs always produce same outputs

  • Portability: Runs consistently across different environments

  • Security: Sandboxed execution with no system access

  • Performance: Near-native execution speed

We're planning to expand language support beyond AssemblyScript to include other WebAssembly-compatible languages like Rust. This will bring more flexibility in how tasks can be written while maintaining all the security and deterministic execution benefits of WebAssembly.


1. Core Concepts

1.1. Intents

Intents are declarations of what you want to happen. Instead of executing transactions directly, you create intents that describe your desired outcome. The protocol then finds the best way to fulfill them.

Three types of intents are available:

  • Call: Execute smart contract functions

  • Swap: Exchange tokens across DEXs

  • Transfer: Move tokens between addresses

1.2. Environment

The Environment provides access to external data and execution capabilities:

  • Price feeds and oracles

  • Token information

  • Contract interactions

  • Intent execution


2. Getting Started

2.1. Installation

# Install dependencies
yarn add @mimicprotocol/lib-ts

# If creating a new project, you'll also need the CLI tools
yarn add @mimicprotocol/cli

2.2. Basic task structure

Every task follows this structure:

import { /* required imports */ } from '@mimicprotocol/lib-ts'

export default function main(): void {
  // 1. Setup: Define tokens, addresses, parameters
  // 2. Logic: Query data, make decisions
  // 3. Action: Create and send intents
}

2.3. Project setup

Create a basic task project:

# Initialize a new Mimic project
mimic init my-automation-task && cd my-automation-task

# Generate types from ABIs (if using custom contracts or external inputs)
mimic codegen

# Compile your task
mimic compile

3. API Reference

3.1. Core types

3.1.1. Primitives

// Addresses
const userAddress = Address.fromString('0x...')
const zeroAddress = Address.zero()

// Big integers for precise arithmetic
const value = BigInt.fromString('1000000000000000000') // 1 ETH in wei
// or...
const value2 = BigInt.fromI32(1).pow(18) // Also 1 ETH in wei
const calculated = value.times(BigInt.fromI32(2))

// Bytes for contract data
const data = Bytes.fromHexString('0x095ea7b3...')
const emptyData = Bytes.empty()

3.1.2. Tokens and Amounts

// Create a token reference
const USDC = Ethereum.USDC
const ETH = Ethereum.ETH
const customToken = ERC20Token.fromString('0xCustomTokenAddress', Ethereum.CHAIN_ID, 18, 'CSTM')

// Work with token amounts
const amount = TokenAmount.fromStringDecimal(USDC, '1000.50') // 1000.5 USDC
const nativeAmount = TokenAmount.fromI32(ETH, 5) // 5 ETH

3.2. Environment functions

3.2.1. Price queries

import { environment, Ethereum, USD } from '@mimicprotocol/lib-ts'

// Get current token price in USD
const price = environment.getPrice(Ethereum.USDC)

// Get historical price
const historicalPrice = environment.getPrice(Ethereum.USDC, new Date(1640995200000))

// Get raw price samples from multiple sources (USD[])
const rawPrices = environment.getRawPrice(Ethereum.USDC)

// Convert between USD and tokens
const usdAmount = USD.fromStringDecimal('1000')
const tokenEquivalent = usdAmount.toTokenAmount(Ethereum.WBTC)

3.2.2. Relevant tokens

// Find all relevant tokens for a user
const userTokens = environment.getRelevantTokens(
  userAddress,
  [ChainId.ETHEREUM, ChainId.POLYGON], // chains to check
  USD.fromStringDecimal('100'),        // minimum USD value
  [unwantedToken],                     // excluded tokens
  ListType.DenyList                    // list type
)

3.2.3. Contract calls

// Read from contracts
const result = environment.contractCall(
  Address.fromString('0xcontractAddress'),
  ChainId.ETHEREUM,
  null, // current timestamp
  '0x70a08231' + '...' // selector + encoded function call
)

3.2.4. Subgraph queries

import { environment, ChainId } from '@mimicprotocol/lib-ts'

const response = environment.subgraphQuery(
  ChainId.ETHEREUM,
  'QmSubgraphId',
  '{ tokens { id symbol } }',
  null // current timestamp
)

3.2.5. Context

import { environment, ChainId } from '@mimicprotocol/lib-ts'

const ctx = environment.getContext()
const user = ctx.user
const settlerForEth = ctx.findSettler(ChainId.ETHEREUM)
const timestampMs = ctx.timestamp

3.3. Intent builders

3.3.1. Transfer

Move tokens between addresses:

import { Address, ChainId, Ethereum, TokenAmount, TransferBuilder } from '@mimicprotocol/lib-ts'

const fee = TokenAmount.fromStringDecimal(Ethereum.USDC, '1')

const transferIntent = TransferBuilder.forChain(ChainId.ETHEREUM)
  .addTransferFromStringDecimal(Ethereum.USDC, '1000', Address.fromString('0xrecipientAddress'))
  .addTransferFromStringDecimal(Ethereum.WBTC, '0.5', Address.fromString('0xrecipientAddress'))
  .addTransferFromStringDecimal(Ethereum.USDT, '500', Address.fromString('0xotherRecipientAddress'))
  .addMaxFee(fee)
  .build()

transferIntent.send()

3.3.2. Swap

Exchange tokens across DEXs:

import { Address, ChainId, Ethereum, SwapBuilder, TokenAmount } from '@mimicprotocol/lib-ts'

const fee = TokenAmount.fromStringDecimal(Ethereum.USDC, '1')

const swapIntent = SwapBuilder.forChains(ChainId.ETHEREUM, ChainId.ETHEREUM) // same chain swap
  .addTokenInFromStringDecimal(Ethereum.USDC, '1')
  .addTokenOutFromStringDecimal(Ethereum.USDT, '0.99', Address.fromString('0xrecipientAddress')) // 1% slippage
  .addMaxFee(fee)
  .build()

swapIntent.send()

3.3.3. Call

Execute smart contract functions:

import { Address, BigInt, Bytes, CallBuilder, ChainId, Ethereum, evm, EvmEncodeParam, TokenAmount } from '@mimicprotocol/lib-ts'

const encodedData = Bytes.fromHexString(
  '0xselector' +
  evm.encode([
    EvmEncodeParam.fromValue('address', Address.zero()),
    EvmEncodeParam.fromValue('uint256', BigInt.zero()),
  ])
) // encoded function(address,uint256)

const fee = TokenAmount.fromStringDecimal(Ethereum.USDC, '1')

const callIntent = CallBuilder.forChain(ChainId.ETHEREUM)
  .addCall(Address.fromString('0xcontractAddress'), encodedData)
  .addMaxFee(fee)
  .build()

callIntent.send()

3.4. EVM Utilities

import { Address, BigInt, evm, EvmDecodeParam, EvmEncodeParam } from '@mimicprotocol/lib-ts'

// Encode function parameters
const encoded = evm.encode([
  EvmEncodeParam.fromValue('address', Address.zero()),
  EvmEncodeParam.fromValue('uint256', BigInt.zero()),
])

// Decode contract responses
const decoded = evm.decode(new EvmDecodeParam('string', response))

// Generate hashes
const hash = evm.keccak('some data')

4. Using generated ABI wrappers

If you are using mimic codegen to generate contract wrappers, refer to the ABI wrappers guide for how read/write methods, tuple classes, arrays, and events are produced and used:

Typed wrappers from Solidity ABIs

Last updated