你如何从js客户端调用一个payable方法?
How do you call a payable method from the js client?
假设您有一个 smart contract
方法,该方法需要将存款附加到方法调用上,类似于这样的 rust
方法:
#[payable]
pub fn spend(&mu self, age: u8){
assert!(env::attached_deposit() > 0,
"Insufficient deposit.");
.
.
.
}
现在您使用 near-api-js
设置您的合约并继续调用它。如何在客户端 js 中调用此方法并附加一些 Near
?
您照常设置合同:
const contract = await new nearlib.Contract(
walletConnection.account(),
nearConfig.contractName,
{
// View methods are read only. They don't modify the state, but usually return some value.
viewMethods: ["getCorgi", "getCorgisList", "displayGolbalCorgis"],
// Change methods can modify the state. But you don't receive the returned value when called.
changeMethods: ["transferCorgi", "createCorgi", "deleteCorgi"],
// Sender is the account ID to initialize transactions.
sender: walletConnection.getAccountId(),
}
);
通常,您将 change 方法调用为:
await contract.transferCorgi({"receiver": "frol.near", "id": "corgi_xxx", "message": "hello"})
但是,当您想附加一些NEAR代币或增加gas津贴时,您需要指定optional positional arguments after the arguments:
await contract.changeMethodName(args: object, gas: BN, amount: BN)
备注:
- BN是大数表示
- 默认 gas 限额为 300 Tgas [300 * 10^12 gas],了解更多:FAQ on Gas in the documentation, NEP67
- 数量在 yoctoNEAR 中指定(1 NEAR 是 10^24 yoctoNEAR)
例如:
const ONE_NEAR = new BN("1000000000000000000000000")
await contract.createCorgi({"id": "corgi_xxx"}, new BN("3000000000000"), ONE_NEAR)
假设您有一个 smart contract
方法,该方法需要将存款附加到方法调用上,类似于这样的 rust
方法:
#[payable]
pub fn spend(&mu self, age: u8){
assert!(env::attached_deposit() > 0,
"Insufficient deposit.");
.
.
.
}
现在您使用 near-api-js
设置您的合约并继续调用它。如何在客户端 js 中调用此方法并附加一些 Near
?
您照常设置合同:
const contract = await new nearlib.Contract(
walletConnection.account(),
nearConfig.contractName,
{
// View methods are read only. They don't modify the state, but usually return some value.
viewMethods: ["getCorgi", "getCorgisList", "displayGolbalCorgis"],
// Change methods can modify the state. But you don't receive the returned value when called.
changeMethods: ["transferCorgi", "createCorgi", "deleteCorgi"],
// Sender is the account ID to initialize transactions.
sender: walletConnection.getAccountId(),
}
);
通常,您将 change 方法调用为:
await contract.transferCorgi({"receiver": "frol.near", "id": "corgi_xxx", "message": "hello"})
但是,当您想附加一些NEAR代币或增加gas津贴时,您需要指定optional positional arguments after the arguments:
await contract.changeMethodName(args: object, gas: BN, amount: BN)
备注:
- BN是大数表示
- 默认 gas 限额为 300 Tgas [300 * 10^12 gas],了解更多:FAQ on Gas in the documentation, NEP67
- 数量在 yoctoNEAR 中指定(1 NEAR 是 10^24 yoctoNEAR)
例如:
const ONE_NEAR = new BN("1000000000000000000000000")
await contract.createCorgi({"id": "corgi_xxx"}, new BN("3000000000000"), ONE_NEAR)