@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,135 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.setOptions = setOptions;
7
+ var _xdr = _interopRequireDefault(require("../xdr"));
8
+ var _keypair = require("../keypair");
9
+ var _strkey = require("../strkey");
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
11
+ /* eslint-disable no-param-reassign */
12
+
13
+ function weightCheckFunction(value, name) {
14
+ if (value >= 0 && value <= 255) {
15
+ return true;
16
+ }
17
+ throw new Error("".concat(name, " value must be between 0 and 255"));
18
+ }
19
+
20
+ /**
21
+ * Returns an XDR SetOptionsOp. A "set options" operations set or clear account flags,
22
+ * set the account's inflation destination, and/or add new signers to the account.
23
+ * The flags used in `opts.clearFlags` and `opts.setFlags` can be the following:
24
+ * - `{@link AuthRequiredFlag}`
25
+ * - `{@link AuthRevocableFlag}`
26
+ * - `{@link AuthImmutableFlag}`
27
+ * - `{@link AuthClawbackEnabledFlag}`
28
+ *
29
+ * It's possible to set/clear multiple flags at once using logical or.
30
+ *
31
+ * @function
32
+ * @alias Operation.setOptions
33
+ *
34
+ * @param {object} opts Options object
35
+ * @param {string} [opts.inflationDest] - Set this account ID as the account's inflation destination.
36
+ * @param {(number|string)} [opts.clearFlags] - Bitmap integer for which account flags to clear.
37
+ * @param {(number|string)} [opts.setFlags] - Bitmap integer for which account flags to set.
38
+ * @param {number|string} [opts.masterWeight] - The master key weight.
39
+ * @param {number|string} [opts.lowThreshold] - The sum weight for the low threshold.
40
+ * @param {number|string} [opts.medThreshold] - The sum weight for the medium threshold.
41
+ * @param {number|string} [opts.highThreshold] - The sum weight for the high threshold.
42
+ * @param {object} [opts.signer] - Add or remove a signer from the account. The signer is
43
+ * deleted if the weight is 0. Only one of `ed25519PublicKey`, `sha256Hash`, `preAuthTx` should be defined.
44
+ * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer.
45
+ * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string) of preimage that will unlock funds. Preimage should be used as signature of future transaction.
46
+ * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction that will unlock funds.
47
+ * @param {string} [opts.signer.ed25519SignedPayload] - Signed payload signer (ed25519 public key + raw payload) for atomic transaction signature disclosure.
48
+ * @param {number|string} [opts.signer.weight] - The weight of the new signer (0 to delete or 1-255)
49
+ * @param {string} [opts.homeDomain] - sets the home domain used for reverse federation lookup.
50
+ * @param {string} [opts.source] - The source account (defaults to transaction source).
51
+ *
52
+ * @returns {xdr.SetOptionsOp} XDR operation
53
+ * @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags)
54
+ */
55
+ function setOptions(opts) {
56
+ var attributes = {};
57
+ if (opts.inflationDest) {
58
+ if (!_strkey.StrKey.isValidEd25519PublicKey(opts.inflationDest)) {
59
+ throw new Error('inflationDest is invalid');
60
+ }
61
+ attributes.inflationDest = _keypair.Keypair.fromPublicKey(opts.inflationDest).xdrAccountId();
62
+ }
63
+ attributes.clearFlags = this._checkUnsignedIntValue('clearFlags', opts.clearFlags);
64
+ attributes.setFlags = this._checkUnsignedIntValue('setFlags', opts.setFlags);
65
+ attributes.masterWeight = this._checkUnsignedIntValue('masterWeight', opts.masterWeight, weightCheckFunction);
66
+ attributes.lowThreshold = this._checkUnsignedIntValue('lowThreshold', opts.lowThreshold, weightCheckFunction);
67
+ attributes.medThreshold = this._checkUnsignedIntValue('medThreshold', opts.medThreshold, weightCheckFunction);
68
+ attributes.highThreshold = this._checkUnsignedIntValue('highThreshold', opts.highThreshold, weightCheckFunction);
69
+ if (opts.homeDomain !== undefined && typeof opts.homeDomain !== 'string') {
70
+ throw new TypeError('homeDomain argument must be of type String');
71
+ }
72
+ attributes.homeDomain = opts.homeDomain;
73
+ if (opts.signer) {
74
+ var weight = this._checkUnsignedIntValue('signer.weight', opts.signer.weight, weightCheckFunction);
75
+ var key;
76
+ var setValues = 0;
77
+ if (opts.signer.ed25519PublicKey) {
78
+ if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) {
79
+ throw new Error('signer.ed25519PublicKey is invalid.');
80
+ }
81
+ var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey);
82
+
83
+ // eslint-disable-next-line new-cap
84
+ key = new _xdr["default"].SignerKey.signerKeyTypeEd25519(rawKey);
85
+ setValues += 1;
86
+ }
87
+ if (opts.signer.preAuthTx) {
88
+ if (typeof opts.signer.preAuthTx === 'string') {
89
+ opts.signer.preAuthTx = Buffer.from(opts.signer.preAuthTx, 'hex');
90
+ }
91
+ if (!(Buffer.isBuffer(opts.signer.preAuthTx) && opts.signer.preAuthTx.length === 32)) {
92
+ throw new Error('signer.preAuthTx must be 32 bytes Buffer.');
93
+ }
94
+
95
+ // eslint-disable-next-line new-cap
96
+ key = new _xdr["default"].SignerKey.signerKeyTypePreAuthTx(opts.signer.preAuthTx);
97
+ setValues += 1;
98
+ }
99
+ if (opts.signer.sha256Hash) {
100
+ if (typeof opts.signer.sha256Hash === 'string') {
101
+ opts.signer.sha256Hash = Buffer.from(opts.signer.sha256Hash, 'hex');
102
+ }
103
+ if (!(Buffer.isBuffer(opts.signer.sha256Hash) && opts.signer.sha256Hash.length === 32)) {
104
+ throw new Error('signer.sha256Hash must be 32 bytes Buffer.');
105
+ }
106
+
107
+ // eslint-disable-next-line new-cap
108
+ key = new _xdr["default"].SignerKey.signerKeyTypeHashX(opts.signer.sha256Hash);
109
+ setValues += 1;
110
+ }
111
+ if (opts.signer.ed25519SignedPayload) {
112
+ if (!_strkey.StrKey.isValidSignedPayload(opts.signer.ed25519SignedPayload)) {
113
+ throw new Error('signer.ed25519SignedPayload is invalid.');
114
+ }
115
+ var _rawKey = _strkey.StrKey.decodeSignedPayload(opts.signer.ed25519SignedPayload);
116
+ var signedPayloadXdr = _xdr["default"].SignerKeyEd25519SignedPayload.fromXDR(_rawKey);
117
+
118
+ // eslint-disable-next-line new-cap
119
+ key = _xdr["default"].SignerKey.signerKeyTypeEd25519SignedPayload(signedPayloadXdr);
120
+ setValues += 1;
121
+ }
122
+ if (setValues !== 1) {
123
+ throw new Error('Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.');
124
+ }
125
+ attributes.signer = new _xdr["default"].Signer({
126
+ key: key,
127
+ weight: weight
128
+ });
129
+ }
130
+ var setOptionsOp = new _xdr["default"].SetOptionsOp(attributes);
131
+ var opAttributes = {};
132
+ opAttributes.body = _xdr["default"].OperationBody.setOptions(setOptionsOp);
133
+ this.setSourceAccount(opAttributes, opts);
134
+ return new _xdr["default"].Operation(opAttributes);
135
+ }
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.setTrustLineFlags = setTrustLineFlags;
7
+ var _xdr = _interopRequireDefault(require("../xdr"));
8
+ var _keypair = require("../keypair");
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
+ /**
12
+ * Creates a trustline flag configuring operation.
13
+ *
14
+ * For the flags, set them to true to enable them and false to disable them. Any
15
+ * unmodified operations will be marked `undefined` in the result.
16
+ *
17
+ * Note that you can only **clear** the clawbackEnabled flag set; it must be set
18
+ * account-wide via operations.SetOptions (setting
19
+ * xdr.AccountFlags.clawbackEnabled).
20
+ *
21
+ * @function
22
+ * @alias Operation.setTrustLineFlags
23
+ *
24
+ * @param {object} opts - Options object
25
+ * @param {string} opts.trustor - the account whose trustline this is
26
+ * @param {Asset} opts.asset - the asset on the trustline
27
+ * @param {object} opts.flags - the set of flags to modify
28
+ *
29
+ * @param {bool} [opts.flags.authorized] - authorize account to perform
30
+ * transactions with its credit
31
+ * @param {bool} [opts.flags.authorizedToMaintainLiabilities] - authorize
32
+ * account to maintain and reduce liabilities for its credit
33
+ * @param {bool} [opts.flags.clawbackEnabled] - stop claimable balances on
34
+ * this trustlines from having clawbacks enabled (this flag can only be set
35
+ * to false!)
36
+ * @param {string} [opts.source] - The source account for the operation.
37
+ * Defaults to the transaction's source account.
38
+ *
39
+ * @note You must include at least one flag.
40
+ *
41
+ * @return {xdr.SetTrustLineFlagsOp}
42
+ *
43
+ * @link xdr.AccountFlags
44
+ * @link xdr.TrustLineFlags
45
+ * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#set-trustline-flags-operation
46
+ * @see https://developers.stellar.org/docs/start/list-of-operations/#set-options
47
+ */
48
+ function setTrustLineFlags() {
49
+ var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
50
+ var attributes = {};
51
+ if (_typeof(opts.flags) !== 'object' || Object.keys(opts.flags).length === 0) {
52
+ throw new Error('opts.flags must be a map of boolean flags to modify');
53
+ }
54
+ var mapping = {
55
+ authorized: _xdr["default"].TrustLineFlags.authorizedFlag(),
56
+ authorizedToMaintainLiabilities: _xdr["default"].TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),
57
+ clawbackEnabled: _xdr["default"].TrustLineFlags.trustlineClawbackEnabledFlag()
58
+ };
59
+
60
+ /* eslint no-bitwise: "off" */
61
+ var clearFlag = 0;
62
+ var setFlag = 0;
63
+ Object.keys(opts.flags).forEach(function (flagName) {
64
+ if (!Object.prototype.hasOwnProperty.call(mapping, flagName)) {
65
+ throw new Error("unsupported flag name specified: ".concat(flagName));
66
+ }
67
+ var flagValue = opts.flags[flagName];
68
+ var bit = mapping[flagName].value;
69
+ if (flagValue === true) {
70
+ setFlag |= bit;
71
+ } else if (flagValue === false) {
72
+ clearFlag |= bit;
73
+ }
74
+ });
75
+ attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId();
76
+ attributes.asset = opts.asset.toXDRObject();
77
+ attributes.clearFlags = clearFlag;
78
+ attributes.setFlags = setFlag;
79
+ var opAttributes = {
80
+ body: _xdr["default"].OperationBody.setTrustLineFlags(new _xdr["default"].SetTrustLineFlagsOp(attributes))
81
+ };
82
+ this.setSourceAccount(opAttributes, opts);
83
+ return new _xdr["default"].Operation(opAttributes);
84
+ }
package/lib/scval.js ADDED
@@ -0,0 +1,369 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.nativeToScVal = nativeToScVal;
7
+ exports.scValToNative = scValToNative;
8
+ var _xdr = _interopRequireDefault(require("./xdr"));
9
+ var _address = require("./address");
10
+ var _contract = require("./contract");
11
+ var _index = require("./numbers/index");
12
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
13
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
14
+ 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."); }
15
+ 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); }
16
+ 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; }
17
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
18
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
19
+ 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); }
20
+ /**
21
+ * Attempts to convert native types into smart contract values
22
+ * ({@link xdr.ScVal}).
23
+ *
24
+ * Provides conversions from smart contract XDR values ({@link xdr.ScVal}) to
25
+ * native JavaScript types.
26
+ *
27
+ * The conversions are as follows:
28
+ *
29
+ * - xdr.ScVal -> passthrough
30
+ * - null/undefined -> scvVoid
31
+ * - string -> scvString (a copy is made)
32
+ * - UintArray8 -> scvBytes (a copy is made)
33
+ * - boolean -> scvBool
34
+ *
35
+ * - number/bigint -> the smallest possible XDR integer type that will fit the
36
+ * input value (if you want a specific type, use {@link ScInt})
37
+ *
38
+ * - {@link Address} or {@link Contract} -> scvAddress (for contracts and
39
+ * public keys)
40
+ *
41
+ * - Array<T> -> scvVec after attempting to convert each item of type `T` to an
42
+ * xdr.ScVal (recursively). note that all values must be the same type!
43
+ *
44
+ * - object -> scvMap after attempting to convert each key and value to an
45
+ * xdr.ScVal (recursively). note that there is no restriction on types
46
+ * matching anywhere (unlike arrays)
47
+ *
48
+ * When passing an integer-like native value, you can also optionally specify a
49
+ * type which will force a particular interpretation of that value.
50
+ *
51
+ * Note that not all type specifications are compatible with all `ScVal`s, e.g.
52
+ * `toScVal("a string", {type: "i256"})` will throw.
53
+ *
54
+ * @param {any} val - a native (or convertible) input value to wrap
55
+ * @param {object} [opts] - an optional set of hints around the type of
56
+ * conversion you'd like to see
57
+ * @param {string} [opts.type] - there is different behavior for different input
58
+ * types for `val`:
59
+ *
60
+ * - when `val` is an integer-like type (i.e. number|bigint), this will be
61
+ * forwarded to {@link ScInt} or forced to be u32/i32.
62
+ *
63
+ * - when `val` is an array type, this is forwarded to the recursion
64
+ *
65
+ * - when `val` is an object type (key-value entries), this should be an
66
+ * object in which each key has a pair of types (to represent forced types
67
+ * for the key and the value), where `null` (or a missing entry) indicates
68
+ * the default interpretation(s) (refer to the examples, below)
69
+ *
70
+ * - when `val` is a string type, this can be 'string' or 'symbol' to force
71
+ * a particular interpretation of `val`.
72
+ *
73
+ * - when `val` is a bytes-like type, this can be 'string', 'symbol', or
74
+ * 'bytes' to force a particular interpretation
75
+ *
76
+ * As a simple example, `nativeToScVal("hello", {type: 'symbol'})` will
77
+ * return an `scvSymbol`, whereas without the type it would have been an
78
+ * `scvString`.
79
+ *
80
+ * @returns {xdr.ScVal} a wrapped, smart, XDR version of the input value
81
+ * @throws {TypeError} if...
82
+ * - there are arrays with more than one type in them
83
+ * - there are values that do not have a sensible conversion (e.g. random XDR
84
+ * types, custom classes)
85
+ * - the type of the input object (or some inner value of said object) cannot
86
+ * be determined (via `typeof`)
87
+ * - the type you specified (via `opts.type`) is incompatible with the value
88
+ * you passed in (`val`), e.g. `nativeToScVal("a string", { type: 'i128' })`,
89
+ * though this does not apply for types that ignore `opts` (e.g. addresses).
90
+ * @see scValToNative
91
+ *
92
+ * @example
93
+ * nativeToScVal(1000); // gives ScValType === scvU64
94
+ * nativeToScVal(1000n); // gives ScValType === scvU64
95
+ * nativeToScVal(1n << 100n); // gives ScValType === scvU128
96
+ * nativeToScVal(1000, { type: 'u32' }); // gives ScValType === scvU32
97
+ * nativeToScVal(1000, { type: 'i125' }); // gives ScValType === scvI256
98
+ * nativeToScVal("a string"); // gives ScValType === scvString
99
+ * nativeToScVal("a string", { type: 'symbol' }); // gives scvSymbol
100
+ * nativeToScVal(new Uint8Array(5)); // scvBytes
101
+ * nativeToScVal(new Uint8Array(5), { type: 'symbol' }); // scvSymbol
102
+ * nativeToScVal(null); // scvVoid
103
+ * nativeToScVal(true); // scvBool
104
+ * nativeToScVal([1, 2, 3]); // gives scvVec with each element as scvU64
105
+ * nativeToScVal([1, 2, 3], { type: 'i128' }); // scvVec<scvI128>
106
+ * nativeToScVal({ 'hello': 1, 'world': [ true, false ] }, {
107
+ * type: {
108
+ * 'hello': [ 'symbol', 'i128' ],
109
+ * }
110
+ * })
111
+ * // gives scvMap with entries: [
112
+ * // [ scvSymbol, scvI128 ],
113
+ * // [ scvString, scvArray<scvBool> ]
114
+ * // ]
115
+ *
116
+ * @example
117
+ * import { nativeToScVal, scValToNative, ScInt, xdr } from 'stellar-base';
118
+ *
119
+ * let gigaMap = {
120
+ * bool: true,
121
+ * void: null,
122
+ * u32: xdr.ScVal.scvU32(1),
123
+ * i32: xdr.ScVal.scvI32(1),
124
+ * u64: 1n,
125
+ * i64: -1n,
126
+ * u128: new ScInt(1).toU128(),
127
+ * i128: new ScInt(1).toI128(),
128
+ * u256: new ScInt(1).toU256(),
129
+ * i256: new ScInt(1).toI256(),
130
+ * map: {
131
+ * arbitrary: 1n,
132
+ * nested: 'values',
133
+ * etc: false
134
+ * },
135
+ * vec: ['same', 'type', 'list'],
136
+ * };
137
+ *
138
+ * // then, simply:
139
+ * let scv = nativeToScVal(gigaMap); // scv.switch() == xdr.ScValType.scvMap()
140
+ *
141
+ * // then...
142
+ * someContract.call("method", scv);
143
+ *
144
+ * // Similarly, the inverse should work:
145
+ * scValToNative(scv) == gigaMap; // true
146
+ */
147
+ function nativeToScVal(val) {
148
+ var _val$constructor$name, _val$constructor;
149
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
150
+ switch (_typeof(val)) {
151
+ case 'object':
152
+ if (val === null) {
153
+ return _xdr["default"].ScVal.scvVoid();
154
+ }
155
+ if (val instanceof _xdr["default"].ScVal) {
156
+ return val; // should we copy?
157
+ }
158
+ if (val instanceof _address.Address) {
159
+ return val.toScVal();
160
+ }
161
+ if (val instanceof _contract.Contract) {
162
+ return val.address().toScVal();
163
+ }
164
+ if (val instanceof Uint8Array || Buffer.isBuffer(val)) {
165
+ var _opts$type;
166
+ var copy = Uint8Array.from(val);
167
+ switch ((_opts$type = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type !== void 0 ? _opts$type : 'bytes') {
168
+ case 'bytes':
169
+ return _xdr["default"].ScVal.scvBytes(copy);
170
+ case 'symbol':
171
+ return _xdr["default"].ScVal.scvSymbol(copy);
172
+ case 'string':
173
+ return _xdr["default"].ScVal.scvString(copy);
174
+ default:
175
+ throw new TypeError("invalid type (".concat(opts.type, ") specified for bytes-like value"));
176
+ }
177
+ }
178
+ if (Array.isArray(val)) {
179
+ if (val.length > 0 && val.some(function (v) {
180
+ return _typeof(v) !== _typeof(val[0]);
181
+ })) {
182
+ throw new TypeError("array values (".concat(val, ") must have the same type (types: ").concat(val.map(function (v) {
183
+ return _typeof(v);
184
+ }).join(','), ")"));
185
+ }
186
+ return _xdr["default"].ScVal.scvVec(val.map(function (v) {
187
+ return nativeToScVal(v, opts);
188
+ }));
189
+ }
190
+ if (((_val$constructor$name = (_val$constructor = val.constructor) === null || _val$constructor === void 0 ? void 0 : _val$constructor.name) !== null && _val$constructor$name !== void 0 ? _val$constructor$name : '') !== 'Object') {
191
+ var _val$constructor2;
192
+ throw new TypeError("cannot interpret ".concat((_val$constructor2 = val.constructor) === null || _val$constructor2 === void 0 ? void 0 : _val$constructor2.name, " value as ScVal (").concat(JSON.stringify(val), ")"));
193
+ }
194
+ return _xdr["default"].ScVal.scvMap(Object.entries(val).map(function (_ref) {
195
+ var _k, _opts$type2;
196
+ var _ref2 = _slicedToArray(_ref, 2),
197
+ k = _ref2[0],
198
+ v = _ref2[1];
199
+ // the type can be specified with an entry for the key and the value,
200
+ // e.g. val = { 'hello': 1 } and opts.type = { hello: [ 'symbol',
201
+ // 'u128' ]} or you can use `null` for the default interpretation
202
+ var _ref3 = (_k = ((_opts$type2 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type2 !== void 0 ? _opts$type2 : {})[k]) !== null && _k !== void 0 ? _k : [null, null],
203
+ _ref4 = _slicedToArray(_ref3, 2),
204
+ keyType = _ref4[0],
205
+ valType = _ref4[1];
206
+ var keyOpts = keyType ? {
207
+ type: keyType
208
+ } : {};
209
+ var valOpts = valType ? {
210
+ type: valType
211
+ } : {};
212
+ return new _xdr["default"].ScMapEntry({
213
+ key: nativeToScVal(k, keyOpts),
214
+ val: nativeToScVal(v, valOpts)
215
+ });
216
+ }));
217
+ case 'number':
218
+ case 'bigint':
219
+ switch (opts === null || opts === void 0 ? void 0 : opts.type) {
220
+ case 'u32':
221
+ return _xdr["default"].ScVal.scvU32(val);
222
+ case 'i32':
223
+ return _xdr["default"].ScVal.scvI32(val);
224
+ default:
225
+ break;
226
+ }
227
+ return new _index.ScInt(val, {
228
+ type: opts === null || opts === void 0 ? void 0 : opts.type
229
+ }).toScVal();
230
+ case 'string':
231
+ {
232
+ var _opts$type3;
233
+ var optType = (_opts$type3 = opts === null || opts === void 0 ? void 0 : opts.type) !== null && _opts$type3 !== void 0 ? _opts$type3 : 'string';
234
+ switch (optType) {
235
+ case 'string':
236
+ return _xdr["default"].ScVal.scvString(val);
237
+ case 'symbol':
238
+ return _xdr["default"].ScVal.scvSymbol(val);
239
+ case 'address':
240
+ return new _address.Address(val).toScVal();
241
+ default:
242
+ if (_index.XdrLargeInt.isType(optType)) {
243
+ return new _index.XdrLargeInt(optType, val).toScVal();
244
+ }
245
+ throw new TypeError("invalid type (".concat(opts.type, ") specified for string value"));
246
+ }
247
+ }
248
+ case 'boolean':
249
+ return _xdr["default"].ScVal.scvBool(val);
250
+ case 'undefined':
251
+ return _xdr["default"].ScVal.scvVoid();
252
+ case 'function':
253
+ // FIXME: Is this too helpful?
254
+ return nativeToScVal(val());
255
+ default:
256
+ throw new TypeError("failed to convert typeof ".concat(_typeof(val), " (").concat(val, ")"));
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Given a smart contract value, attempt to convert it to a native type.
262
+ * Possible conversions include:
263
+ *
264
+ * - void -> `null`
265
+ * - u32, i32 -> `number`
266
+ * - u64, i64, u128, i128, u256, i256 -> `bigint`
267
+ * - vec -> `Array` of any of the above (via recursion)
268
+ * - map -> key-value object of any of the above (via recursion)
269
+ * - bool -> `boolean`
270
+ * - bytes -> `Uint8Array`
271
+ * - symbol -> `string`
272
+ * - string -> `string` IF the underlying buffer can be decoded as ascii/utf8,
273
+ * `Uint8Array` of the raw contents in any error case
274
+ *
275
+ * If no viable conversion can be determined, this just "unwraps" the smart
276
+ * value to return its underlying XDR value.
277
+ *
278
+ * @param {xdr.ScVal} scv - the input smart contract value
279
+ *
280
+ * @returns {any}
281
+ * @see nativeToScVal
282
+ */
283
+ function scValToNative(scv) {
284
+ var _scv$vec, _scv$map;
285
+ // we use the verbose xdr.ScValType.<type>.value form here because it's faster
286
+ // than string comparisons and the underlying constants never need to be
287
+ // updated
288
+ switch (scv["switch"]().value) {
289
+ case _xdr["default"].ScValType.scvVoid().value:
290
+ return null;
291
+
292
+ // these can be converted to bigints directly
293
+ case _xdr["default"].ScValType.scvU64().value:
294
+ case _xdr["default"].ScValType.scvI64().value:
295
+ return scv.value().toBigInt();
296
+
297
+ // these can be parsed by internal abstractions note that this can also
298
+ // handle the above two cases, but it's not as efficient (another
299
+ // type-check, parsing, etc.)
300
+ case _xdr["default"].ScValType.scvU128().value:
301
+ case _xdr["default"].ScValType.scvI128().value:
302
+ case _xdr["default"].ScValType.scvU256().value:
303
+ case _xdr["default"].ScValType.scvI256().value:
304
+ return (0, _index.scValToBigInt)(scv);
305
+ case _xdr["default"].ScValType.scvVec().value:
306
+ return ((_scv$vec = scv.vec()) !== null && _scv$vec !== void 0 ? _scv$vec : []).map(scValToNative);
307
+ case _xdr["default"].ScValType.scvAddress().value:
308
+ return _address.Address.fromScVal(scv).toString();
309
+ case _xdr["default"].ScValType.scvMap().value:
310
+ return Object.fromEntries(((_scv$map = scv.map()) !== null && _scv$map !== void 0 ? _scv$map : []).map(function (entry) {
311
+ return [scValToNative(entry.key()), scValToNative(entry.val())];
312
+ }));
313
+
314
+ // these return the primitive type directly
315
+ case _xdr["default"].ScValType.scvBool().value:
316
+ case _xdr["default"].ScValType.scvU32().value:
317
+ case _xdr["default"].ScValType.scvI32().value:
318
+ case _xdr["default"].ScValType.scvBytes().value:
319
+ return scv.value();
320
+
321
+ // Symbols are limited to [a-zA-Z0-9_]+, so we can safely make ascii strings
322
+ //
323
+ // Strings, however, are "presented" as strings and we treat them as such
324
+ // (in other words, string = bytes with a hint that it's text). If the user
325
+ // encoded non-printable bytes in their string value, that's on them.
326
+ //
327
+ // Note that we assume a utf8 encoding (ascii-compatible). For other
328
+ // encodings, you should probably use bytes anyway. If it cannot be decoded,
329
+ // the raw bytes are returned.
330
+ case _xdr["default"].ScValType.scvSymbol().value:
331
+ case _xdr["default"].ScValType.scvString().value:
332
+ {
333
+ var v = scv.value(); // string|Buffer
334
+ if (Buffer.isBuffer(v) || ArrayBuffer.isView(v)) {
335
+ try {
336
+ return new TextDecoder().decode(v);
337
+ } catch (e) {
338
+ return new Uint8Array(v.buffer); // copy of bytes
339
+ }
340
+ }
341
+ return v; // string already
342
+ }
343
+
344
+ // these can be converted to bigint
345
+ case _xdr["default"].ScValType.scvTimepoint().value:
346
+ case _xdr["default"].ScValType.scvDuration().value:
347
+ return new _xdr["default"].Uint64(scv.value()).toBigInt();
348
+ case _xdr["default"].ScValType.scvStatus().value:
349
+ // TODO: Convert each status type into a human-readable error string?
350
+ switch (scv.value()["switch"]()) {
351
+ case _xdr["default"].ScStatusType.sstOk().value:
352
+ case _xdr["default"].ScStatusType.sstUnknownError().value:
353
+ case _xdr["default"].ScStatusType.sstHostValueError().value:
354
+ case _xdr["default"].ScStatusType.sstHostObjectError().value:
355
+ case _xdr["default"].ScStatusType.sstHostFunctionError().value:
356
+ case _xdr["default"].ScStatusType.sstHostStorageError().value:
357
+ case _xdr["default"].ScStatusType.sstHostContextError().value:
358
+ case _xdr["default"].ScStatusType.sstVmError().value:
359
+ case _xdr["default"].ScStatusType.sstContractError().value:
360
+ case _xdr["default"].ScStatusType.sstHostAuthError().value:
361
+ default:
362
+ break;
363
+ }
364
+
365
+ // in the fallthrough case, just return the underlying value directly
366
+ default:
367
+ return scv.value();
368
+ }
369
+ }