在Solana Solidity程序上调用特定方法



我已经构建了一个简单的智能合约,可以在以太坊区块链上运行,我正在尝试在Solana上复制它的一些行为。在做了一些细微的更改后,我已经设法用Solang编译了针对Solana的程序,但我不确定如何调用这些方法;这方面似乎没有大量的文档或例子。例如,如果我的程序是这样写的:

contract Example {
function foo(...) { ... }
function bar(...) { ... }
}

如何指定对foo的调用与对bar的调用?此外,我将如何对这些方法调用的参数进行编码?

目前,我的方法是使用@solana/缓冲区布局库将我的参数编码为结构,从lo.u8('instruction')开始指定方法调用(在本例中,我假设0将引用foo1将引用bar(。我在查看@solana/spl令牌的源代码(特别是这个文件及其依赖项(的基础上采取了这种方法,但我不确定它是否适用于使用Solang编译的程序,缓冲区布局编码也引发了一个意外错误:

TypeError: Blob.encode requires (length 32) Uint8Array as src

引发此错误的代码如下:

const method = lo.struct([
lo.u8('instruction'),
lo.seq(
lo.blob(32),
lo.greedy(lo.blob(32).span),
'publicKeys',
),
])
const data = Buffer.alloc(64); // Using method.span here results in an error, as method.span == -1
method.encode(
{
instruction: 0,
publicKeys: [firstPublicKey, secondPublicKey],
},
data,
);

虽然这种类型的错误看起来很明显,但它与solanalabs/solana程序库存储库中的示例代码不一致。我很确定这个问题与我使用lo.seq()有关,但我不确定问题出在哪里

除了这种类型的错误之外,我的方法是正确的,还是我的方法根本错误?如何使用编码的参数调用预期的方法?谢谢你的帮助。

有一个更好的库供您使用,@solana/solidity,它有一个Contract类来封装对契约的调用。

例如,在您的情况下,您可以执行以下操作:

const { Connection, LAMPORTS_PER_SOL, Keypair } = require('@solana/web3.js');
const { Contract, Program } = require('@solana/solidity');
const { readFileSync } = require('fs');
const EXAMPLE_ABI = JSON.parse(readFileSync('./example.abi', 'utf8'));
const PROGRAM_SO = readFileSync('./example.so');
(async function () {
console.log('Connecting to your local Solana node ...');
const connection = new Connection('http://localhost:8899', 'confirmed');
const payer = Keypair.generate();
console.log('Airdropping SOL to a new wallet ...');
const signature = await connection.requestAirdrop(payer.publicKey, LAMPORTS_PER_SOL);
await connection.confirmTransaction(signature, 'confirmed');
const program = Keypair.generate();
const storage = Keypair.generate();
const contract = new Contract(connection, program.publicKey, storage.publicKey, EXAMPLE_ABI, payer);
await contract.load(program, PROGRAM_SO);
console.log('Program deployment finished, deploying the example contract ...');
await contract.deploy('example', [true], program, storage);
const res = await contract.functions.foo();
console.log('foo: ' + res.result);
const res2 = await contract.functions.bar();
console.log('bar: ' + res2.result);
})();

示例改编自https://github.com/hyperledger-labs/solang#build-用于solana

有关程序包的详细信息,请访问https://www.npmjs.com/package/@solana/固体

最新更新