与合约和断言类似,一旦您在 Sway 中编写了脚本并使用 forc build
编译它(了解有关如何使用 Sway 的更多信息,请阅读此处 ),您将获得脚本二进制文件。使用二进制文件,您可以像下面的代码片段一样实例化一个 script
:
// #import { ScriptRequest, arrayify };
const scriptBin = readFileSync(join(__dirname, './path/to/script-binary.bin'));
type MyStruct = {
arg_one: boolean;
arg_two: BigNumberish;
};
/**
* @group node
*/
describe('Script', () => {
let scriptRequest: ScriptRequest<MyStruct, MyStruct>;
beforeAll(() => {
const abiInterface = new Interface(scriptJsonAbi);
scriptRequest = new ScriptRequest(
scriptBin,
(myStruct: MyStruct) => {
const encoded = abiInterface.functions.main.encodeArguments([myStruct]);
return arrayify(encoded);
},
(scriptResult) => {
if (scriptResult.returnReceipt.type === ReceiptType.Revert) {
throw new Error('Reverted');
}
if (scriptResult.returnReceipt.type !== ReceiptType.ReturnData) {
throw new Error('fail');
}
const decoded = abiInterface.functions.main.decodeOutput(scriptResult.returnReceipt.data);
return (decoded as any)[0];
}
);
});
在下一节 中,我们将展示如何运行一个脚本。