bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 12쪽 중 3쪽
Home
Quickstart Guides
Multiple Agent setup
Multi-Agent Setup
In this guide, you'll learn how to set up and manage a Safe Smart Account with multiple agents.
This setup ensures that every transaction proposed by one agent is approved by at least one other agent.
To maintain full functionality, we recommend including human signers in addition to the AI agents.
Below, we demonstrate a 2-out-of-4 setup as an example.
Two Agents Propose, Check, and Execute Transactions
Setup Safe Smart Account with agent one
You will use the Safe
Protocol Kit
.
_
17
import Safe from '@safe-global/protocol-kit'
_
17
_
17
const AGENT_1_ADDRESS = // ...
_
17
const AGENT_1_PRIVATE_KEY = // ...
_
17
const AGENT_2_ADDRESS = // ...
_
17
const HUMAN_SIGNER_1_ADDRESS = // ...
_
17
const HUMAN_SIGNER_2_ADDRESS = // ...
_
17
const RPC_URL = 'https://rpc.ankr.com/eth_sepolia'
_
17
_
17
const newSafe = await Safe.init({
_
17
provider: RPC_URL,
_
17
signer: AGENT_1_PRIVATE_KEY,
_
17
safeOptions: {
_
17
owners: [AGENT_1_ADDRESS, AGENT_2_ADDRESS, HUMAN_SIGNER_1_ADDRESS, HUMAN_SIGNER_2_ADDRESS],
_
17
threshold: 2
_
17
}
_
17
})
The Smart Account is now created with a fixed address. If the account has not been deployed yet, it will automatically deploy when the first transaction is executed.
Propose a Transaction with Agent One
Agent One can now propose transactions. We recommend sending these transactions to the
Safe Transaction Service
. Using this service provides several benefits:
It allows Agent Two to easily receive, sign, and execute the transaction.
Transactions appear in the Safe Wallet interface, where human signers can review, approve, and execute them.
You can use the
API Kit
to propose transactions to the Safe Transaction Service.
Here's an example of how Agent One can propose a simple transaction to the zero address:
_
31
import SafeApiKit from '@safe-global/api-kit'
_
31
_
31
// How to get an Api key => http://docs.safe.global/core-api/how-to-use-api-keys
_
31
const apiKit = new SafeApiKit({
_
31
chainId: 11155111n,
_
31
apiKey: 'YOUR_API_KEY'
_
31
})
_
31
_
31
const tx = await newSafe.createTransaction({
_
31
transactions: [
_
31
{
_
31
to: '0x0000000000000000000000000000000000000000',
_
31
data: '0x',
_
31
value: '0'
_
31
}
_
31
]
_
31
})
_
31
_
31
// Every transaction has a Safe (Smart Account) Transaction Hash different than the final transaction hash
_
31
const safeTxHash = await newSafe.getTransactionHash(tx)
_
31
// The AI agent signs this Safe (Smart Account) Transaction Hash
_
31
const signature = await newSafe.signHash(safeTxHash)
_
31
_
31
// Now the transaction with the signature is sent to the Transaction Service with the Api Kit:
_
31
await apiKit.proposeTransaction({
_
31
safeAddress: safeAddress,
_
31
safeTransactionData: tx.data,
_
31
safeTxHash,
_
31
senderSignature: signature.data,
_
31
senderAddress: AGENT_ADDRESS
_
31
})
Receive and sign transaction with agent two
In the next step, the second AI agent needs to receive the transaction and, after performing any necessary checks, sign and execute it.
The second AI agent will run on its own machine, so you would have to initialize the Safe instance with the Smart Account's address.
_
18
const SAFE_ADDRESS = '0x...' // The address of the Smart Account from step one
_
18
_
18
// Initialize the Safe object with the same address, but a different signer
_
18
const existingSafe = await Safe.init({
_
18
provider: RPC_URL,
_
18
signer: AGENT_2_PRIVATE_KEY,
_
18
safeAddress: SAFE_ADDRESS
_
18
})
_
18
_
18
// Get pending transactions that need a signature
_
18
const pendingTransactions = await apiKit.getPendingTransactions(SAFE_ADDRESS)
_
18
// We assume there is only one pending transaction
_
18
const transaction = pendingTransactions.results[0]
_
18
_
18
// Here, your AI agent could check this transaction.
_
18
_
18
// As only one more signater is required, AI agent two can execute the transaction:
_
18
existingSafe.executeTransaction(transaction)
Next steps
Your AI agents can make autonomous decisions, and the human signers can do so, too.
We are exited to see what you will build.
If you have a technical question, feel free to reach out on
Stack Exchange
(opens in a new tab)
with the safe-core tag.
Human approval for agent action
Agent with spending limit
Was this page helpful?
Report issue
## /home/ai-agent-quickstarts/agent-with-spending-limit
Home
Quickstart Guides
Agent with spending limit
AI agent with a spending limit for a treasury
This setup is used by DAOs or other organizations that want to utilize AI agents to manage their funds.
This setup uses Safe's
allowance module
(opens in a new tab)
.
After activating it for a Safe Smart Account, you can set an allowance per token for a spender (the delegator).
It can be a one-time allowance, or an allowance that resets after a certain time interval (for example, 100 USDC every day).
You can find an easy to run example for the allowance module in our
example repository
(opens in a new tab)
.
You can setup an allowance (spending limit) on a Safe Smart Account with the
Safe Wallet
(opens in a new tab)
interface following
this guide
(opens in a new tab)
.
Then, your agent can spend the allowance, as described in the last step.
Here are the important code snippets to get you up and running:
Pre-requisites
A deployed Safe Smart Account
The Smart Account should hold an amount of the ERC20 token for which the allowance will be given
Set and use a spending limit for the AI agent
Enable the Allowance module on your Safe
When you set a spending limit from Safe Wallet, the allowance module will be enabled automatically.
You will use the Safe
Protocol Kit
.
Here is a code example to enable it programmatically:
_
16
import Safe from '@safe-global/protocol-kit'
_
16
import { getAllowanceModuleDeployment } from '@safe-global/safe-modules-deployments'
_
16
_
16
const preExistingSafe = await Safe.init({
_
16
provider: RPC_URL,
_
16
signer: OWNER_1_PRIVATE_KEY,
_
16
safeAddress: safeAddress
_
16
})
_
16
_
16
// Add Module
_
16
const allowanceModule = getAllowanceModuleDeployment({ network: '11155111' })!
_
16
const safeTransaction = await preExistingSafe.createEnableModuleTx(
_
16
allowanceModule.networkAddresses['11155111']
_
16
)
_
16
const txResponse = await preExistingSafe.executeTransaction(safeTransaction)
_
16
console.log(txResponse)
Set spending limit for AI agent
Now you can set a spending limit to your AI agent:
_
55
import { getAllowanceModuleDeployment } from '@safe-global/safe-modules-deployments'
_
55
import Safe from '@safe-global/protocol-kit'
_
55
import { getAllowanceModuleDeployment } from '@safe-global/safe-modules-deployments'
_
55
import { OperationType, MetaTransactionData } from '@safe-global/types-kit'
_
55
_
55
const ERC20_TOKEN_ADDRESS = '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238'
_
55
const preExistingSafe = await Safe.init({
_
55
provider: RPC_URL,
_
55
signer: OWNER_1_PRIVATE_KEY,
_
55
safeAddress: safeAddress
_
55
})
_
55
_
55
const allowanceModule = getAllowanceModuleDeployment({ network: '11155111' })!
_
55
_
55
const allowanceModuleAddress = allowanceModule.networkAddresses['11155111']
_
55
_
55
const callData1 = encodeFunctionData({
_
55
abi: allowanceModule.abi,
_
55
functionName: 'addDelegate',
_
55
args: [AGENT_ADDRESS]
_
55
})
_
55
// agent can spend 1 USDC per day:
_
55
const callData2 = encodeFunctionData({
_
55
abi: allowanceModule.abi,
_
55
functionName: 'setAllowance',
_
55
args: [
_
55
AGENT_ADDRESS, // delegate
_
55
ERC20_TOKEN_ADDRESS, // token
_
55
1_000_000, // allowance amount (1 USDC)
_
55
1_440, // reset time in minutes (1440 mins = 1 day)
_
55
0 // reset base (fine to set zero)
_
55
]
_
55
})
_
55
_
55
const safeTransactionData1: MetaTransactionData = {
_
55
to: allowanceModuleAddress,
_
55
value: '0',
_
55
data: callData1,
_
55
operation: OperationType.Call
_
55
}
_
55
_
55
const safeTransactionData2: MetaTransactionData = {
_
55
to: allowanceModuleAddress,
_
55
value: '0',
_
55
data: callData2,
_
55
operation: OperationType.Call
_
55
}
_
55
_
55
const safeTransaction = await preExistingSafe.createTransaction({
_
55
transactions: [safeTransactionData1, safeTransactionData2],
_
55
onlyCalls: true
_
55
})
_
55
_
55
const txResponse = await preExistingSafe.executeTransaction(safeTransaction)
_
55
console.log(txResponse)
Let the AI agent use the spending limit
Now your agent has a spending limit, either set programmatically or from Safe Wallet.
Here is how the agent can spend it:
_
72
import {
_
72
createPublicClient,
_
72
http,
_
72
encodeFunctionData,
_
72
zeroAddress,
_
72
createWalletClient,
_
72
} from 'viem'
_
72
import { privateKeyToAccount } from 'viem/accounts'
_
72
const ERC20_TOKEN_ADDRESS = '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238'
_
72
_
72
const allowanceModule = getAllowanceModuleDeployment({ network: '11155111' })!
_
72
_
72
const allowanceModuleAddress = allowanceModule.networkAddresses[
_
72
'11155111'
_
72
] as `0x${string}`
_
72
_
72
const publicClient = createPublicClient({ transport: http(RPC_URL!) })
_
72
_
72
// Read allowance module to get current nonce
_
72
const allowance = await publicClient.readContract({
_
72
address: allowanceModuleAddress,
_
72
abi: allowanceModule.abi,
_
72
functionName: 'getTokenAllowance',
_
72
args: [safeAddress, AGENT_ADDRESS, ERC20_TOKEN_ADDRESS]
_
72
})
_
72
_
72
const amount = 1 // You might want to adapt the amount
_
72
_
72
// generate hash
_
72
const hash = await publicClient.readContract({
_
72
address: allowanceModuleAddress,
_
72
abi: allowanceModule.abi,
_
72
functionName: 'generateTransferHash',
_
72
args: [
_
72
safeAddress,
_
72
ERC20_TOKEN_ADDRESS,
_
72
AGENT_ADDRESS,
_
72
amount,
_
72
zeroAddress,
_
72
0,
_
72
allowance[4] // nonce
_
72
]
_
72
})
_
72
_
72
const agentAccount = privateKeyToAccount(
_
72
AGENT_PRIVATE_KEY as `0x${string}`
_
72
)
_
72
const signature = await agentAccount.sign({
_
72
hash: hash as unknown as `0x${string}`
_
72
})
_
72
_
72
const { request } = await publicClient.simulateContract({
_
72
address: allowanceModuleAddress,
_
72
abi: allowanceModule.abi,
_
72
functionName: 'executeAllowanceTransfer',
_
72
args: [
_
72
safeAddress,
_
72
ERC20_TOKEN_ADDRESS,
_
72
AGENT_ADDRESS,
_
72
amount,
_
72
zeroAddress,
_
72
0,
_
72
AGENT_ADDRESS,
_
72
signature
_
72
],
_
72
account: agentAccount
_
72
})
_
72
_
72
const walletClient = createWalletClient({ transport: http(RPC_URL!) })
_
72
_
72
const tx = await walletClient.writeContract(request)
_
72
console.log(tx)
In this example, your agent will get a daily spending limit of 10 USDC.
Next steps
You can find more info in the example repository or in the documentation about the allowance module.
If you have a technical question, feel free to reach out on
Stack Exchange
(opens in a new tab)
with the safe-core tag.
Multiple Agent setup
Introduction
Was this page helpful?
Report issue
## /home/ai-agent-actions/introduction
Home
Action Guides
Introduction
Introduction
Here you find example actions your AI agent can do.
AI agent swaps on CoW Swap
: The AI agent sends a swap intent to CoW Swap, which ensures the best swap rates and reduces MEV losses.
AI agent swaps on Uniswap
: An example of how your AI agent can trade tokens on Uniswap.
Agent with spending limit
AI agent swaps on CoW Swap
Was this page helpful?
Report issue
## /home/ai-agent-actions/ai-agent-swaps-with-cow-swap
Home
Action Guides
AI agent swaps on CoW Swap
AI agent swaps on CoW Swap
CoW swap ensures best prices and fastest execution and minimizes MEV.
You can find a working code example to run locally in our
AI agent with Safe Smart Account CoW Swap example repository
(opens in a new tab)
.
Here is a quick guide to get you up and running:
Requirements
A deployed Safe Smart Account
The AI agent is a signer on the Safe
This example assumes, that the threshold of the Safe Smart Account is one, so the AI agent can sign autonomously.
If you require more signatures, you have to collect those signatures programmatically of with the
Safe Wallet
(opens in a new tab)
.
Let your AI agent send an intent
Setup the Safe Smart Account
Your Safe Smart Account should be deployed.
Now, initialize an instance with the
Protocol Kit
:
_
10
import Safe from "@safe-global/protocol-kit";
_
10
_
10
const preExistingSafe = await Safe.init({
_
10
provider: RPC_URL,
_
10
signer: AGENT_PRIVATE_KEY,
_
10
safeAddress: SAFE_ADDRESS,
_
10
});
Send swap intent
Now, you can use the CoW Swap SDK to assemble a transaction that you can sign and execute with your Safe Smart Account.
The swap will then be executed.
Please be aware that the CoW Swap's SDK uses Ethers, while Safe's SDK use viem.
You will see some warnings in the logs, but the code works nonetheless.
In this example, we buy COW and pay with WETH.
_
78
import {
_
78
SwapAdvancedSettings,
_
78
TradeParameters,
_
78
TradingSdk,
_
78
SupportedChainId,
_
78
OrderKind,
_
78
SigningScheme,
_
78
} from "@cowprotocol/cow-sdk";
_
78
import { VoidSigner } from "@ethersproject/abstract-signer";
_
78
import { JsonRpcProvider } from "@ethersproject/providers";
_
78
_
78
const traderParams = {
_
78
chainId: SupportedChainId.SEPOLIA,
_
78
signer: new VoidSigner(
_
78
smartContractWalletAddress: SAFE_ADDRESS,
_
78
new JsonRpcProvider("https://sepolia.gateway.tenderly.co")
_
78
),
_
78
appCode: "awesome-app",
_
78
};
_
78
_
78
const cowSdk = new TradingSdk(traderParams, { logs: false });
_
78
_
78
const parameters: TradeParameters = {
_
78
kind: OrderKind.SELL,
_
78
sellToken: WETH_ADDRESS,
_
78
sellTokenDecimals: 18,
_
78
buyToken: COW_ADDRESS,
_
78
buyTokenDecimals: 18,
_
78
amount: INPUT_AMOUNT,
_
78
};
_
78
_
78
const advancedParameters: SwapAdvancedSettings = {
_
78
quoteRequest: {
_
78
// Specify the signing scheme
_
78
signingScheme: SigningScheme.PRESIGN,
_
78
},
_
78
};
_
78
_
78
const orderId = await cowSdk.postSwapOrder(parameters, advancedParameters);
_
78
_
78
console.log(`Order ID: [${orderId}]`);
_
78
_
78
const preSignTransaction = await cowSdk.getPreSignTransaction({
_
78
orderId,
_
78
account: smartContractWalletAddress,
_
78
});
_
78
_
78
const customChain = defineChain({
_
78
...sepolia,
_
78
name: "custom chain",
_
78
transport: http(RPC_URL),
_
78
});
_
78
_
78
const publicClient = createPublicClient({
_
78
chain: customChain,
_
78
transport: http(RPC_URL),
_
78
});
_
78
_
78
const safePreSignTx: MetaTransactionData = {
_
78
to: preSignTransaction.to,
_
78
value: preSignTransaction.value,
_
78
data: preSignTransaction.data,
_
78
operation: OperationType.Call,
_
78
};
_
78
_
78
const safeTx = await preExistingSafe.createTransaction({
_
78
transactions: [safePreSignTx],
_
78
onlyCalls: true,
_
78
});
_
78
_
78
// You might need to collect more signatures here
_
78
_
78
const txResponse = await preExistingSafe.executeTransaction(safeTx);
_
78
console.log(`Sent tx hash: [${txResponse.hash}]`);
_
78
console.log("Waiting for the tx to be mined");
_
78
await publicClient.waitForTransactionReceipt({
_
78
hash: txResponse.hash as `0x${string}`,
_
78
});
Next steps
Now, where your AI agent can execute trades autonomously, you are free to use this power as you like.
You can find more specific information in the
CoW Swap Trading SDK docs
(opens in a new tab)
.
If you have a technical question about Safe Smart Accounts, feel free to reach out on
Stack Exchange
(opens in a new tab)
with the safe-core tag.
Introduction
AI agent swaps on Uniswap
Was this page helpful?
Report issue
## /home/ai-agent-actions/ai-agent-swaps-on-uniswap
Home
Action Guides
AI agent swaps on Uniswap
AI agent swaps on Uniswap
You can find a working code example to run locally in our
example repository
(opens in a new tab)
.
Requirements
A deployed Safe Smart Account
The AI agent is a signer on the Safe
This example assumes, that the threshold of the Safe Smart Account is one, so the AI agent can sign autonomously.
If you require more signatures, you have to collect those signatures programmatically of with the
Safe Wallet
(opens in a new tab)
.
This guide assumes the Safe owns WETH.
The example repository shows how to swap ETH to WETH.
Swap on Uniswap
Here is a quick guide to get you up and running:
Setup the Safe Smart Account
Your Safe Smart Account should be deployed.
Now, initialize an instance with the Safe
Protocol Kit
:
_
10
import Safe from "@safe-global/protocol-kit";
_
10
_
10
const preExistingSafe = await Safe.init({
_
10
provider: RPC_URL,
_
10
signer: AGENT_PRIVATE_KEY,
_
10
safeAddress: SAFE_ADDRESS,
_
10
});
Fetch Uniswap pool data
First, you have to fetch the pool data from Uniswap.
This data provides information about the liquidity at the current and at other prices.
Uniswap has a unique
Pricing Math
(opens in a new tab)
.
_
26
import {
_
26
Address,
_
26
createPublicClient,
_
26
createWalletClient,
_
26
defineChain,
_
26
encodeFunctionData,
_
26
http,
_
26
PublicClient,
_
26
} from "viem";
_
26
_
26
// Fetch slot0 data (current price, tick, etc.)
_
26
const slot0 = (await publicClient.readContract({
_
26
address: poolAddress,
_
26
abi: POOL_ABI,
_
26
functionName: "slot0",
_
26
})) as any;
_
26
_
26
// Fetch liquidity
_
26
const liquidity = (await publicClient.readContract({
_
26
address: poolAddress,
_
26
abi: POOL_ABI,
_
26
functionName: "liquidity",
_
26
})) as any;
_
26
_
26
const sqrtPriceX96 = BigInt(slot0[0]);
_
26
const tick = slot0[1];
Execute Swap
Now, you can setup your Safe Smart Account and send a swap transaction to Uniswap:
_
104
import {
_
104
FeeAmount,
_
104
Pool,
_
104
Route,
_
104
SwapRouter,
_
104
CurrencyAmount,
_
104
TradeType,
_
104
Percent
_
104
} from "@uniswap/v3-sdk";
_
104
import { Token, SwapOptions } from "@uniswap/sdk-core";
_
104
import JSBI from "jsbi";
_
104
import { OperationType, MetaTransactionData } from "@safe-global/types-kit";
_
104
_
104
// Set up viem clients and accounts
_
104
const account = privateKeyToAccount(AGENT_PRIVATE_KEY as `0x${string}`);
_
104
_
104
const publicClient = createPublicClient({
_
104
transport: http(RPC_URL!)
_
104
});
_
104
const walletClient = createWalletClient({
_
104
transport: http(RPC_URL!)
_
104
});
_
104
_
104
const chainId = (await publicClient.getChainId());
_
104
_
104
// Example Values for WETH/USDC Uniswap Pool on Sepolia:
_
104
const WETH_ADDRESS = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
_
104
const USDC_ADDRESS = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
_
104
const USDC_ETH_POOL_ADDRESS = "0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640";
_
104
const SWAP_ROUTER_ADDRESS = "0xE592427A0AEce92De3Edee1F18E0157C05861564"; // Uniswap V3 Router
_
104
const INPUT_AMOUNT = "100000000000"; // Amount of ETH to swap to USDC
_
104
const OUTOUT_AMOUNT = "0"; // 0 USDC
_
104
_
104
// Define token details
_
104
const USDC = new Token(chainId, USDC_ADDRESS, 6, "USDC", "USD Coin");
_
104
const WETH = new Token(chainId, WETH_ADDRESS, 18, "WETH", "Wrapped Ether");
_
104
_
104
const callDataApprove = encodeFunctionData({
_
104
abi: WETH_ABI,
_
104
functionName: "approve",
_
104
args: [SWAP_ROUTER_ADDRESS, INPUT_AMOUNT],
_
104
});
_
104
_
104
const safeApproveTx: MetaTransactionData = {
_
104
to: WETH_ADDRESS,
_
104
value: "0",
_
104
data: callDataApprove,
_
104
operation: OperationType.Call,
_
104
};
_
104
_
104
const options: SwapOptions = {
_
104
slippageTolerance: new Percent(50, 10_000), // 50 bips, or 0.50%
_
104
deadline: Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from the current Unix time
_
104
recipient: SAFE_ADDRESS,
_
104
};
_
104
_
104
const poolInfo = await fetchPoolData(publicClient, USDC_ETH_POOL_ADDRESS);
_
104
_
104
// Create the pool object
_
104
const pool = new Pool(
_
104
WETH,
_
104
USDC,
_
104
FeeAmount.MEDIUM,
_
104
JSBI.BigInt(poolInfo.sqrtPriceX96.toString()),
_
104
JSBI.BigInt(poolInfo.liquidity.toString()),
_
104
poolInfo.tick프로젝트로 돌아가기