网站Logo 北之屿

IDL 指令账户计算

beiyu
13
2025-08-08

寻找程序的入口点

查看关键词:initializeinitcreate

分析账户定义模式

通过PDA计算地址

{
  "name": "market",
  "writable": true,
  "pda": {
    "seeds": [
      {
        "kind": "const",
        "value": [109, 97, 114, 107, 101, 116]
      },
      {
        "kind": "arg",
        "path": "args.symbol"
      },
      {
        "kind": "account",
        "path": "config"
      }
    ]
  }
}

这里直接给出了pda的参数,直接使用findProgramAddressSync方法

const [marketPDA,] = PublicKey.findProgramAddressSync(
    [
        Buffer.from([109, 97, 114, 107, 101, 116]),        // 常量 "market"
        Buffer.from("TTYL"),          // 代币符号
        configAddress.toBuffer() // config 地址
    ],
    programId
);

通过Relations计算地址

当账户有relations 说明是一个关联地址,可以从关联地址中获取到这个地址

{
  "name": "native_vault",
  "writable": true,
  "relations": ["market"]
}

计算步骤,通过fetch获取账户数据

// 1. 通过pda计算出 marketPDA
const [marketPDA] = PublicKey.findProgramAddressSync(
    [
        Buffer.from("market"),
        Buffer.from("TTYL"),
        configPublicKey.toBuffer()  //已知的地址
    ],
    programId
);
// 2. 获取关联账户数据
const marketAccount = await program.account.market.fetch(marketPDA);

// 1. 从账户数据中读取地址
const nativeVault = marketAccount.nativeVault;
const tokenVault = marketAccount.tokenVault;
const communityVault = marketAccount.communityVault;

marketAccount 对应的数据结构

{
  "name": "Market",
  "type": {
    "kind": "struct", 
    "fields": [
      {
        "name": "config",
        "type": "pubkey"
      },
      {
        "name": "token_mint",
        "type": "pubkey"
      },
      {
        "name": "token_vault",
        "type": "pubkey"
      },
      {
        "name": "native_vault", 
        "type": "pubkey"
      },
      {
        "name": "community_vault",
        "type": "pubkey"
      }
    ]
  }
}

计算代币ATA地址

// 提供代币地址和钱包地址
// 查看idl中所需的TOKEN_PROGRAM_ID和ASSOCIATED_TOKEN_PROGRAM_ID是什么

const tokenRecipientPDA = await getAssociatedTokenAddress(
  new PublicKey(tokenMint),  //代币地址
  payer,   // 用户钱包地址PublicKey对象钱包
  false, // allowOwnerOffCurve
  TOKEN_PROGRAM_ID,   //这里可指定程序
  ASSOCIATED_TOKEN_PROGRAM_ID   // 这里也能指定
);

动物装饰