自动驱动 SDK

概览
这个 auto-drive 软件包提供了一套工具来与自动驱动的 API 交互.
安装
要安装软件包,请使用以下命令:
yarn add @autonomys/auto-drive
如何用取来?
要与自动驱动 API 互动, 您需要创建 API 密钥 。 遵循这些步骤:
- 转到 自动驱动 并登录您的预设SSO.
- 一旦登录,点击左侧栏菜单中的开发者部分.
- 在开发部分,单击“创建 API 密钥”
- 读取模式信件并单击生成
如何从缓冲器上传文件 ?
这里有一个例子 如何使用 uploadFileFromBuffer 可选加密和压缩的上传缓冲的方法 :
import { createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
const api = createAutoDriveApi({ apiKey: 'your-api-key', network: NetworkId.MAINNET }) // Initialize your API instance with API key
// Create a buffer from your data
const buffer = Buffer.from('Hello, Autonomys!')
const fileName = 'hello.txt'
const options = {
password: 'your-encryption-password', // Optional: specify a password for encryption
compression: true,
// an optional callback useful for large file uploads
onProgress?: (progress: number) => {
console.log(`The upload is ${progress}% completed`)
}
}
const cid = await api.uploadFileFromBuffer(buffer, fileName, options)
console.log(`The file is uploaded and its cid is ${cid}`)
如何从文件路径上传文件 ? (浏览器中不可用)
这里有一个例子 如何使用 fs.uploadFileFromFilepath 以可选加密和压缩方式上传文件的方法:
import { fs, createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
const api = createAutoDriveApi({ apiKey: 'your-api-key', network: NetworkId.MAINNET }) // Initialize your API instance with API key
const filePath = 'path/to/your/file.txt' // Specify the path to your file
const options = {
password: 'your-encryption-password', // Optional: specify a password for encryption
compression: true,
// an optional callback useful for large file uploads
onProgress?: (progress: number) => {
console.log(`The upload is completed is ${progress}% completed`)
}
}
const cid = await fs.uploadFileFromFilepath(api, filePath, options)
console.log(`The file is uploaded and its cid is ${cid}`)
如何上传 文件 接口
import { createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
const api = createAutoDriveApi({ apiKey: 'your-api-key', network: NetworkId.MAINNET }) // Initialize your API instance with API key
// e.g Get File from object from HTML event
const file: File = e.target.value // Substitute with your file
const options = {
password: 'your-encryption-password', // Optional: specify a password for encryption
compression: true,
}
const cid = await api.uploadFileFromInput(file, options)
console.log(`The file is uploaded and its cid is ${cid}`)
如何从自定义接口上传文件 ?
有时你可能会有一个自定义的界面,既不适合文件,也不适合文件路径. 对于这些案例,有界面通用文件:
export interface GenericFile {
read(): AsyncIterable<Buffer> // A buffer generator function that will output the bytes of the file
name: string
mimeType?: string
size: number
path: string // Could be ignored in file upload
}
要了解更多关于 Aynn 生成器的访问信息 这个网站。 。 。 .
您可以上传任何可以以这种方式表示的文件 。 例如,将文件上传为 Buffer
import { createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
const api = createAutoDriveApi({ apiKey: 'your-api-key', network: NetworkId.MAINNET }) // Initialize your API instance with API key
const buffer = Buffer.from(...);
const genericFile = {
read: async function *() {
yield buffer
},
name: "autonomys-whitepaper.pdf",
mimeType: "application/pdf",
size: 1234556,
path: "autonomys-whitepaper.pdf"
}
const options = {
password: 'your-encryption-password', // Optional: specify a password for encryption
compression: true,
// an optional callback useful for large file uploads
onProgress?: (progress: number) => {
console.log(`The upload is completed is ${progress}% completed`)
}
}
const cid = api.uploadFile(genericFile, options)
console.log(`The file is uploaded and its cid is ${cid}`)
如何从文件夹上传文件夹 ? (浏览器中不可用)
import { createAutoDriveApi, fs } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
const api = createAutoDriveApi({ apiKey: 'your-api-key', network: NetworkId.MAINNET }) // Initialize your API instance with API key
const folderPath = 'path/to/your/folder' // Specify the path to your folder
const options = {
uploadChunkSize: 1024 * 1024, // Optional: specify the chunk size for uploads
password: 'your-encryption-password', // Optional: If folder is encrypted
// an optional callback useful for large file uploads
onProgress: (progress: number) => {
console.log(`The upload is completed is ${progress}% completed`)
},
}
const folderCID = await fs.uploadFolderFromFolderPath(api, folderPath, options)
console.log(`The folder is uploaded and its cid is ${folderCID}`)
注意: 如果试图加密一个文件夹, 将生成一个 zip 文件, 该文件将被加密并上传 .
下载使用示例
这里有一个例子 如何使用 downloadFile 从服务器下载文件的方法 :
import { createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
const api = createAutoDriveApi({ apiKey: 'your-api-key', network: NetworkId.MAINNET }) // Initialize your API instance with API key
try {
const cid = '..'
const stream = await api.downloadFile(cid)
let file = Buffer.alloc(0)
for await (const chunk of stream) {
file = Buffer.concat([file, chunk])
}
console.log('File downloaded successfully:', stream)
} catch (error) {
console.error('Error downloading file:', error)
}
对象调制使用示例
以下是如何使用对象节制方法的例子:
报告对象
import { createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
const api = createAutoDriveApi({ apiKey: 'your-api-key', network: NetworkId.MAINNET })
try {
const cid = 'your-object-cid'
await api.reportObject(cid)
console.log('Object reported successfully')
} catch (error) {
console.error('Error reporting object:', error)
}
禁用对象
import { createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
const api = createAutoDriveApi({ apiKey: 'your-api-key', network: NetworkId.MAINNET })
try {
const cid = 'your-object-cid'
await api.banObject(cid)
console.log('Object banned successfully')
} catch (error) {
console.error('Error banning object:', error)
}
撤销报告
import { createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
const api = createAutoDriveApi({ apiKey: 'your-api-key', network: NetworkId.MAINNET })
try {
const cid = 'your-object-cid'
await api.dismissReport(cid)
console.log('Report dismissed successfully')
} catch (error) {
console.error('Error dismissing report:', error)
}
获取要审查的对象
import { createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
const api = createAutoDriveApi({ apiKey: 'your-api-key', network: NetworkId.MAINNET })
try {
const toBeReviewed = await api.getToBeReviewedList(50, 0)
console.log(`Found ${toBeReviewed.length} objects to be reviewed`)
for (const object of toBeReviewed) {
console.log(`${object.name} - ${object.headCid}: ${object.size}`)
}
} catch (error) {
console.error('Error getting objects to be reviewed:', error)
}
创建可共享的下载链接
这里有一个例子 如何使用 publishObject 发布对象并获取其公开下载 URL的方法:
import { createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
const api = createAutoDriveApi({ apiKey: 'your-api-key', network: NetworkId.MAINNET }) // Initialize your API instance with API key
try {
const cid = 'your-file-cid'
const publicUrl = await api.publishObject(cid)
console.log('Public download URL:', publicUrl)
} catch (error) {
console.error('Error publishing object:', error)
}
注意: 要检索已公布对象的链接, 请再次调用 publishObject 方法
获取 MyFiles 的示例使用
这里有一个例子 如何使用 getMyFiles 获取根目录的方法 :
import { createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
const api = createAutoDriveApi({ apiKey: 'your-api-key', network: NetworkId.MAINNET }) // Initialize your API instance with API key
try {
for (let i = 0; i < 10; i++) {
const myFiles = await api.getMyFiles(i, 100)
console.log(`Retrieved ${myFiles.rows.length} files of ${myFiles.totalCount} total`)
for (const file of myFiles.rows) {
console.log(`${file.name} - ${file.headCid}: ${file.size}`)
}
}
} catch (error) {
console.error('Error downloading file:', error)
}
与AI3付款——购买存储信贷
在自主网络上的存储通过链上支付意向流量以AI3的代币支付. SDK 处理所有 Auto Drive API 交互; 您使用您首选的 EVM 钱包库( wagmi, viem, etes等) 提供链上交易 .
流动
0. getStoragePrice(api) → optional: show live price estimate before payment
1. createPaymentIntent(api, sizeBytes) → checks credit cap, locks price, returns amount + contract details
2. send ai3AmountWei to contractAddress → payIntent(intentId) on-chain (your wallet code)
3. watchPaymentTransaction(api, id, tx) → notifies Auto Drive of your tx hash
4. waitForPaymentCompletion(api, id) → polls until COMPLETED (credits applied)
重要: 保留您的 API 密钥服务器侧
createPaymentIntent, (中文(简体) ), watchPaymentTransaction,以及 getPaymentIntentStatus 全部需要 API 密钥 。 在网络应用程序中,这些呼叫必须取自您的服务器(例如Next.js API路由,Express处理器),而不是取自浏览器. getStoragePrice 财务报告和审定财务报表 getPaymentContractInfo 是公共终点,可以从任何地方调用.
获得现场价格估计
// Public endpoint — no API key required. Good for showing a cost estimate
// before the user connects a wallet or commits to a payment.
const publicApi = createAutoDriveApi({ apiKey: null, network: NetworkId.MAINNET })
const { shannonsPerByte, ai3PerGb } = await publicApi.getStoragePrice()
console.log(`Current price: ${ai3PerGb} AI3/GB`)
服务器侧示例 (Node / Next.js API 路由)
import { createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
// Run on your server — never expose your API key to the browser
const api = createAutoDriveApi({
apiKey: process.env.AUTO_DRIVE_API_KEY!,
network: NetworkId.MAINNET,
})
// Step 1 — create a price-locked intent for the content you want to store.
// Throws CreditCapExceededError (before anything is paid) if the purchase
// would exceed your per-user credit cap.
const intent = await api.createPaymentIntent(contentSizeBytes)
// intent.ai3AmountWei — exact amount to send (as a BigInt-safe string)
// intent.ai3Amount — human-readable amount, e.g. "0.00123"
// intent.contractAddress — Credits Receiver contract on Auto EVM
// intent.intentId — pass as the bytes32 arg to payIntent()
// intent.expiresAt — ISO timestamp, intent expires after 10 minutes
// Step 2 — your client sends the on-chain transaction (see below)
// const txHash = await walletClient.writeContract({ ... })
// Step 3 — submit the tx hash so Auto Drive can watch it
await api.watchPaymentTransaction(intent.intentId, txHash)
// Step 4 — poll until credits are applied (or intent expires/fails)
const result = await api.waitForPaymentCompletion(intent.intentId)
// result: 'COMPLETED' | 'EXPIRED' | 'FAILED' | 'OVER_CAP'
if (result === 'COMPLETED') {
console.log('Credits applied — ready to upload')
}
客户端实例( 浏览器, 使用viem)
import { createAutoDriveApi } from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
import { createWalletClient, custom, parseGwei } from 'viem'
// Step 1 — fetch contract details (public endpoint, no API key needed)
const publicApi = createAutoDriveApi({ apiKey: null, network: NetworkId.MAINNET })
const contractInfo = await publicApi.getPaymentContractInfo()
// Step 2 — send the on-chain transaction with your wallet
const walletClient = createWalletClient({ transport: custom(window.ethereum) })
const [account] = await walletClient.requestAddresses()
const txHash = await walletClient.writeContract({
address: contractInfo.contractAddress as `0x${string}`,
abi: contractInfo.payIntentAbi,
functionName: 'payIntent',
args: [intent.intentId as `0x${string}`],
value: BigInt(intent.ai3AmountWei),
})
// Then call your server route to run steps 3 and 4
带有自定义选项的投票
const result = await api.waitForPaymentCompletion(intent.intentId, {
pollIntervalMs: 5_000, // check every 5 seconds (default: 3 000)
timeoutMs: 120_000, // give up after 2 minutes (default: 300 000)
})
手动检查意图状态
const { id, status } = await api.getPaymentIntentStatus(intent.intentId)
// status: 'PENDING' | 'CONFIRMED' | 'COMPLETED' | 'EXPIRED' | 'FAILED' | 'OVER_CAP'
拒付信贷上限
createPaymentIntent 将购买大小发送给自动驱动器 requestedBytes自动驱动然后拒绝在支付任何款项之前超过用户信用上限的购买。 一个不适合你 剩下的头室的购买 扔一个 CreditCapExceededError (HTTP 403,代码 CREDIT_CAP_EXCEEDED) (中文(简体) ). 单项购买大于整个盖子 PaymentApiError 使用 HTTP 400 且没有代码 :
import { CreditCapExceededError, PaymentApiError } from '@autonomys/auto-drive'
try {
const intent = await api.createPaymentIntent(contentSizeBytes)
} catch (error) {
if (
error instanceof CreditCapExceededError ||
(error instanceof PaymentApiError && error.status === 400)
) {
// Nothing was paid. Try a smaller size.
} else {
throw error
}
}
用USDC付款——用USDC购买Ethereum的储存信贷
您也可在Ethereum购买USDC的存储信用。 和AI3一样,SDK会让Auto Drive API打电话,你的钱包库会签下交易. SDK不签署任何东西,也不依赖viem或醚.
流动
1. createUsdcPaymentIntent(api, sizeBytes) → locks a USDC price, returns amount + chain, token and receiver
2. approve(receiverAddress, usdcAmount) → on tokenAddress, on chainId (your wallet code)
3. payIntentWithToken(intentId, usdcAmount) → on receiverAddress, no value (your wallet code)
4. watchPaymentTransaction(api, id, tx) → the hash from step 3, not step 2, as soon as you have it
5. waitForPaymentCompletion(api, id, { settleGraceMs }) → polls until COMPLETED
所有这些通话都需要一个API密钥,所以从您的服务器中进行. createUsdcPaymentIntent 从 Auto Drive 获得链式ID、接收器地址和符号地址(getUsdcPaymentTarget) (中文(简体) ). 总是使用这些值。 别用硬密码.
SDK为钱包的呼叫输出出两个最小的ABI:
erc20ApprovalAbi数字 :approve, (中文(简体) ),allowance财务报告和审定财务报表balanceOf。其中不包括transfer或者说transferFrom因为接收者合同会自己拉出信物.usdcReceiverAbi数字 :payIntentWithToken(bytes32 intentId, uint256 amount)。 。 。 .
示例(节点,使用viem)
import {
createAutoDriveApi,
erc20ApprovalAbi,
PaymentApiError,
usdcReceiverAbi,
} from '@autonomys/auto-drive'
import { NetworkId } from '@autonomys/auto-utils'
import { createPublicClient, createWalletClient, http, type Hex } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { mainnet, sepolia } from 'viem/chains'
const api = createAutoDriveApi({
apiKey: process.env.AUTO_DRIVE_API_KEY!,
network: NetworkId.MAINNET,
})
// Step 1 — lock a USDC price for 1 GiB. Accepts a number or a bigint.
const intent = await api.createUsdcPaymentIntent(BigInt(1024) ** BigInt(3))
// intent.usdcAmount — exact amount in base units (6 decimals), as a BigInt-safe string
// intent.usdcAmountFormatted — human-readable amount, e.g. "2.500001"
// intent.chainId, intent.tokenAddress, intent.receiverAddress — where to pay
// intent.expiresAt — ISO timestamp when the price lock ends (10 minutes by default)
// Use the chain that Auto Drive names. Do not pick one yourself.
const chain = [mainnet, sepolia].find((c) => c.id === intent.chainId)
if (!chain) throw new Error(`Unsupported USDC chain ${intent.chainId}`)
const account = privateKeyToAccount(process.env.PAYER_PRIVATE_KEY as Hex)
const transport = http(process.env.ETH_RPC_URL)
const publicClient = createPublicClient({ chain, transport })
const walletClient = createWalletClient({ account, chain, transport })
const amount = BigInt(intent.usdcAmount)
const token = intent.tokenAddress as Hex
const receiver = intent.receiverAddress as Hex
// Step 2 — approve the receiver to pull the USDC (skip if the allowance is enough)
const allowance = await publicClient.readContract({
address: token,
abi: erc20ApprovalAbi,
functionName: 'allowance',
args: [account.address, receiver],
})
if (allowance < amount) {
const approveHash = await walletClient.writeContract({
address: token,
abi: erc20ApprovalAbi,
functionName: 'approve',
args: [receiver, amount],
})
await publicClient.waitForTransactionReceipt({ hash: approveHash })
}
// Step 3 — pay the intent. No value: the receiver pulls the approved USDC.
const txHash = await walletClient.writeContract({
address: receiver,
abi: usdcReceiverAbi,
functionName: 'payIntentWithToken',
args: [intent.intentId as Hex, amount],
})
// Step 4 — tell Auto Drive about the payment transaction (not the approval).
// Do this as soon as you have the hash, while the price lock is still open.
try {
await api.watchPaymentTransaction(intent.intentId, txHash)
} catch (error) {
// 410: the price lock has lapsed. The payment can still settle, so continue.
if (!(error instanceof PaymentApiError && error.status === 410)) throw error
}
// Wait for the receipt before step 5, so block time does not use up the 410 grace.
const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash })
if (receipt.status !== 'success') throw new Error(`USDC payment reverted: ${txHash}`)
// Step 5 — wait for credits. Pass settleGraceMs so a 410 does not end the wait too early.
const result = await api.waitForPaymentCompletion(intent.intentId, {
settleGraceMs: intent.settleGraceMs,
})
// result: 'COMPLETED' | 'EXPIRED' | 'FAILED' | 'OVER_CAP'
// 'EXPIRED' here means the SDK stopped waiting. Check your credits before you
// report the payment as lost (see below).
为什么 settleGraceMs 事项
GET /intents/:id hTTP 410 一旦价格锁定因没有记录交易散列的意向而失效,则回答。 例如,当 watchPaymentTransaction 它本身就有一个410。 (有记录的散列车,410起于Auto Drive停止接受付款时,目前为20分钟后) expiresAt. ) (中文(简体) ). 这就是为什么这个例子要求 watchPaymentTransaction 当钱包返回散列时, 在等待接收之前: 当锁打开时记录的散列会让状态结束点不回答 410 。 前410后,在锁端附近发送的付款仍然可以贷记.
与 settleGraceMs 设定, waitForPaymentCompletion 在410次投票中持续了那么长的时间 然后再回来 'EXPIRED'在重排时钟之间读取成功 。 无 settleGraceMs,一个410抛出一个 PaymentApiError,如前几个版本。 Auto Drive 服务于支付目标的值,以及 createUsdcPaymentIntent 复制到意图.
铭记这些要点:
'EXPIRED'从这条路径意味着SDK停止了等待. 无法证明这笔付款已经丢失,因为Auto Drive仍然可以暂时信用. 在告诉用户付款失败之前, 请检查您的信用值 .- 优等从SDK所看到的前410来测量. 在你打电话前等付款收据
waitForPaymentCompletion。 。 。 . - 保留
timeoutMs(默认5分) 大于锁上剩下的时间加settleGraceMs。否则,该调用在返回前会发出超时错误'EXPIRED'。 。 。 .
处理错误
当 Auto Drive 拒绝付款请求时, SDK 丢出一个 PaymentApiError它拥有HTTP status 并且,对于编码错误,机器可读 code数字 :
code | 状态 | 怎么办 |
|---|---|---|
PRICE_ORACLE_UNAVAILABLE | 第503条 | 稍后重试同样的请求 |
PRICE_UNSTABLE | 第503条 | 稍后重试同样的请求 |
USDC_PAYMENTS_UNAVAILABLE | 第503条 | USDC暂时关闭了 用 AI3 支付, 或稍后重试 |
USDC_PAYMENTS_DISABLED | 403 (韩语) | USDC不给你服务。 与 AI3 支付 |
CREDIT_CAP_EXCEEDED | 403 (韩语) | 丢弃为 CreditCapExceededError少买 |
GOOGLE_ACCOUNT_REQUIRED | 403 (韩语) | 使用谷歌注册账户的 API 密钥 |
有些失败没有 code检查 status 用于:
- 400点: 请求无效, 例如
requestedBytes大于整个信用上限. - 404号
/intents数字 : 账户无法购买信用。 自动驱动器通常发送此选项, 而不是GOOGLE_ACCOUNT_REQUIRED的账户. - 410点: 价格锁失效了 见 为什么
settleGraceMs事项。 。 。 .
try {
const intent = await api.createUsdcPaymentIntent(sizeBytes)
} catch (error) {
if (!(error instanceof PaymentApiError)) throw error
switch (error.code) {
case 'PRICE_ORACLE_UNAVAILABLE':
case 'PRICE_UNSTABLE':
// retry later
break
case 'USDC_PAYMENTS_DISABLED':
case 'USDC_PAYMENTS_UNAVAILABLE':
// fall back to api.createPaymentIntent (AI3)
break
default:
throw error
}
}
许可证
这个项目根据麻省理工学院的许可证获得许可。 见 自由主义 详细文件.
额外资源
- 自治学院: 学习更多 自治学院。 。 。 .
联系人
如果您有任何问题或需要支持,请随意联系:
- GitHub 问题数字 : GitHub 问题页面
我们感谢你的反馈和贡献!