本页面的翻译由 LLM 生成。如果你发现翻译有误,请在 GitHub 上提交 issue 告诉我们。
Sai EVM 集成指南
通过 EVM 签名者和 Interface 合约操作 Sai,传入 JSON 编码的 wasmMsgBytes 及代币数量、地址。
0. 开始使用
Section titled “0. 开始使用”- Node.js ≥ 18。
- pnpm、npm 或 yarn。
mkdir sai-evm && cd sai-evmpnpm init -ypnpm add ethers bignumber.jspnpm add -D typescript ts-node @types/node dotenvnpx tsc --init --target ES2022 --module NodeNext --moduleResolution NodeNext同一应用也需调用 Cosmos 时,添加
@nibiruchain/nibijs @cosmjs/cosmwasm-stargate @cosmjs/stargate cosmjs-types。
创建包含配置的 .env。
# Testnet-2EVM_RPC=https://evm-rpc.testnet-2.nibiru.fi/
# Or Mainnet# EVM_RPC=https://evm-rpc.nibiru.fi/
PRIVATE_KEY=0x... # Your private key (keep this secret!)INTERFACE_ADDR=0x... # Contract address from saiEvmInterfaceFromChainType(chainType)初始化 Provider 和签名者
Section titled “初始化 Provider 和签名者”import "dotenv/config"import { ethers } from "ethers"
export function makeSigner() { const rpc = process.env.EVM_RPC! const pk = process.env.PRIVATE_KEY! const provider = new ethers.JsonRpcProvider(rpc) const signer = new ethers.Wallet(pk, provider) return { provider, signer }}接口 ABI
Section titled “接口 ABI”导入公开 openTrade、executeSimpleFunctions、deposit、makeWithdrawRequest、redeem、executeVaultSimpleFunctions 的 ABI。
import PerpVaultEvmInterfaceAbi from "./PerpVaultEvmInterface.json" // Place your ABI file hereGas 估算工具
Section titled “Gas 估算工具”eth_estimateGas 使用无限 Cosmos SDK Gas 计量器,无法模拟执行时 ERC-20 子调用的 63/64 限制,可能低估。应保留充分余量和下限。调用费率为零,过高上限不增加成本,过低会使交易失败。
const FALLBACK_GAS_LIMIT = 5_000_000nconst MIN_GAS_LIMIT = 2_500_000nconst FALLBACK_GAS_PRICE = ethers.parseUnits("1", "gwei")
const withGasBuffer = (g: bigint) => { const padded = g <= 0n ? 0n : g * 2n return padded > MIN_GAS_LIMIT ? padded : MIN_GAS_LIMIT}
async function estimateGasWithFallback( fn: () => Promise<bigint>, info?: unknown) { try { const est = await fn() return { gasLimit: withGasBuffer(est) } } catch (error) { console.warn("Gas estimation failed, using fallback", info) return { gasLimit: FALLBACK_GAS_LIMIT, gasPrice: FALLBACK_GAS_PRICE } }}
const toTxOverrides = ({ gasLimit, gasPrice,}: { gasLimit: bigint gasPrice?: bigint}) => (gasPrice === undefined ? { gasLimit } : { gasLimit, gasPrice })1. 抵押资产与支付代币
Section titled “1. 抵押资产与支付代币”- BANK 使用 Cosmos 侧 6 位小数。
- ERC-20 使用代币自身小数位,通常 6。
Testnet-2
Section titled “Testnet-2”| 代币 | ERC-20 地址 |
|---|---|
| USDC | 0xAb68f1D1d91854383fd4Df9016E3040D03e8191a |
| stNIBI | 0xCae3d404AFB50016154a4B18091351065154E9bD |
| 代币 | ERC-20 地址 |
|---|---|
| USDC | 0x0829F361A05D993d5CEb035cA6DF3446b060970b |
| stNIBI | 0xcA0a9Fb5FBF692fa12fD13c0A900EC56Bb3f0a7b |
合并 BANK、ERC-20 前,先统一为 BANK 的 6 位小数单位。
const toBankUnits = ( amt: bigint, sourceDecimals: number, bankDecimals: number = 6): bigint => { if (sourceDecimals === bankDecimals) return amt const diff = Math.abs(sourceDecimals - bankDecimals) const factor = 10n ** BigInt(diff) return sourceDecimals > bankDecimals ? amt / factor : amt * factor}2. 永续合约开仓
Section titled “2. 永续合约开仓”contract.openTrade( wasmMsgBytes, // JSON-encoded WASM message with is_evm_origin: true collateralIndex, // Token index (e.g., 0 for first collateral) totalAmountBankUnits, // Total amount in BANK units useErc20Amount, // ERC-20 amount in token decimals overrides // Gas overrides)import { ethers } from "ethers"import BigNumber from "bignumber.js"import PerpVaultEvmInterfaceAbi from "./PerpVaultEvmInterface.json"import { makeSigner } from "./evm"
async function openTrade() { const { signer } = makeSigner() const iface = new ethers.Contract( process.env.INTERFACE_ADDR!, PerpVaultEvmInterfaceAbi.abi, signer )
const msg = { open_trade: { market_index: "MarketIndex(0)", leverage: "5", long: true, collateral_index: "TokenIndex(0)", trade_type: "trade", open_price: "70000", tp: undefined, sl: undefined, slippage_p: "0.01", // CosmWasm Decimal fraction: 0.01 = 1% is_evm_origin: true, // IMPORTANT: Set to true for EVM origin }, }
const bankDecimals = 6 const erc20Decimals = 6 const displayAmount = new BigNumber("100") const bankAmount = ethers.parseUnits(displayAmount.toString(), bankDecimals) const erc20Amount = ethers.parseUnits(displayAmount.toString(), erc20Decimals)
const toBankUnits = ( amt: bigint, ercDec: number, bankDec: number ): bigint => { if (ercDec === bankDec) return amt const diff = Math.abs(ercDec - bankDec) const factor = 10n ** BigInt(diff) return ercDec > bankDec ? amt / factor : amt * factor }
const totalBank = bankAmount + toBankUnits(erc20Amount, erc20Decimals, bankDecimals) const wasmMsgBytes = ethers.toUtf8Bytes(JSON.stringify(msg))
const gas = await estimateGasWithFallback(() => iface.openTrade.estimateGas(wasmMsgBytes, 0, totalBank, erc20Amount) )
const tx = await iface.openTrade( wasmMsgBytes, 0, totalBank, erc20Amount, toTxOverrides(gas) ) console.log("Transaction submitted:", tx.hash)
const receipt = await tx.wait() console.log("Mined in block:", receipt?.blockNumber)}3. 永续合约平仓
Section titled “3. 永续合约平仓”关闭未平仓仓位。
async function closeTrade() { const { signer } = makeSigner() const iface = new ethers.Contract( process.env.INTERFACE_ADDR!, PerpVaultEvmInterfaceAbi.abi, signer )
const msg = { close_trade: { trade_index: "UserTradeIndex(0)" } } const wasmMsgBytes = ethers.toUtf8Bytes(JSON.stringify(msg))
const gas = await estimateGasWithFallback(() => iface.executeSimpleFunctions.estimateGas(wasmMsgBytes) )
const tx = await iface.executeSimpleFunctions(wasmMsgBytes, toTxOverrides(gas)) const receipt = await tx.wait() console.log("Trade closed in block:", receipt?.blockNumber)}4. 创建和使用推荐码
Section titled “4. 创建和使用推荐码”async function createReferralCode() { const { signer } = makeSigner() const iface = new ethers.Contract( process.env.INTERFACE_ADDR!, PerpVaultEvmInterfaceAbi.abi, signer )
const msg = { create_referrer_code: { code: "MYCODE" } } const bytes = ethers.toUtf8Bytes(JSON.stringify(msg))
const gas = await estimateGasWithFallback(() => iface.executeSimpleFunctions.estimateGas(bytes) )
const tx = await iface.executeSimpleFunctions(bytes, toTxOverrides(gas)) await tx.wait() console.log("Referral code created")}async function redeemReferralCode() { const { signer } = makeSigner() const iface = new ethers.Contract( process.env.INTERFACE_ADDR!, PerpVaultEvmInterfaceAbi.abi, signer )
const msg = { redeem_referrer_code: { code: "PARTNER" } } const bytes = ethers.toUtf8Bytes(JSON.stringify(msg))
const gas = await estimateGasWithFallback(() => iface.executeSimpleFunctions.estimateGas(bytes) )
const tx = await iface.executeSimpleFunctions(bytes, toTxOverrides(gas)) await tx.wait() console.log("Referral code redeemed")}5. 金库充值
Section titled “5. 金库充值”向金库存入抵押资产。
async function depositToVault() { const { signer } = makeSigner() const iface = new ethers.Contract( process.env.INTERFACE_ADDR!, PerpVaultEvmInterfaceAbi.abi, signer )
const msg = { deposit: {} } const bytes = ethers.toUtf8Bytes(JSON.stringify(msg))
const bankDecimals = 6 const erc20Decimals = 6 const bankAmount = ethers.parseUnits("250", bankDecimals) const erc20Amount = ethers.parseUnits("250", erc20Decimals)
const toBankUnits = ( amt: bigint, ercDec: number, bankDec: number ): bigint => { if (ercDec === bankDec) return amt const diff = Math.abs(ercDec - bankDec) const factor = 10n ** BigInt(diff) return ercDec > bankDec ? amt / factor : amt * factor }
const totalBank = bankAmount + toBankUnits(erc20Amount, erc20Decimals, bankDecimals)
const vaultAddr = "<bech32 vault address>" const collateralErc20 = "<erc20 token address>"
const gas = await estimateGasWithFallback(() => iface.deposit.estimateGas( bytes, totalBank, erc20Amount, vaultAddr, collateralErc20, true ) )
const tx = await iface.deposit( bytes, totalBank, erc20Amount, vaultAddr, collateralErc20, true, toTxOverrides(gas) ) await tx.wait() console.log("Deposited to vault")}6. 金库提现申请
Section titled “6. 金库提现申请”申请从金库提现。
async function makeWithdrawRequest() { const { signer } = makeSigner() const iface = new ethers.Contract( process.env.INTERFACE_ADDR!, PerpVaultEvmInterfaceAbi.abi, signer )
const msg = { make_withdraw_request: {} } const bytes = ethers.toUtf8Bytes(JSON.stringify(msg))
const sharesBank = 1_000_000n // 1.0 shares in BANK units const sharesFromErc20 = 0n const totalShares = sharesBank + sharesFromErc20
const vaultAddr = "<vault address>"
const gas = await estimateGasWithFallback(() => iface.makeWithdrawRequest.estimateGas(vaultAddr, bytes, totalShares, sharesFromErc20) )
const tx = await iface.makeWithdrawRequest( vaultAddr, bytes, totalShares, sharesFromErc20, toTxOverrides(gas) ) await tx.wait() console.log("Withdraw request created")}7. 金库赎回
Section titled “7. 金库赎回”赎回金库份额。
async function redeemVaultShares() { const { signer } = makeSigner() const iface = new ethers.Contract( process.env.INTERFACE_ADDR!, PerpVaultEvmInterfaceAbi.abi, signer )
const msg = { redeem: { shares: "500000" } } // 0.5 shares const bytes = ethers.toUtf8Bytes(JSON.stringify(msg))
const vaultAddr = "<vault address>" const sendToEvm = true
const gas = await estimateGasWithFallback(() => iface.redeem.estimateGas(bytes, vaultAddr, "500000", sendToEvm) )
const tx = await iface.redeem( bytes, vaultAddr, "500000", sendToEvm, toTxOverrides(gas) ) await tx.wait() console.log("Shares redeemed")}8. 取消提现申请
Section titled “8. 取消提现申请”取消待处理提现申请。
async function cancelWithdrawRequest() { const { signer } = makeSigner() const iface = new ethers.Contract( process.env.INTERFACE_ADDR!, PerpVaultEvmInterfaceAbi.abi, signer )
const msg = { cancel_withdraw_request: { unlock_epoch: 123 } } const bytes = ethers.toUtf8Bytes(JSON.stringify(msg))
const vaultAddr = "<vault address>"
const gas = await estimateGasWithFallback(() => iface.executeVaultSimpleFunctions.estimateGas(bytes, vaultAddr) )
const tx = await iface.executeVaultSimpleFunctions( bytes, vaultAddr, toTxOverrides(gas) ) await tx.wait() console.log("Withdraw request cancelled")}错误处理与排查
Section titled “错误处理与排查”| 问题 | 解决方法 |
|---|---|
| ”No EVM signer” | 确认已调用 makeSigner() 并在 .env 设置 PRIVATE_KEY |
| Gas 估算失败 | 自动回退到 5,000,000 上限和 1 gwei |
| 链上交易回退 | 用归档 RPC 的 debug_traceTransaction 检查最深层错误 |
| 小数转换错误 | 求和前统一 BANK、ERC-20 小数位 |
无效 INTERFACE_ADDR | 确认地址对应 Testnet-2 或主网 |
- 始终使用 EVM 签名者,仅 Provider 无法发送交易。
- 保留 Gas 余量,避免耗尽。
- 检查全部交易消息有
is_evm_origin: true。 - 合并前正确转换小数位。
- 安全保存
PRIVATE_KEY,不得提交到版本控制。