[英]How to convert near to yocto using assemblyscript?
If I have an amount less than 1 NEAR let's say .5 near, how do I convert it and store it using assemblyscript in a near protocol smart contract?如果我的金额小于 1 NEAR,比如说 0.5 近,我如何转换它并将其使用汇编脚本存储在近协议智能合约中?
I tried to convert it to f64 first and make the arithmetic operation then convert it back to u128 like:我尝试先将其转换为 f64 并进行算术运算,然后将其转换回 u128,如:
u128.fromF64((ONE_NEAR.toF64() * .5))
but fromF64 gives the following error但 fromF64 给出以下错误
ExecutionError: 'WebAssembly trap: An arithmetic exception, e.g. divided by zero.'
I think you are going about this the wrong way.我认为你正在以错误的方式解决这个问题。 You need to operate on yoctoNEAR instead of 0.5 NEAR.您需要在 yoctoNEAR 而不是 0.5 NEAR 上进行操作。
Below examples are taken directly from the docs以下示例直接取自文档
https://docs.near.org/docs/api/naj-quick-reference#utils https://docs.near.org/docs/api/naj-quick-reference#utils
NEAR => yoctoNEAR NEAR => yoctoNEAR
// converts NEAR amount into yoctoNEAR (10^-24)
const { utils } = nearAPI;
const amountInYocto = utils.format.parseNearAmount("1");
YoctoNEAR => NEAR YoctoNEAR => 近
// converts yoctoNEAR (10^-24) amount into NEAR
const { utils } = nearAPI;
const amountInNEAR = utils.format.formatNearAmount("1000000000000000000000000");
basically, you have to multiply the near amount (eg 1.25) by a large number first (eg 1000000) in order to preserve the fraction before you convert the number to Yocto using toYoctob128(u128.from(amount))
.基本上,在使用toYoctob128(u128.from(amount))
将数字转换为 Yocto 之前,您必须先将近似量(例如 1.25)乘以一个大数(例如 1000000)以保留分数。 and after the successful conversion, you can use u128.div()
(eg u128.div(amountInU128, u128.from(1000000))
) to get the correct value.转换成功后,您可以使用u128.div()
(例如u128.div(amountInU128, u128.from(1000000))
)来获取正确的值。
PS The larger the number you multiply by first the more accurate the conversion will be but be careful not to exceed the number
and u128
limit. PS你首先乘以的数字越大,转换就越准确,但注意不要超过number
和u128
的限制。
Here is a complete example:这是一个完整的例子:
Contract Class:
nearToYocto(x: string): u128 {
let amountBase = (parseFloat(x) * BASE_TO_CONVERT);
return u128.div(toYoctob128(u128.from(amountBase)), u128.from(BASE_TO_CONVERT));
}
utils:
export const BASE_TO_CONVERT = 1000000.0;
export function toYoctob128(amount: u128): u128 {
return u128.mul(ONE_NEAR, amount)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.