@stellar/stellar-base 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +1262 -0
  2. package/LICENSE +202 -0
  3. package/README.md +198 -0
  4. package/dist/stellar-base.js +30777 -0
  5. package/dist/stellar-base.min.js +2 -0
  6. package/lib/account.js +80 -0
  7. package/lib/address.js +169 -0
  8. package/lib/asset.js +323 -0
  9. package/lib/auth.js +253 -0
  10. package/lib/claimant.js +193 -0
  11. package/lib/contract.js +113 -0
  12. package/lib/events.js +42 -0
  13. package/lib/fee_bump_transaction.js +134 -0
  14. package/lib/generated/curr_generated.js +8315 -0
  15. package/lib/generated/next_generated.js +8315 -0
  16. package/lib/get_liquidity_pool_id.js +57 -0
  17. package/lib/hashing.js +12 -0
  18. package/lib/index.js +385 -0
  19. package/lib/invocation.js +195 -0
  20. package/lib/keypair.js +308 -0
  21. package/lib/liquidity_pool_asset.js +126 -0
  22. package/lib/liquidity_pool_id.js +101 -0
  23. package/lib/memo.js +270 -0
  24. package/lib/muxed_account.js +159 -0
  25. package/lib/network.js +22 -0
  26. package/lib/numbers/index.js +85 -0
  27. package/lib/numbers/int128.js +50 -0
  28. package/lib/numbers/int256.js +50 -0
  29. package/lib/numbers/sc_int.js +134 -0
  30. package/lib/numbers/uint128.js +50 -0
  31. package/lib/numbers/uint256.js +50 -0
  32. package/lib/numbers/xdr_large_int.js +267 -0
  33. package/lib/operation.js +715 -0
  34. package/lib/operations/account_merge.js +32 -0
  35. package/lib/operations/allow_trust.js +57 -0
  36. package/lib/operations/begin_sponsoring_future_reserves.js +38 -0
  37. package/lib/operations/bump_sequence.js +37 -0
  38. package/lib/operations/change_trust.js +52 -0
  39. package/lib/operations/claim_claimable_balance.js +40 -0
  40. package/lib/operations/clawback.js +46 -0
  41. package/lib/operations/clawback_claimable_balance.js +39 -0
  42. package/lib/operations/create_account.js +37 -0
  43. package/lib/operations/create_claimable_balance.js +65 -0
  44. package/lib/operations/create_passive_sell_offer.js +44 -0
  45. package/lib/operations/end_sponsoring_future_reserves.js +27 -0
  46. package/lib/operations/extend_footprint_ttl.js +45 -0
  47. package/lib/operations/index.js +254 -0
  48. package/lib/operations/inflation.js +23 -0
  49. package/lib/operations/invoke_host_function.js +219 -0
  50. package/lib/operations/liquidity_pool_deposit.js +64 -0
  51. package/lib/operations/liquidity_pool_withdraw.js +50 -0
  52. package/lib/operations/manage_buy_offer.js +50 -0
  53. package/lib/operations/manage_data.js +41 -0
  54. package/lib/operations/manage_sell_offer.js +50 -0
  55. package/lib/operations/path_payment_strict_receive.js +68 -0
  56. package/lib/operations/path_payment_strict_send.js +68 -0
  57. package/lib/operations/payment.js +47 -0
  58. package/lib/operations/restore_footprint.js +38 -0
  59. package/lib/operations/revoke_sponsorship.js +301 -0
  60. package/lib/operations/set_options.js +135 -0
  61. package/lib/operations/set_trustline_flags.js +84 -0
  62. package/lib/scval.js +369 -0
  63. package/lib/signerkey.js +103 -0
  64. package/lib/signing.js +96 -0
  65. package/lib/soroban.js +96 -0
  66. package/lib/sorobandata_builder.js +218 -0
  67. package/lib/strkey.js +400 -0
  68. package/lib/transaction.js +369 -0
  69. package/lib/transaction_base.js +248 -0
  70. package/lib/transaction_builder.js +753 -0
  71. package/lib/util/checksum.js +20 -0
  72. package/lib/util/continued_fraction.js +58 -0
  73. package/lib/util/decode_encode_muxed_account.js +116 -0
  74. package/lib/util/util.js +14 -0
  75. package/lib/xdr.js +9 -0
  76. package/package.json +133 -0
  77. package/types/curr.d.ts +14078 -0
  78. package/types/index.d.ts +1270 -0
  79. package/types/next.d.ts +14078 -0
  80. package/types/xdr.d.ts +1 -0
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.SignerKey = void 0;
7
+ var _xdr = _interopRequireDefault(require("./xdr"));
8
+ var _strkey = require("./strkey");
9
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
10
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
11
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
12
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
13
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
14
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
15
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
16
+ /**
17
+ * A container class with helpers to convert between signer keys
18
+ * (`xdr.SignerKey`) and {@link StrKey}s.
19
+ *
20
+ * It's primarly used for manipulating the `extraSigners` precondition on a
21
+ * {@link Transaction}.
22
+ *
23
+ * @see {@link TransactionBuilder.setExtraSigners}
24
+ */
25
+ var SignerKey = exports.SignerKey = /*#__PURE__*/function () {
26
+ function SignerKey() {
27
+ _classCallCheck(this, SignerKey);
28
+ }
29
+ _createClass(SignerKey, null, [{
30
+ key: "decodeAddress",
31
+ value:
32
+ /**
33
+ * Decodes a StrKey address into an xdr.SignerKey instance.
34
+ *
35
+ * Only ED25519 public keys (G...), pre-auth transactions (T...), hashes
36
+ * (H...), and signed payloads (P...) can be signer keys.
37
+ *
38
+ * @param {string} address a StrKey-encoded signer address
39
+ * @returns {xdr.SignerKey}
40
+ */
41
+ function decodeAddress(address) {
42
+ var signerKeyMap = {
43
+ ed25519PublicKey: _xdr["default"].SignerKey.signerKeyTypeEd25519,
44
+ preAuthTx: _xdr["default"].SignerKey.signerKeyTypePreAuthTx,
45
+ sha256Hash: _xdr["default"].SignerKey.signerKeyTypeHashX,
46
+ signedPayload: _xdr["default"].SignerKey.signerKeyTypeEd25519SignedPayload
47
+ };
48
+ var vb = _strkey.StrKey.getVersionByteForPrefix(address);
49
+ var encoder = signerKeyMap[vb];
50
+ if (!encoder) {
51
+ throw new Error("invalid signer key type (".concat(vb, ")"));
52
+ }
53
+ var raw = (0, _strkey.decodeCheck)(vb, address);
54
+ switch (vb) {
55
+ case 'signedPayload':
56
+ return encoder(new _xdr["default"].SignerKeyEd25519SignedPayload({
57
+ ed25519: raw.slice(0, 32),
58
+ payload: raw.slice(32 + 4)
59
+ }));
60
+ case 'ed25519PublicKey': // falls through
61
+ case 'preAuthTx': // falls through
62
+ case 'sha256Hash': // falls through
63
+ default:
64
+ return encoder(raw);
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Encodes a signer key into its StrKey equivalent.
70
+ *
71
+ * @param {xdr.SignerKey} signerKey the signer
72
+ * @returns {string} the StrKey representation of the signer
73
+ */
74
+ }, {
75
+ key: "encodeSignerKey",
76
+ value: function encodeSignerKey(signerKey) {
77
+ var strkeyType;
78
+ var raw;
79
+ switch (signerKey["switch"]()) {
80
+ case _xdr["default"].SignerKeyType.signerKeyTypeEd25519():
81
+ strkeyType = 'ed25519PublicKey';
82
+ raw = signerKey.value();
83
+ break;
84
+ case _xdr["default"].SignerKeyType.signerKeyTypePreAuthTx():
85
+ strkeyType = 'preAuthTx';
86
+ raw = signerKey.value();
87
+ break;
88
+ case _xdr["default"].SignerKeyType.signerKeyTypeHashX():
89
+ strkeyType = 'sha256Hash';
90
+ raw = signerKey.value();
91
+ break;
92
+ case _xdr["default"].SignerKeyType.signerKeyTypeEd25519SignedPayload():
93
+ strkeyType = 'signedPayload';
94
+ raw = signerKey.ed25519SignedPayload().toXDR('raw');
95
+ break;
96
+ default:
97
+ throw new Error("invalid SignerKey (type: ".concat(signerKey["switch"](), ")"));
98
+ }
99
+ return (0, _strkey.encodeCheck)(strkeyType, raw);
100
+ }
101
+ }]);
102
+ return SignerKey;
103
+ }();
package/lib/signing.js ADDED
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.FastSigning = void 0;
7
+ exports.generate = generate;
8
+ exports.sign = sign;
9
+ exports.verify = verify;
10
+ // This module provides the signing functionality used by the stellar network
11
+ // The code below may look a little strange... this is because we try to provide
12
+ // the most efficient signing method possible. First, we try to load the
13
+ // native `sodium-native` package for node.js environments, and if that fails we
14
+ // fallback to `tweetnacl`
15
+
16
+ var actualMethods = {};
17
+
18
+ /**
19
+ * Use this flag to check if fast signing (provided by `sodium-native` package) is available.
20
+ * If your app is signing a large number of transaction or verifying a large number
21
+ * of signatures make sure `sodium-native` package is installed.
22
+ */
23
+ var FastSigning = exports.FastSigning = checkFastSigning();
24
+ function sign(data, secretKey) {
25
+ return actualMethods.sign(data, secretKey);
26
+ }
27
+ function verify(data, signature, publicKey) {
28
+ return actualMethods.verify(data, signature, publicKey);
29
+ }
30
+ function generate(secretKey) {
31
+ return actualMethods.generate(secretKey);
32
+ }
33
+ function checkFastSigning() {
34
+ return typeof window === 'undefined' ? checkFastSigningNode() : checkFastSigningBrowser();
35
+ }
36
+ function checkFastSigningNode() {
37
+ // NOTE: we use commonjs style require here because es6 imports
38
+ // can only occur at the top level. thanks, obama.
39
+ var sodium;
40
+ try {
41
+ // eslint-disable-next-line
42
+ sodium = require('sodium-native');
43
+ } catch (err) {
44
+ return checkFastSigningBrowser();
45
+ }
46
+ if (!Object.keys(sodium).length) {
47
+ return checkFastSigningBrowser();
48
+ }
49
+ actualMethods.generate = function (secretKey) {
50
+ var pk = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES);
51
+ var sk = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES);
52
+ sodium.crypto_sign_seed_keypair(pk, sk, secretKey);
53
+ return pk;
54
+ };
55
+ actualMethods.sign = function (data, secretKey) {
56
+ data = Buffer.from(data);
57
+ var signature = Buffer.alloc(sodium.crypto_sign_BYTES);
58
+ sodium.crypto_sign_detached(signature, data, secretKey);
59
+ return signature;
60
+ };
61
+ actualMethods.verify = function (data, signature, publicKey) {
62
+ data = Buffer.from(data);
63
+ try {
64
+ return sodium.crypto_sign_verify_detached(signature, data, publicKey);
65
+ } catch (e) {
66
+ return false;
67
+ }
68
+ };
69
+ return true;
70
+ }
71
+ function checkFastSigningBrowser() {
72
+ // fallback to `tweetnacl` if we're in the browser or
73
+ // if there was a failure installing `sodium-native`
74
+ // eslint-disable-next-line
75
+ var nacl = require('tweetnacl');
76
+ actualMethods.generate = function (secretKey) {
77
+ var secretKeyUint8 = new Uint8Array(secretKey);
78
+ var naclKeys = nacl.sign.keyPair.fromSeed(secretKeyUint8);
79
+ return Buffer.from(naclKeys.publicKey);
80
+ };
81
+ actualMethods.sign = function (data, secretKey) {
82
+ data = Buffer.from(data);
83
+ data = new Uint8Array(data.toJSON().data);
84
+ secretKey = new Uint8Array(secretKey.toJSON().data);
85
+ var signature = nacl.sign.detached(data, secretKey);
86
+ return Buffer.from(signature);
87
+ };
88
+ actualMethods.verify = function (data, signature, publicKey) {
89
+ data = Buffer.from(data);
90
+ data = new Uint8Array(data.toJSON().data);
91
+ signature = new Uint8Array(signature.toJSON().data);
92
+ publicKey = new Uint8Array(publicKey.toJSON().data);
93
+ return nacl.sign.detached.verify(data, signature, publicKey);
94
+ };
95
+ return false;
96
+ }
package/lib/soroban.js ADDED
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.Soroban = void 0;
7
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
8
+ function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); }
9
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
10
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
11
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
12
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
13
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
14
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
15
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
16
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
17
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
18
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
19
+ /* Helper class to assist with formatting and parsing token amounts. */
20
+ var Soroban = exports.Soroban = /*#__PURE__*/function () {
21
+ function Soroban() {
22
+ _classCallCheck(this, Soroban);
23
+ }
24
+ _createClass(Soroban, null, [{
25
+ key: "formatTokenAmount",
26
+ value:
27
+ /**
28
+ * Given a whole number smart contract amount of a token and an amount of
29
+ * decimal places (if the token has any), it returns a "display" value.
30
+ *
31
+ * All arithmetic inside the contract is performed on integers to avoid
32
+ * potential precision and consistency issues of floating-point.
33
+ *
34
+ * @param {string} amount the token amount you want to display
35
+ * @param {number} decimals specify how many decimal places a token has
36
+ *
37
+ * @returns {string} the display value
38
+ * @throws {TypeError} if the given amount has a decimal point already
39
+ * @example
40
+ * formatTokenAmount("123000", 4) === "12.3";
41
+ */
42
+ function formatTokenAmount(amount, decimals) {
43
+ if (amount.includes('.')) {
44
+ throw new TypeError('No decimals are allowed');
45
+ }
46
+ var formatted = amount;
47
+ if (decimals > 0) {
48
+ if (decimals > formatted.length) {
49
+ formatted = ['0', formatted.toString().padStart(decimals, '0')].join('.');
50
+ } else {
51
+ formatted = [formatted.slice(0, -decimals), formatted.slice(-decimals)].join('.');
52
+ }
53
+ }
54
+
55
+ // remove trailing zero if any
56
+ return formatted.replace(/(\.\d*?)0+$/, '$1');
57
+ }
58
+
59
+ /**
60
+ * Parse a token amount to use it on smart contract
61
+ *
62
+ * This function takes the display value and its decimals (if the token has
63
+ * any) and returns a string that'll be used within the smart contract.
64
+ *
65
+ * @param {string} value the token amount you want to use it on smart
66
+ * contract which you've been displaying in a UI
67
+ * @param {number} decimals the number of decimal places expected in the
68
+ * display value (different than the "actual" number, because suffix zeroes
69
+ * might not be present)
70
+ *
71
+ * @returns {string} the whole number token amount represented by the display
72
+ * value with the decimal places shifted over
73
+ *
74
+ * @example
75
+ * const displayValueAmount = "123.4560"
76
+ * const parsedAmtForSmartContract = parseTokenAmount(displayValueAmount, 5);
77
+ * parsedAmtForSmartContract === "12345600"
78
+ */
79
+ }, {
80
+ key: "parseTokenAmount",
81
+ value: function parseTokenAmount(value, decimals) {
82
+ var _fraction$padEnd;
83
+ var _value$split$slice = value.split('.').slice(),
84
+ _value$split$slice2 = _toArray(_value$split$slice),
85
+ whole = _value$split$slice2[0],
86
+ fraction = _value$split$slice2[1],
87
+ rest = _value$split$slice2.slice(2);
88
+ if (rest.length) {
89
+ throw new Error("Invalid decimal value: ".concat(value));
90
+ }
91
+ var shifted = BigInt(whole + ((_fraction$padEnd = fraction === null || fraction === void 0 ? void 0 : fraction.padEnd(decimals, '0')) !== null && _fraction$padEnd !== void 0 ? _fraction$padEnd : '0'.repeat(decimals)));
92
+ return shifted.toString();
93
+ }
94
+ }]);
95
+ return Soroban;
96
+ }();
@@ -0,0 +1,218 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.SorobanDataBuilder = void 0;
7
+ var _xdr = _interopRequireDefault(require("./xdr"));
8
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
9
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
10
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
11
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
12
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
13
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
14
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
15
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
16
+ /**
17
+ * Supports building {@link xdr.SorobanTransactionData} structures with various
18
+ * items set to specific values.
19
+ *
20
+ * This is recommended for when you are building
21
+ * {@link Operation.extendFootprintTtl} / {@link Operation.restoreFootprint}
22
+ * operations and need to {@link TransactionBuilder.setSorobanData} to avoid
23
+ * (re)building the entire data structure from scratch.
24
+ *
25
+ * @constructor
26
+ *
27
+ * @param {string | xdr.SorobanTransactionData} [sorobanData] either a
28
+ * base64-encoded string that represents an
29
+ * {@link xdr.SorobanTransactionData} instance or an XDR instance itself
30
+ * (it will be copied); if omitted or "falsy" (e.g. an empty string), it
31
+ * starts with an empty instance
32
+ *
33
+ * @example
34
+ * // You want to use an existing data blob but override specific parts.
35
+ * const newData = new SorobanDataBuilder(existing)
36
+ * .setReadOnly(someLedgerKeys)
37
+ * .setRefundableFee("1000")
38
+ * .build();
39
+ *
40
+ * // You want an instance from scratch
41
+ * const newData = new SorobanDataBuilder()
42
+ * .setFootprint([someLedgerKey], [])
43
+ * .setRefundableFee("1000")
44
+ * .build();
45
+ */
46
+ var SorobanDataBuilder = exports.SorobanDataBuilder = /*#__PURE__*/function () {
47
+ function SorobanDataBuilder(sorobanData) {
48
+ _classCallCheck(this, SorobanDataBuilder);
49
+ _defineProperty(this, "_data", void 0);
50
+ var data;
51
+ if (!sorobanData) {
52
+ data = new _xdr["default"].SorobanTransactionData({
53
+ resources: new _xdr["default"].SorobanResources({
54
+ footprint: new _xdr["default"].LedgerFootprint({
55
+ readOnly: [],
56
+ readWrite: []
57
+ }),
58
+ instructions: 0,
59
+ readBytes: 0,
60
+ writeBytes: 0
61
+ }),
62
+ ext: new _xdr["default"].ExtensionPoint(0),
63
+ resourceFee: new _xdr["default"].Int64(0)
64
+ });
65
+ } else if (typeof sorobanData === 'string' || ArrayBuffer.isView(sorobanData)) {
66
+ data = SorobanDataBuilder.fromXDR(sorobanData);
67
+ } else {
68
+ data = SorobanDataBuilder.fromXDR(sorobanData.toXDR()); // copy
69
+ }
70
+ this._data = data;
71
+ }
72
+
73
+ /**
74
+ * Decodes and builds a {@link xdr.SorobanTransactionData} instance.
75
+ * @param {Uint8Array|Buffer|string} data raw input to decode
76
+ * @returns {xdr.SorobanTransactionData}
77
+ */
78
+ _createClass(SorobanDataBuilder, [{
79
+ key: "setResourceFee",
80
+ value:
81
+ /**
82
+ * Sets the resource fee portion of the Soroban data.
83
+ * @param {number | bigint | string} fee the resource fee to set (int64)
84
+ * @returns {SorobanDataBuilder}
85
+ */
86
+ function setResourceFee(fee) {
87
+ this._data.resourceFee(new _xdr["default"].Int64(fee));
88
+ return this;
89
+ }
90
+
91
+ /**
92
+ * Sets up the resource metrics.
93
+ *
94
+ * You should almost NEVER need this, as its often generated / provided to you
95
+ * by transaction simulation/preflight from a Soroban RPC server.
96
+ *
97
+ * @param {number} cpuInstrs number of CPU instructions
98
+ * @param {number} readBytes number of bytes being read
99
+ * @param {number} writeBytes number of bytes being written
100
+ *
101
+ * @returns {SorobanDataBuilder}
102
+ */
103
+ }, {
104
+ key: "setResources",
105
+ value: function setResources(cpuInstrs, readBytes, writeBytes) {
106
+ this._data.resources().instructions(cpuInstrs);
107
+ this._data.resources().readBytes(readBytes);
108
+ this._data.resources().writeBytes(writeBytes);
109
+ return this;
110
+ }
111
+
112
+ /**
113
+ * Appends the given ledger keys to the existing storage access footprint.
114
+ * @param {xdr.LedgerKey[]} readOnly read-only keys to add
115
+ * @param {xdr.LedgerKey[]} readWrite read-write keys to add
116
+ * @returns {SorobanDataBuilder} this builder instance
117
+ */
118
+ }, {
119
+ key: "appendFootprint",
120
+ value: function appendFootprint(readOnly, readWrite) {
121
+ return this.setFootprint(this.getReadOnly().concat(readOnly), this.getReadWrite().concat(readWrite));
122
+ }
123
+
124
+ /**
125
+ * Sets the storage access footprint to be a certain set of ledger keys.
126
+ *
127
+ * You can also set each field explicitly via
128
+ * {@link SorobanDataBuilder.setReadOnly} and
129
+ * {@link SorobanDataBuilder.setReadWrite} or add to the existing footprint
130
+ * via {@link SorobanDataBuilder.appendFootprint}.
131
+ *
132
+ * Passing `null|undefined` to either parameter will IGNORE the existing
133
+ * values. If you want to clear them, pass `[]`, instead.
134
+ *
135
+ * @param {xdr.LedgerKey[]|null} [readOnly] the set of ledger keys to set in
136
+ * the read-only portion of the transaction's `sorobanData`, or `null |
137
+ * undefined` to keep the existing keys
138
+ * @param {xdr.LedgerKey[]|null} [readWrite] the set of ledger keys to set in
139
+ * the read-write portion of the transaction's `sorobanData`, or `null |
140
+ * undefined` to keep the existing keys
141
+ * @returns {SorobanDataBuilder} this builder instance
142
+ */
143
+ }, {
144
+ key: "setFootprint",
145
+ value: function setFootprint(readOnly, readWrite) {
146
+ if (readOnly !== null) {
147
+ // null means "leave me alone"
148
+ this.setReadOnly(readOnly);
149
+ }
150
+ if (readWrite !== null) {
151
+ this.setReadWrite(readWrite);
152
+ }
153
+ return this;
154
+ }
155
+
156
+ /**
157
+ * @param {xdr.LedgerKey[]} readOnly read-only keys in the access footprint
158
+ * @returns {SorobanDataBuilder}
159
+ */
160
+ }, {
161
+ key: "setReadOnly",
162
+ value: function setReadOnly(readOnly) {
163
+ this._data.resources().footprint().readOnly(readOnly !== null && readOnly !== void 0 ? readOnly : []);
164
+ return this;
165
+ }
166
+
167
+ /**
168
+ * @param {xdr.LedgerKey[]} readWrite read-write keys in the access footprint
169
+ * @returns {SorobanDataBuilder}
170
+ */
171
+ }, {
172
+ key: "setReadWrite",
173
+ value: function setReadWrite(readWrite) {
174
+ this._data.resources().footprint().readWrite(readWrite !== null && readWrite !== void 0 ? readWrite : []);
175
+ return this;
176
+ }
177
+
178
+ /**
179
+ * @returns {xdr.SorobanTransactionData} a copy of the final data structure
180
+ */
181
+ }, {
182
+ key: "build",
183
+ value: function build() {
184
+ return _xdr["default"].SorobanTransactionData.fromXDR(this._data.toXDR()); // clone
185
+ }
186
+
187
+ //
188
+ // getters follow
189
+ //
190
+
191
+ /** @returns {xdr.LedgerKey[]} the read-only storage access pattern */
192
+ }, {
193
+ key: "getReadOnly",
194
+ value: function getReadOnly() {
195
+ return this.getFootprint().readOnly();
196
+ }
197
+
198
+ /** @returns {xdr.LedgerKey[]} the read-write storage access pattern */
199
+ }, {
200
+ key: "getReadWrite",
201
+ value: function getReadWrite() {
202
+ return this.getFootprint().readWrite();
203
+ }
204
+
205
+ /** @returns {xdr.LedgerFootprint} the storage access pattern */
206
+ }, {
207
+ key: "getFootprint",
208
+ value: function getFootprint() {
209
+ return this._data.resources().footprint();
210
+ }
211
+ }], [{
212
+ key: "fromXDR",
213
+ value: function fromXDR(data) {
214
+ return _xdr["default"].SorobanTransactionData.fromXDR(data, typeof data === 'string' ? 'base64' : 'raw');
215
+ }
216
+ }]);
217
+ return SorobanDataBuilder;
218
+ }();