欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > 在 Solana 中实现映射表与嵌套映射表

在 Solana 中实现映射表与嵌套映射表

2025/4/2 15:54:03 来源:https://blog.csdn.net/2408_87746709/article/details/146604449  浏览:    关键词:在 Solana 中实现映射表与嵌套映射表

本文将通过填充 seeds 参数,模拟 Solidity 中的映射(mapping)功能。seeds 中的数据类似于映射的键,用于生成唯一的数据账户地址。

以 Solidity 为例:

contract ExampleMapping {struct SomeNum { uint64 num; }mapping(uint64 => SomeNum) public exampleMap;function setExampleMap(uint64 key, uint64 val) public {exampleMap[key] = SomeNum(val);}
}

我们将在 Solana Anchor 中创建项目 example_map,实现类似功能。


初始化映射表

Rust 实现

首先展示初始化代码,引入新语法:

use anchor_lang::prelude::*;
use std::mem::size_of;declare_id!("BB7Z6YvBMPRKDutbVh8SGy8QS82e9GZc4jLrEt1Ym2o9");#[program]
pub mod example_map {use super::*;pub fn initialize(ctx: Context<Initialize>, key: u64) -> Result<()> {Ok(())}
}#[derive(Accounts)]
#[instruction(key: u64)]
pub struct Initialize<'info> {#[account(init,payer = signer,space = size_of::<Val>() + 8,seeds = [&key.to_le_bytes()],bump)]val: Account<'info, Val>,#[account(mut)]signer: Signer<'info>,system_program: Program<'info, System>,
}#[account]
pub struct Val {value: u64,
}

关键点解析

  1. seeds = [&key.to_le_bytes()]
    • seeds 需为字节数组,key(u64)通过 to_le_bytes() 转换为 8 字节小端数组(little-endian)。
    • 可选大端(to_be_bytes()),只需保持一致。
    • seeds 类似映射表的键,生成唯一的程序派生地址(PDA)。
  2. #[instruction(key: u64)]
    • 使 initialize 的参数 key 在 Initialize 结构中可见,用于 seeds 计算。
    • 缺少此宏,init 将无法访问 key。

类比:seeds 中的 key 类似 mapping(uint64 => Val) 中的键。

Typescript 实现

初始化测试代码:

import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { ExampleMap } from "../target/types/example_map";describe("example_map", () => {anchor.setProvider(anchor.AnchorProvider.env());const program = anchor.workspace.ExampleMap as Program<ExampleMap>;it("Initialize mapping storage", async () => {const key = new anchor.BN(42);const seeds = [key.toArrayLike(Buffer, "le", 8)];const [valueAccount, _bump] = anchor.web3.PublicKey.findProgramAddressSync(seeds,program.programId);await program.methods.initialize(key).accounts({ val: valueAccount }).rpc();});
});
  • key.toArrayLike(Buffer, "le", 8) 将 u64 转为 8 字节小端缓冲区,与 Rust 保持一致。
  • 每个映射表项对应一个独立账户,需单独初始化。

设置映射表值

Rust 实现

新增 set 函数:

#[program]
pub mod example_map {use super::*;pub fn initialize(ctx: Context<Initialize>, key: u64) -> Result<()> {Ok(())}pub fn set(ctx: Context<Set>, key: u64, val: u64) -> Result<()> {ctx.accounts.val.value = val;Ok(())}
}#[derive(Accounts)]
#[instruction(key: u64)]
pub struct Set<'info> {#[account(mut, seeds = [&key.to_le_bytes()], bump)]val: Account<'info, Val>,
}
  • Set 使用相同 seeds 定位账户,mut 表示可写。

Typescript 读写

完整测试代码:

import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { ExampleMap } from "../target/types/example_map";describe("example_map", () => {anchor.setProvider(anchor.AnchorProvider.env());const program = anchor.workspace.ExampleMap as Program<ExampleMap>;it("Initialize and set value", async () => {const key = new anchor.BN(42);const value = new anchor.BN(1337);const seeds = [key.toArrayLike(Buffer, "le", 8)];let valueAccount = anchor.web3.PublicKey.findProgramAddressSync(seeds,program.programId,)[0];await program.methods.initialize(key).accounts({ val: valueAccount }).rpc();await program.methods.set(key, value).accounts({ val: valueAccount }).rpc();let result = await program.account.val.fetch(valueAccount);console.log(`the value ${result.value} was stored in ${valueAccount.toBase58()}`);});
});
  • 客户端通过 seeds 推导地址,读写语法与前文一致。

嵌套映射表解析

Solidity vs. 真实嵌套

  • 真实嵌套(如 Python):map[key1] 返回另一映射表。
  • Solidity 嵌套:mapping(uint => mapping(uint => uint)) 需提供所有键(如 map[key1][key2])获取值,非真正嵌套。
  • Solana 限制:seeds 模拟 Solidity 风格,需完整提供所有键。

Rust 实现

完整嵌套映射表代码:

use anchor_lang::prelude::*;
use std::mem::size_of;declare_id!("BB7Z6YvBMPRKDutbVh8SGy8QS82e9GZc4jLrEt1Ym2o9");#[program]
pub mod example_map {use super::*;pub fn initialize(ctx: Context<Initialize>, key1: u64, key2: u64) -> Result<()> {Ok(())}pub fn set(ctx: Context<Set>, key1: u64, key2: u64, val: u64) -> Result<()> {ctx.accounts.val.value = val;Ok(())}
}#[derive(Accounts)]
#[instruction(key1: u64, key2: u64)]
pub struct Initialize<'info> {#[account(init,payer = signer,space = size_of::<Val>() + 8,seeds = [&key1.to_le_bytes(), &key2.to_le_bytes()],bump)]val: Account<'info, Val>,#[account(mut)]signer: Signer<'info>,system_program: Program<'info, System>,
}#[derive(Accounts)]
#[instruction(key1: u64, key2: u64)]
pub struct Set<'info> {#[account(mut, seeds = [&key1.to_le_bytes(), &key2.to_le_bytes()], bump)]val: Account<'info, Val>,
}#[account]
pub struct Val {value: u64,
}
  • seeds 包含两个键,模拟 mapping(uint => mapping(uint => uint))。

Typescript 实现

import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { ExampleMap } from "../target/types/example_map";describe("example_map", () => {anchor.setProvider(anchor.AnchorProvider.env());const program = anchor.workspace.ExampleMap as Program<ExampleMap>;it("Initialize and set value", async () => {const key1 = new anchor.BN(42);const key2 = new anchor.BN(43);const value = new anchor.BN(1337);const seeds = [key1.toArrayLike(Buffer, "le", 8), key2.toArrayLike(Buffer, "le", 8)];let valueAccount = anchor.web3.PublicKey.findProgramAddressSync(seeds,program.programId,)[0];await program.methods.initialize(key1, key2).accounts({val: valueAccount}).rpc();await program.methods.set(key1, key2, value).accounts({val: valueAccount}).rpc();let result = await program.account.val.fetch(valueAccount);console.log(`the value ${result.value} was stored in ${valueAccount.toBase58()}`);});
});

本文到此结束,更多相关,信息,请,, https://t.me/gtokentool  。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词