ethers.js/lib.commonjs/abi/coders/number.js

49 lines
1.9 KiB
JavaScript
Raw Normal View History

2022-09-05 23:57:11 +03:00
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NumberCoder = void 0;
2022-09-16 05:58:45 +03:00
const index_js_1 = require("../../utils/index.js");
2022-09-05 23:57:11 +03:00
const typed_js_1 = require("../typed.js");
const abstract_coder_js_1 = require("./abstract-coder.js");
const BN_0 = BigInt(0);
const BN_1 = BigInt(1);
const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
2022-11-30 23:44:23 +03:00
/**
* @_ignore
*/
2022-09-05 23:57:11 +03:00
class NumberCoder extends abstract_coder_js_1.Coder {
size;
signed;
constructor(size, signed, localName) {
const name = ((signed ? "int" : "uint") + (size * 8));
super(name, name, localName, false);
2022-09-16 05:58:45 +03:00
(0, index_js_1.defineProperties)(this, { size, signed }, { size: "number", signed: "boolean" });
2022-09-05 23:57:11 +03:00
}
defaultValue() {
return 0;
}
encode(writer, _value) {
2022-09-16 05:58:45 +03:00
let value = (0, index_js_1.getBigInt)(typed_js_1.Typed.dereference(_value, this.type));
2022-09-05 23:57:11 +03:00
// Check bounds are safe for encoding
2022-09-16 05:58:45 +03:00
let maxUintValue = (0, index_js_1.mask)(BN_MAX_UINT256, abstract_coder_js_1.WordSize * 8);
2022-09-05 23:57:11 +03:00
if (this.signed) {
2022-09-16 05:58:45 +03:00
let bounds = (0, index_js_1.mask)(maxUintValue, (this.size * 8) - 1);
2022-09-05 23:57:11 +03:00
if (value > bounds || value < -(bounds + BN_1)) {
this._throwError("value out-of-bounds", _value);
}
2022-11-30 23:44:23 +03:00
value = (0, index_js_1.toTwos)(value, 8 * abstract_coder_js_1.WordSize);
2022-09-05 23:57:11 +03:00
}
2022-09-16 05:58:45 +03:00
else if (value < BN_0 || value > (0, index_js_1.mask)(maxUintValue, this.size * 8)) {
2022-09-05 23:57:11 +03:00
this._throwError("value out-of-bounds", _value);
}
return writer.writeValue(value);
}
decode(reader) {
2022-09-16 05:58:45 +03:00
let value = (0, index_js_1.mask)(reader.readValue(), this.size * 8);
2022-09-05 23:57:11 +03:00
if (this.signed) {
2022-09-16 05:58:45 +03:00
value = (0, index_js_1.fromTwos)(value, this.size * 8);
2022-09-05 23:57:11 +03:00
}
return value;
}
}
exports.NumberCoder = NumberCoder;
//# sourceMappingURL=number.js.map