Source

js-stellar-base/src/contract.js

  1. import { Address } from './address';
  2. import { Operation } from './operation';
  3. import xdr from './xdr';
  4. import { StrKey } from './strkey';
  5. /**
  6. * Create a new Contract object.
  7. *
  8. * `Contract` represents a single contract in the Stellar network, embodying the
  9. * interface of the contract. See
  10. * [Contracts](https://soroban.stellar.org/docs/learn/interacting-with-contracts)
  11. * for more information about how contracts work in Stellar.
  12. *
  13. * @constructor
  14. *
  15. * @param {string} contractId - ID of the contract (ex.
  16. * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`).
  17. */
  18. export class Contract {
  19. constructor(contractId) {
  20. try {
  21. // First, try it as a strkey
  22. this._id = StrKey.decodeContract(contractId);
  23. } catch (_) {
  24. throw new Error(`Invalid contract ID: ${contractId}`);
  25. }
  26. }
  27. /**
  28. * Returns Stellar contract ID as a strkey, ex.
  29. * `CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE`.
  30. * @returns {string}
  31. */
  32. contractId() {
  33. return StrKey.encodeContract(this._id);
  34. }
  35. /** @returns {string} the ID as a strkey (C...) */
  36. toString() {
  37. return this.contractId();
  38. }
  39. /** @returns {Address} the wrapped address of this contract */
  40. address() {
  41. return Address.contract(this._id);
  42. }
  43. /**
  44. * Returns an operation that will invoke this contract call.
  45. *
  46. * @param {string} method name of the method to call
  47. * @param {...xdr.ScVal} params arguments to pass to the function call
  48. *
  49. * @returns {xdr.Operation} an InvokeHostFunctionOp operation to call the
  50. * contract with the given method and parameters
  51. *
  52. * @see Operation.invokeHostFunction
  53. * @see Operation.invokeContractFunction
  54. * @see Operation.createCustomContract
  55. * @see Operation.createStellarAssetContract
  56. * @see Operation.uploadContractWasm
  57. */
  58. call(method, ...params) {
  59. return Operation.invokeContractFunction({
  60. contract: this.address().toString(),
  61. function: method,
  62. args: params
  63. });
  64. }
  65. /**
  66. * Returns the read-only footprint entries necessary for any invocations to
  67. * this contract, for convenience when manually adding it to your
  68. * transaction's overall footprint or doing bump/restore operations.
  69. *
  70. * @returns {xdr.LedgerKey} the ledger key for the deployed contract instance
  71. */
  72. getFootprint() {
  73. return xdr.LedgerKey.contractData(
  74. new xdr.LedgerKeyContractData({
  75. contract: this.address().toScAddress(),
  76. key: xdr.ScVal.scvLedgerKeyContractInstance(),
  77. durability: xdr.ContractDataDurability.persistent()
  78. })
  79. );
  80. }
  81. }