@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
package/lib/auth.js ADDED
@@ -0,0 +1,253 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.authorizeEntry = authorizeEntry;
7
+ exports.authorizeInvocation = authorizeInvocation;
8
+ var _xdr = _interopRequireDefault(require("./xdr"));
9
+ var _keypair = require("./keypair");
10
+ var _strkey = require("./strkey");
11
+ var _network = require("./network");
12
+ var _hashing = require("./hashing");
13
+ var _address = require("./address");
14
+ var _scval = require("./scval");
15
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
16
+ 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); }
17
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
18
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
19
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
20
+ /**
21
+ * @async
22
+ * @callback SigningCallback A callback for signing an XDR structure
23
+ * representing all of the details necessary to authorize an invocation tree.
24
+ *
25
+ * @param {xdr.HashIdPreimage} preimage the entire authorization envelope
26
+ * whose hash you should sign, so that you can inspect the entire structure
27
+ * if necessary (rather than blindly signing a hash)
28
+ *
29
+ * @returns {Promise<Uint8Array>} the signature of the raw payload (which is
30
+ * the sha256 hash of the preimage bytes, so `hash(preimage.toXDR())`) signed
31
+ * by the key corresponding to the public key in the entry you pass to
32
+ * {@link authorizeEntry} (decipherable from its
33
+ * `credentials().address().address()`)
34
+ */
35
+ /**
36
+ * Actually authorizes an existing authorization entry using the given the
37
+ * credentials and expiration details, returning a signed copy.
38
+ *
39
+ * This "fills out" the authorization entry with a signature, indicating to the
40
+ * {@link Operation.invokeHostFunction} its attached to that:
41
+ * - a particular identity (i.e. signing {@link Keypair} or other signer)
42
+ * - approving the execution of an invocation tree (i.e. a simulation-acquired
43
+ * {@link xdr.SorobanAuthorizedInvocation} or otherwise built)
44
+ * - on a particular network (uniquely identified by its passphrase, see
45
+ * {@link Networks})
46
+ * - until a particular ledger sequence is reached.
47
+ *
48
+ * This one lets you pass a either a {@link Keypair} (or, more accurately,
49
+ * anything with a `sign(Buffer): Buffer` method) or a callback function (see
50
+ * {@link SigningCallback}) to handle signing the envelope hash.
51
+ *
52
+ * @param {xdr.SorobanAuthorizationEntry} entry an unsigned authorization entr
53
+ * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance
54
+ * or a function which takes a payload (a
55
+ * {@link xdr.HashIdPreimageSorobanAuthorization} instance) input and returns
56
+ * the signature of the hash of the raw payload bytes (where the signing key
57
+ * should correspond to the address in the `entry`)
58
+ * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence
59
+ * number until which this authorization entry should be valid (if
60
+ * `currentLedgerSeq==validUntil`, this is expired))
61
+ * @param {string} [networkPassphrase] the network passphrase is incorprated
62
+ * into the signature (see {@link Networks} for options)
63
+ *
64
+ * @returns {Promise<xdr.SorobanAuthorizationEntry>} a promise for an
65
+ * authorization entry that you can pass along to
66
+ * {@link Operation.invokeHostFunction}
67
+ *
68
+ * @see authorizeInvocation
69
+ * @example
70
+ * import { Server, Transaction, Networks, authorizeEntry } from 'soroban-client';
71
+ *
72
+ * // Assume signPayloadCallback is a well-formed signing callback.
73
+ * //
74
+ * // It might, for example, pop up a modal from a browser extension, send the
75
+ * // transaction to a third-party service for signing, or just do simple
76
+ * // signing via Keypair like it does here:
77
+ * function signPayloadCallback(payload) {
78
+ * return signer.sign(hash(payload.toXDR());
79
+ * }
80
+ *
81
+ * function multiPartyAuth(
82
+ * server: Server,
83
+ * // assume this involves multi-party auth
84
+ * tx: Transaction,
85
+ * ) {
86
+ * return server
87
+ * .simulateTransaction(tx)
88
+ * .then((simResult) => {
89
+ * tx.operations[0].auth.map(entry =>
90
+ * authorizeEntry(
91
+ * entry,
92
+ * signPayloadCallback,
93
+ * currentLedger + 1000,
94
+ * Networks.FUTURENET);
95
+ * ));
96
+ *
97
+ * return server.prepareTransaction(tx, Networks.FUTURENET, simResult);
98
+ * })
99
+ * .then((preppedTx) => {
100
+ * preppedTx.sign(source);
101
+ * return server.sendTransaction(preppedTx);
102
+ * });
103
+ * }
104
+ */
105
+ function authorizeEntry(_x, _x2, _x3) {
106
+ return _authorizeEntry.apply(this, arguments);
107
+ }
108
+ /**
109
+ * This builds an entry from scratch, allowing you to express authorization as a
110
+ * function of:
111
+ * - a particular identity (i.e. signing {@link Keypair} or other signer)
112
+ * - approving the execution of an invocation tree (i.e. a simulation-acquired
113
+ * {@link xdr.SorobanAuthorizedInvocation} or otherwise built)
114
+ * - on a particular network (uniquely identified by its passphrase, see
115
+ * {@link Networks})
116
+ * - until a particular ledger sequence is reached.
117
+ *
118
+ * This is in contrast to {@link authorizeEntry}, which signs an existing entry.
119
+ *
120
+ * @param {Keypair | SigningCallback} signer either a {@link Keypair} instance
121
+ * (or anything with a `.sign(buf): Buffer-like` method) or a function which
122
+ * takes a payload (a {@link xdr.HashIdPreimageSorobanAuthorization}
123
+ * instance) input and returns the signature of the hash of the raw payload
124
+ * bytes (where the signing key should correspond to the address in the
125
+ * `entry`)
126
+ * @param {number} validUntilLedgerSeq the (exclusive) future ledger sequence
127
+ * number until which this authorization entry should be valid (if
128
+ * `currentLedgerSeq==validUntilLedgerSeq`, this is expired))
129
+ * @param {xdr.SorobanAuthorizedInvocation} invocation the invocation tree that
130
+ * we're authorizing (likely, this comes from transaction simulation)
131
+ * @param {string} [publicKey] the public identity of the signer (when
132
+ * providing a {@link Keypair} to `signer`, this can be omitted, as it just
133
+ * uses {@link Keypair.publicKey})
134
+ * @param {string} [networkPassphrase] the network passphrase is incorprated
135
+ * into the signature (see {@link Networks} for options, default:
136
+ * {@link Networks.FUTURENET})
137
+ *
138
+ * @returns {Promise<xdr.SorobanAuthorizationEntry>} a promise for an
139
+ * authorization entry that you can pass along to
140
+ * {@link Operation.invokeHostFunction}
141
+ *
142
+ * @see authorizeEntry
143
+ */
144
+ function _authorizeEntry() {
145
+ _authorizeEntry = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(entry, signer, validUntilLedgerSeq) {
146
+ var networkPassphrase,
147
+ clone,
148
+ addrAuth,
149
+ networkId,
150
+ preimage,
151
+ payload,
152
+ signature,
153
+ publicKey,
154
+ sigScVal,
155
+ _args = arguments;
156
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
157
+ while (1) switch (_context.prev = _context.next) {
158
+ case 0:
159
+ networkPassphrase = _args.length > 3 && _args[3] !== undefined ? _args[3] : _network.Networks.FUTURENET;
160
+ if (!(entry.credentials()["switch"]().value !== _xdr["default"].SorobanCredentialsType.sorobanCredentialsAddress().value)) {
161
+ _context.next = 3;
162
+ break;
163
+ }
164
+ return _context.abrupt("return", entry);
165
+ case 3:
166
+ clone = _xdr["default"].SorobanAuthorizationEntry.fromXDR(entry.toXDR());
167
+ /** @type {xdr.SorobanAddressCredentials} */
168
+ addrAuth = clone.credentials().address();
169
+ addrAuth.signatureExpirationLedger(validUntilLedgerSeq);
170
+ networkId = (0, _hashing.hash)(Buffer.from(networkPassphrase));
171
+ preimage = _xdr["default"].HashIdPreimage.envelopeTypeSorobanAuthorization(new _xdr["default"].HashIdPreimageSorobanAuthorization({
172
+ networkId: networkId,
173
+ nonce: addrAuth.nonce(),
174
+ invocation: clone.rootInvocation(),
175
+ signatureExpirationLedger: addrAuth.signatureExpirationLedger()
176
+ }));
177
+ payload = (0, _hashing.hash)(preimage.toXDR());
178
+ if (!(typeof signer === 'function')) {
179
+ _context.next = 17;
180
+ break;
181
+ }
182
+ _context.t0 = Buffer;
183
+ _context.next = 13;
184
+ return signer(preimage);
185
+ case 13:
186
+ _context.t1 = _context.sent;
187
+ signature = _context.t0.from.call(_context.t0, _context.t1);
188
+ _context.next = 18;
189
+ break;
190
+ case 17:
191
+ signature = Buffer.from(signer.sign(payload));
192
+ case 18:
193
+ publicKey = _address.Address.fromScAddress(addrAuth.address()).toString();
194
+ if (_keypair.Keypair.fromPublicKey(publicKey).verify(payload, signature)) {
195
+ _context.next = 21;
196
+ break;
197
+ }
198
+ throw new Error("signature doesn't match payload");
199
+ case 21:
200
+ // This structure is defined here:
201
+ // https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#stellar-account-signatures
202
+ //
203
+ // Encoding a contract structure as an ScVal means the map keys are supposed
204
+ // to be symbols, hence the forced typing here.
205
+ sigScVal = (0, _scval.nativeToScVal)({
206
+ public_key: _strkey.StrKey.decodeEd25519PublicKey(publicKey),
207
+ signature: signature
208
+ }, {
209
+ type: {
210
+ public_key: ['symbol', null],
211
+ signature: ['symbol', null]
212
+ }
213
+ });
214
+ addrAuth.signature(_xdr["default"].ScVal.scvVec([sigScVal]));
215
+ return _context.abrupt("return", clone);
216
+ case 24:
217
+ case "end":
218
+ return _context.stop();
219
+ }
220
+ }, _callee);
221
+ }));
222
+ return _authorizeEntry.apply(this, arguments);
223
+ }
224
+ function authorizeInvocation(signer, validUntilLedgerSeq, invocation) {
225
+ var publicKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
226
+ var networkPassphrase = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _network.Networks.FUTURENET;
227
+ // We use keypairs as a source of randomness for the nonce to avoid mucking
228
+ // with any crypto dependencies. Note that this just has to be random and
229
+ // unique, not cryptographically secure, so it's fine.
230
+ var kp = _keypair.Keypair.random().rawPublicKey();
231
+ var nonce = new _xdr["default"].Int64(bytesToInt64(kp));
232
+ var pk = publicKey || signer.publicKey();
233
+ if (!pk) {
234
+ throw new Error("authorizeInvocation requires publicKey parameter");
235
+ }
236
+ var entry = new _xdr["default"].SorobanAuthorizationEntry({
237
+ rootInvocation: invocation,
238
+ credentials: _xdr["default"].SorobanCredentials.sorobanCredentialsAddress(new _xdr["default"].SorobanAddressCredentials({
239
+ address: new _address.Address(pk).toScAddress(),
240
+ nonce: nonce,
241
+ signatureExpirationLedger: 0,
242
+ // replaced
243
+ signature: _xdr["default"].ScVal.scvVec([]) // replaced
244
+ }))
245
+ });
246
+ return authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphrase);
247
+ }
248
+ function bytesToInt64(bytes) {
249
+ // eslint-disable-next-line no-bitwise
250
+ return bytes.subarray(0, 8).reduce(function (accum, b) {
251
+ return accum << 8 | b;
252
+ }, 0);
253
+ }
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.Claimant = void 0;
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
+ 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); }
12
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
13
+ 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); } }
14
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
15
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
16
+ 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); }
17
+ /**
18
+ * Claimant class represents an xdr.Claimant
19
+ *
20
+ * The claim predicate is optional, it defaults to unconditional if none is specified.
21
+ *
22
+ * @constructor
23
+ * @param {string} destination - The destination account ID.
24
+ * @param {xdr.ClaimPredicate} [predicate] - The claim predicate.
25
+ */
26
+ var Claimant = exports.Claimant = /*#__PURE__*/function () {
27
+ function Claimant(destination, predicate) {
28
+ _classCallCheck(this, Claimant);
29
+ if (destination && !_strkey.StrKey.isValidEd25519PublicKey(destination)) {
30
+ throw new Error('Destination is invalid');
31
+ }
32
+ this._destination = destination;
33
+ if (!predicate) {
34
+ this._predicate = _xdr["default"].ClaimPredicate.claimPredicateUnconditional();
35
+ } else if (predicate instanceof _xdr["default"].ClaimPredicate) {
36
+ this._predicate = predicate;
37
+ } else {
38
+ throw new Error('Predicate should be an xdr.ClaimPredicate');
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Returns an unconditional claim predicate
44
+ * @Return {xdr.ClaimPredicate}
45
+ */
46
+ _createClass(Claimant, [{
47
+ key: "toXDRObject",
48
+ value:
49
+ /**
50
+ * Returns the xdr object for this claimant.
51
+ * @returns {xdr.Claimant} XDR Claimant object
52
+ */
53
+ function toXDRObject() {
54
+ var claimant = new _xdr["default"].ClaimantV0({
55
+ destination: _keypair.Keypair.fromPublicKey(this._destination).xdrAccountId(),
56
+ predicate: this._predicate
57
+ });
58
+ return _xdr["default"].Claimant.claimantTypeV0(claimant);
59
+ }
60
+
61
+ /**
62
+ * @type {string}
63
+ * @readonly
64
+ */
65
+ }, {
66
+ key: "destination",
67
+ get: function get() {
68
+ return this._destination;
69
+ },
70
+ set: function set(value) {
71
+ throw new Error('Claimant is immutable');
72
+ }
73
+
74
+ /**
75
+ * @type {xdr.ClaimPredicate}
76
+ * @readonly
77
+ */
78
+ }, {
79
+ key: "predicate",
80
+ get: function get() {
81
+ return this._predicate;
82
+ },
83
+ set: function set(value) {
84
+ throw new Error('Claimant is immutable');
85
+ }
86
+ }], [{
87
+ key: "predicateUnconditional",
88
+ value: function predicateUnconditional() {
89
+ return _xdr["default"].ClaimPredicate.claimPredicateUnconditional();
90
+ }
91
+
92
+ /**
93
+ * Returns an `and` claim predicate
94
+ * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate
95
+ * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate
96
+ * @Return {xdr.ClaimPredicate}
97
+ */
98
+ }, {
99
+ key: "predicateAnd",
100
+ value: function predicateAnd(left, right) {
101
+ if (!(left instanceof _xdr["default"].ClaimPredicate)) {
102
+ throw new Error('left Predicate should be an xdr.ClaimPredicate');
103
+ }
104
+ if (!(right instanceof _xdr["default"].ClaimPredicate)) {
105
+ throw new Error('right Predicate should be an xdr.ClaimPredicate');
106
+ }
107
+ return _xdr["default"].ClaimPredicate.claimPredicateAnd([left, right]);
108
+ }
109
+
110
+ /**
111
+ * Returns an `or` claim predicate
112
+ * @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate
113
+ * @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate
114
+ * @Return {xdr.ClaimPredicate}
115
+ */
116
+ }, {
117
+ key: "predicateOr",
118
+ value: function predicateOr(left, right) {
119
+ if (!(left instanceof _xdr["default"].ClaimPredicate)) {
120
+ throw new Error('left Predicate should be an xdr.ClaimPredicate');
121
+ }
122
+ if (!(right instanceof _xdr["default"].ClaimPredicate)) {
123
+ throw new Error('right Predicate should be an xdr.ClaimPredicate');
124
+ }
125
+ return _xdr["default"].ClaimPredicate.claimPredicateOr([left, right]);
126
+ }
127
+
128
+ /**
129
+ * Returns a `not` claim predicate
130
+ * @param {xdr.ClaimPredicate} predicate an xdr.ClaimPredicate
131
+ * @Return {xdr.ClaimPredicate}
132
+ */
133
+ }, {
134
+ key: "predicateNot",
135
+ value: function predicateNot(predicate) {
136
+ if (!(predicate instanceof _xdr["default"].ClaimPredicate)) {
137
+ throw new Error('right Predicate should be an xdr.ClaimPredicate');
138
+ }
139
+ return _xdr["default"].ClaimPredicate.claimPredicateNot(predicate);
140
+ }
141
+
142
+ /**
143
+ * Returns a `BeforeAbsoluteTime` claim predicate
144
+ *
145
+ * This predicate will be fulfilled if the closing time of the ledger that
146
+ * includes the CreateClaimableBalance operation is less than this (absolute)
147
+ * Unix timestamp (expressed in seconds).
148
+ *
149
+ * @param {string} absBefore Unix epoch (in seconds) as a string
150
+ * @Return {xdr.ClaimPredicate}
151
+ */
152
+ }, {
153
+ key: "predicateBeforeAbsoluteTime",
154
+ value: function predicateBeforeAbsoluteTime(absBefore) {
155
+ return _xdr["default"].ClaimPredicate.claimPredicateBeforeAbsoluteTime(_xdr["default"].Int64.fromString(absBefore));
156
+ }
157
+
158
+ /**
159
+ * Returns a `BeforeRelativeTime` claim predicate
160
+ *
161
+ * This predicate will be fulfilled if the closing time of the ledger that
162
+ * includes the CreateClaimableBalance operation plus this relative time delta
163
+ * (in seconds) is less than the current time.
164
+ *
165
+ * @param {strings} seconds seconds since closeTime of the ledger in which the ClaimableBalanceEntry was created (as string)
166
+ * @Return {xdr.ClaimPredicate}
167
+ */
168
+ }, {
169
+ key: "predicateBeforeRelativeTime",
170
+ value: function predicateBeforeRelativeTime(seconds) {
171
+ return _xdr["default"].ClaimPredicate.claimPredicateBeforeRelativeTime(_xdr["default"].Int64.fromString(seconds));
172
+ }
173
+
174
+ /**
175
+ * Returns a claimant object from its XDR object representation.
176
+ * @param {xdr.Claimant} claimantXdr - The claimant xdr object.
177
+ * @returns {Claimant}
178
+ */
179
+ }, {
180
+ key: "fromXDR",
181
+ value: function fromXDR(claimantXdr) {
182
+ var value;
183
+ switch (claimantXdr["switch"]()) {
184
+ case _xdr["default"].ClaimantType.claimantTypeV0():
185
+ value = claimantXdr.v0();
186
+ return new this(_strkey.StrKey.encodeEd25519PublicKey(value.destination().ed25519()), value.predicate());
187
+ default:
188
+ throw new Error("Invalid claimant type: ".concat(claimantXdr["switch"]().name));
189
+ }
190
+ }
191
+ }]);
192
+ return Claimant;
193
+ }();
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.Contract = void 0;
7
+ var _address = require("./address");
8
+ var _operation = require("./operation");
9
+ var _xdr = _interopRequireDefault(require("./xdr"));
10
+ var _strkey = require("./strkey");
11
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
12
+ 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); }
13
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
14
+ 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); } }
15
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
16
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
17
+ 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); }
18
+ /**
19
+ * Create a new Contract object.
20
+ *
21
+ * `Contract` represents a single contract in the Stellar network, embodying the
22
+ * interface of the contract. See
23
+ * [Contracts](https://soroban.stellar.org/docs/learn/interacting-with-contracts)
24
+ * for more information about how contracts work in Stellar.
25
+ *
26
+ * @constructor
27
+ *
28
+ * @param {string} contractId - ID of the contract (ex.
29
+ * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`).
30
+ */
31
+ var Contract = exports.Contract = /*#__PURE__*/function () {
32
+ function Contract(contractId) {
33
+ _classCallCheck(this, Contract);
34
+ try {
35
+ // First, try it as a strkey
36
+ this._id = _strkey.StrKey.decodeContract(contractId);
37
+ } catch (_) {
38
+ throw new Error("Invalid contract ID: ".concat(contractId));
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Returns Stellar contract ID as a strkey, ex.
44
+ * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`.
45
+ * @returns {string}
46
+ */
47
+ _createClass(Contract, [{
48
+ key: "contractId",
49
+ value: function contractId() {
50
+ return _strkey.StrKey.encodeContract(this._id);
51
+ }
52
+
53
+ /** @returns {string} the ID as a strkey (C...) */
54
+ }, {
55
+ key: "toString",
56
+ value: function toString() {
57
+ return this.contractId();
58
+ }
59
+
60
+ /** @returns {Address} the wrapped address of this contract */
61
+ }, {
62
+ key: "address",
63
+ value: function address() {
64
+ return _address.Address.contract(this._id);
65
+ }
66
+
67
+ /**
68
+ * Returns an operation that will invoke this contract call.
69
+ *
70
+ * @param {string} method name of the method to call
71
+ * @param {...xdr.ScVal} params arguments to pass to the function call
72
+ *
73
+ * @returns {xdr.Operation} an InvokeHostFunctionOp operation to call the
74
+ * contract with the given method and parameters
75
+ *
76
+ * @see Operation.invokeHostFunction
77
+ * @see Operation.invokeContractFunction
78
+ * @see Operation.createCustomContract
79
+ * @see Operation.createStellarAssetContract
80
+ * @see Operation.uploadContractWasm
81
+ */
82
+ }, {
83
+ key: "call",
84
+ value: function call(method) {
85
+ for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
86
+ params[_key - 1] = arguments[_key];
87
+ }
88
+ return _operation.Operation.invokeContractFunction({
89
+ contract: this.address().toString(),
90
+ "function": method,
91
+ args: params
92
+ });
93
+ }
94
+
95
+ /**
96
+ * Returns the read-only footprint entries necessary for any invocations to
97
+ * this contract, for convenience when manually adding it to your
98
+ * transaction's overall footprint or doing bump/restore operations.
99
+ *
100
+ * @returns {xdr.LedgerKey} the ledger key for the deployed contract instance
101
+ */
102
+ }, {
103
+ key: "getFootprint",
104
+ value: function getFootprint() {
105
+ return _xdr["default"].LedgerKey.contractData(new _xdr["default"].LedgerKeyContractData({
106
+ contract: this.address().toScAddress(),
107
+ key: _xdr["default"].ScVal.scvLedgerKeyContractInstance(),
108
+ durability: _xdr["default"].ContractDataDurability.persistent()
109
+ }));
110
+ }
111
+ }]);
112
+ return Contract;
113
+ }();
package/lib/events.js ADDED
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.humanizeEvents = humanizeEvents;
7
+ var _xdr = _interopRequireDefault(require("./xdr"));
8
+ var _strkey = require("./strkey");
9
+ var _scval = require("./scval");
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
11
+ /**
12
+ * Converts raw diagnostic or contract events into something with a flatter,
13
+ * human-readable, and understandable structure.
14
+ *
15
+ * @param {xdr.DiagnosticEvent[] | xdr.ContractEvent[]} events either contract
16
+ * events or diagnostic events to parse into a friendly format
17
+ *
18
+ * @returns {SorobanEvent[]} a list of human-readable event structures, where
19
+ * each element has the following properties:
20
+ * - type: a string of one of 'system', 'contract', 'diagnostic
21
+ * - contractId?: optionally, a `C...` encoded strkey
22
+ * - topics: a list of {@link scValToNative} invocations on the topics
23
+ * - data: similarly, a {@link scValToNative} invocation on the raw event data
24
+ */
25
+ function humanizeEvents(events) {
26
+ return events.map(function (e) {
27
+ if (e instanceof _xdr["default"].DiagnosticEvent) {
28
+ return extractEvent(e.event());
29
+ }
30
+ return extractEvent(e);
31
+ });
32
+ }
33
+ function extractEvent(event) {
34
+ return {
35
+ contractId: event.contractId() === null ? '' : _strkey.StrKey.encodeContract(event.contractId()),
36
+ type: event.type().name,
37
+ topics: event.body().value().topics().map(function (t) {
38
+ return (0, _scval.scValToNative)(t);
39
+ }),
40
+ data: (0, _scval.scValToNative)(event.body().value().data())
41
+ };
42
+ }