我已经建立了一个简单的智能契约来运行Ethereum区块链,并且我试图复制它在Solana上的一些行为。在做了一些轻微的更改之后,我成功地用索朗以Solana为目标编写了程序,但我不知道如何调用这些方法;在这方面似乎没有大量的文档或示例。例如,如果我的程序编写如下:
contract Example {
function foo(...) { ... }
function bar(...) { ... }
}
我将如何指定对foo
的调用与对bar
的调用?此外,我将如何编码这些方法调用的参数?
目前,我的方法是使用@solana/buffer-布局库将我的参数编码为一个结构,从lo.u8('instruction')
开始指定方法调用(在示例中,我假设0
将引用foo
,1
将引用bar
)。我采用这种方法是基于查看@solana/spl-令牌的源代码(特别是这个文件及其依赖项),但我不确定它是否适用于使用索朗编译的程序,缓冲区布局编码也引发了意外错误:
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,
);
虽然这种类型错误似乎很明显,但它与solana-实验室/solana-程序库存储库中的示例代码不一致。我很确定这个问题与我对lo.seq()
的使用有关,但我不知道问题是什么。
除了这个类型的错误,我的方法是正确的吗?还是我的方法根本上是错误的?如何用编码的参数调用预期的方法?谢谢你的帮助。
发布于 2022-03-15 09:49:02
有一个更好的库可供您使用,@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-for-solana改编的示例
https://stackoverflow.com/questions/71474942
复制相似问题