@0xpolygonid/js-sdk 1.11.1 → 1.13.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.
@@ -576,7 +576,7 @@ var PolygonIdSdk = (function (exports) {
576
576
 
577
577
  var commonjsGlobal$1 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
578
578
 
579
- function getDefaultExportFromCjs$1 (x) {
579
+ function getDefaultExportFromCjs (x) {
580
580
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
581
581
  }
582
582
 
@@ -1701,7 +1701,7 @@ var PolygonIdSdk = (function (exports) {
1701
1701
  } (pubsub, pubsub.exports));
1702
1702
 
1703
1703
  var pubsubExports = pubsub.exports;
1704
- var PubSub = /*@__PURE__*/getDefaultExportFromCjs$1(pubsubExports);
1704
+ var PubSub = /*@__PURE__*/getDefaultExportFromCjs(pubsubExports);
1705
1705
 
1706
1706
  const SDK_EVENTS = {
1707
1707
  TX_RECEIPT_ACCEPTED: 'TX_RECEIPT_ACCEPTED'
@@ -7496,6 +7496,33 @@ var PolygonIdSdk = (function (exports) {
7496
7496
  (function (RefreshServiceType) {
7497
7497
  RefreshServiceType["Iden3RefreshService2023"] = "Iden3RefreshService2023";
7498
7498
  })(exports.RefreshServiceType || (exports.RefreshServiceType = {}));
7499
+ /**
7500
+ * PaymentRequestType type for payment requests
7501
+ *
7502
+ * @enum {string}
7503
+ */
7504
+ exports.PaymentRequestType = void 0;
7505
+ (function (PaymentRequestType) {
7506
+ PaymentRequestType["PaymentRequest"] = "PaymentRequest";
7507
+ })(exports.PaymentRequestType || (exports.PaymentRequestType = {}));
7508
+ /**
7509
+ * PaymentRequestDataType type for payment requests
7510
+ *
7511
+ * @enum {string}
7512
+ */
7513
+ exports.PaymentRequestDataType = void 0;
7514
+ (function (PaymentRequestDataType) {
7515
+ PaymentRequestDataType["Iden3PaymentRequestCryptoV1"] = "Iden3PaymentRequestCryptoV1";
7516
+ })(exports.PaymentRequestDataType || (exports.PaymentRequestDataType = {}));
7517
+ /**
7518
+ * PaymentType type for payment responses
7519
+ *
7520
+ * @enum {string}
7521
+ */
7522
+ exports.PaymentType = void 0;
7523
+ (function (PaymentType) {
7524
+ PaymentType["Iden3PaymentCryptoV1"] = "Iden3PaymentCryptoV1";
7525
+ })(exports.PaymentType || (exports.PaymentType = {}));
7499
7526
 
7500
7527
  /**
7501
7528
  * Iden3SparseMerkleProof is a iden3 protocol merkle tree proof
@@ -28082,7 +28109,7 @@ var PolygonIdSdk = (function (exports) {
28082
28109
  } (ajv, ajv.exports));
28083
28110
 
28084
28111
  var ajvExports = ajv.exports;
28085
- var Ajv = /*@__PURE__*/getDefaultExportFromCjs$1(ajvExports);
28112
+ var Ajv = /*@__PURE__*/getDefaultExportFromCjs(ajvExports);
28086
28113
 
28087
28114
  var _2020 = {exports: {}};
28088
28115
 
@@ -29011,7 +29038,7 @@ var PolygonIdSdk = (function (exports) {
29011
29038
  } (_2020, _2020.exports));
29012
29039
 
29013
29040
  var _2020Exports = _2020.exports;
29014
- var Ajv2020 = /*@__PURE__*/getDefaultExportFromCjs$1(_2020Exports);
29041
+ var Ajv2020 = /*@__PURE__*/getDefaultExportFromCjs(_2020Exports);
29015
29042
 
29016
29043
  var _2019 = {exports: {}};
29017
29044
 
@@ -29590,7 +29617,7 @@ var PolygonIdSdk = (function (exports) {
29590
29617
  } (_2019, _2019.exports));
29591
29618
 
29592
29619
  var _2019Exports = _2019.exports;
29593
- var Ajv2019 = /*@__PURE__*/getDefaultExportFromCjs$1(_2019Exports);
29620
+ var Ajv2019 = /*@__PURE__*/getDefaultExportFromCjs(_2019Exports);
29594
29621
 
29595
29622
  var dist = {exports: {}};
29596
29623
 
@@ -29883,7 +29910,7 @@ var PolygonIdSdk = (function (exports) {
29883
29910
  } (dist, dist.exports));
29884
29911
 
29885
29912
  var distExports = dist.exports;
29886
- var addFormats = /*@__PURE__*/getDefaultExportFromCjs$1(distExports);
29913
+ var addFormats = /*@__PURE__*/getDefaultExportFromCjs(distExports);
29887
29914
 
29888
29915
  // or ESM/TypeScript import
29889
29916
  const defaultOpts = { verbose: true, strict: false };
@@ -53622,7 +53649,11 @@ var PolygonIdSdk = (function (exports) {
53622
53649
  // ProposalRequestMessageType is type for proposal-request message
53623
53650
  PROPOSAL_REQUEST_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/0.1/proposal-request',
53624
53651
  // ProposalMessageType is type for proposal message
53625
- PROPOSAL_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/0.1/proposal'
53652
+ PROPOSAL_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/0.1/proposal',
53653
+ // PaymentRequestMessageType is type for payment-request message
53654
+ PAYMENT_REQUEST_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/0.1/payment-request',
53655
+ // PaymentMessageType is type for payment message
53656
+ PAYMENT_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/0.1/payment'
53626
53657
  });
53627
53658
  /**
53628
53659
  * Media types for iden3 comm communication protocol
@@ -55725,10 +55756,6 @@ var PolygonIdSdk = (function (exports) {
55725
55756
  }
55726
55757
  }
55727
55758
 
55728
- function getDefaultExportFromCjs (x) {
55729
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
55730
- }
55731
-
55732
55759
  var utils$6 = {};
55733
55760
 
55734
55761
  /*
@@ -68614,26 +68641,6 @@ var PolygonIdSdk = (function (exports) {
68614
68641
  return runTask;
68615
68642
  }
68616
68643
 
68617
- /**
68618
- * Copyright 2020 Google LLC
68619
- *
68620
- * Licensed under the Apache License, Version 2.0 (the "License");
68621
- * you may not use this file except in compliance with the License.
68622
- * You may obtain a copy of the License at
68623
- *
68624
- * http://www.apache.org/licenses/LICENSE-2.0
68625
- *
68626
- * Unless required by applicable law or agreed to in writing, software
68627
- * distributed under the License is distributed on an "AS IS" BASIS,
68628
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
68629
- * See the License for the specific language governing permissions and
68630
- * limitations under the License.
68631
- */
68632
-
68633
- var browser$1 = Worker;
68634
-
68635
- var Worker$1 = /*@__PURE__*/getDefaultExportFromCjs(browser$1);
68636
-
68637
68644
  /*
68638
68645
  Copyright 2019 0KIMS association.
68639
68646
 
@@ -68669,15 +68676,19 @@ var PolygonIdSdk = (function (exports) {
68669
68676
  return new Promise(resolve => setTimeout(resolve, ms));
68670
68677
  }
68671
68678
 
68672
- function stringToBase64(str) {
68673
- {
68674
- return globalThis.btoa(str);
68679
+ let workerSource;
68680
+
68681
+ const threadStr = `(${"function thread(self) {\n const MAXMEM = 32767;\n let instance;\n let memory;\n\n if (self) {\n self.onmessage = function(e) {\n let data;\n if (e.data) {\n data = e.data;\n } else {\n data = e;\n }\n\n if (data[0].cmd == \"INIT\") {\n init(data[0]).then(function() {\n self.postMessage(data.result);\n });\n } else if (data[0].cmd == \"TERMINATE\") {\n self.close();\n } else {\n const res = runTask(data);\n self.postMessage(res);\n }\n };\n }\n\n async function init(data) {\n const code = new Uint8Array(data.code);\n const wasmModule = await WebAssembly.compile(code);\n memory = new WebAssembly.Memory({initial:data.init, maximum: MAXMEM});\n\n instance = await WebAssembly.instantiate(wasmModule, {\n env: {\n \"memory\": memory\n }\n });\n }\n\n\n\n function alloc(length) {\n const u32 = new Uint32Array(memory.buffer, 0, 1);\n while (u32[0] & 3) u32[0]++; // Return always aligned pointers\n const res = u32[0];\n u32[0] += length;\n if (u32[0] + length > memory.buffer.byteLength) {\n const currentPages = memory.buffer.byteLength / 0x10000;\n let requiredPages = Math.floor((u32[0] + length) / 0x10000)+1;\n if (requiredPages>MAXMEM) requiredPages=MAXMEM;\n memory.grow(requiredPages-currentPages);\n }\n return res;\n }\n\n function allocBuffer(buffer) {\n const p = alloc(buffer.byteLength);\n setBuffer(p, buffer);\n return p;\n }\n\n function getBuffer(pointer, length) {\n const u8 = new Uint8Array(memory.buffer);\n return new Uint8Array(u8.buffer, u8.byteOffset + pointer, length);\n }\n\n function setBuffer(pointer, buffer) {\n const u8 = new Uint8Array(memory.buffer);\n u8.set(new Uint8Array(buffer), pointer);\n }\n\n function runTask(task) {\n if (task[0].cmd == \"INIT\") {\n return init(task[0]);\n }\n const ctx = {\n vars: [],\n out: []\n };\n const u32a = new Uint32Array(memory.buffer, 0, 1);\n const oldAlloc = u32a[0];\n for (let i=0; i<task.length; i++) {\n switch (task[i].cmd) {\n case \"ALLOCSET\":\n ctx.vars[task[i].var] = allocBuffer(task[i].buff);\n break;\n case \"ALLOC\":\n ctx.vars[task[i].var] = alloc(task[i].len);\n break;\n case \"SET\":\n setBuffer(ctx.vars[task[i].var], task[i].buff);\n break;\n case \"CALL\": {\n const params = [];\n for (let j=0; j<task[i].params.length; j++) {\n const p = task[i].params[j];\n if (typeof p.var !== \"undefined\") {\n params.push(ctx.vars[p.var] + (p.offset || 0));\n } else if (typeof p.val != \"undefined\") {\n params.push(p.val);\n }\n }\n instance.exports[task[i].fnName](...params);\n break;\n }\n case \"GET\":\n ctx.out[task[i].out] = getBuffer(ctx.vars[task[i].var], task[i].len).slice();\n break;\n default:\n throw new Error(\"Invalid cmd\");\n }\n }\n const u32b = new Uint32Array(memory.buffer, 0, 1);\n u32b[0] = oldAlloc;\n return ctx.out;\n }\n\n\n return runTask;\n}"})(self)`;
68682
+ {
68683
+ if(globalThis?.Blob) {
68684
+ const threadBytes= new TextEncoder().encode(threadStr);
68685
+ const workerBlob = new Blob([threadBytes], { type: "application/javascript" }) ;
68686
+ workerSource = URL.createObjectURL(workerBlob);
68687
+ } else {
68688
+ workerSource = "data:application/javascript;base64," + globalThis.btoa(threadStr);
68675
68689
  }
68676
68690
  }
68677
68691
 
68678
- const threadSource = stringToBase64("(" + "function thread(self) {\n const MAXMEM = 32767;\n let instance;\n let memory;\n\n if (self) {\n self.onmessage = function(e) {\n let data;\n if (e.data) {\n data = e.data;\n } else {\n data = e;\n }\n\n if (data[0].cmd == \"INIT\") {\n init(data[0]).then(function() {\n self.postMessage(data.result);\n });\n } else if (data[0].cmd == \"TERMINATE\") {\n self.close();\n } else {\n const res = runTask(data);\n self.postMessage(res);\n }\n };\n }\n\n async function init(data) {\n const code = new Uint8Array(data.code);\n const wasmModule = await WebAssembly.compile(code);\n memory = new WebAssembly.Memory({initial:data.init, maximum: MAXMEM});\n\n instance = await WebAssembly.instantiate(wasmModule, {\n env: {\n \"memory\": memory\n }\n });\n }\n\n\n\n function alloc(length) {\n const u32 = new Uint32Array(memory.buffer, 0, 1);\n while (u32[0] & 3) u32[0]++; // Return always aligned pointers\n const res = u32[0];\n u32[0] += length;\n if (u32[0] + length > memory.buffer.byteLength) {\n const currentPages = memory.buffer.byteLength / 0x10000;\n let requiredPages = Math.floor((u32[0] + length) / 0x10000)+1;\n if (requiredPages>MAXMEM) requiredPages=MAXMEM;\n memory.grow(requiredPages-currentPages);\n }\n return res;\n }\n\n function allocBuffer(buffer) {\n const p = alloc(buffer.byteLength);\n setBuffer(p, buffer);\n return p;\n }\n\n function getBuffer(pointer, length) {\n const u8 = new Uint8Array(memory.buffer);\n return new Uint8Array(u8.buffer, u8.byteOffset + pointer, length);\n }\n\n function setBuffer(pointer, buffer) {\n const u8 = new Uint8Array(memory.buffer);\n u8.set(new Uint8Array(buffer), pointer);\n }\n\n function runTask(task) {\n if (task[0].cmd == \"INIT\") {\n return init(task[0]);\n }\n const ctx = {\n vars: [],\n out: []\n };\n const u32a = new Uint32Array(memory.buffer, 0, 1);\n const oldAlloc = u32a[0];\n for (let i=0; i<task.length; i++) {\n switch (task[i].cmd) {\n case \"ALLOCSET\":\n ctx.vars[task[i].var] = allocBuffer(task[i].buff);\n break;\n case \"ALLOC\":\n ctx.vars[task[i].var] = alloc(task[i].len);\n break;\n case \"SET\":\n setBuffer(ctx.vars[task[i].var], task[i].buff);\n break;\n case \"CALL\": {\n const params = [];\n for (let j=0; j<task[i].params.length; j++) {\n const p = task[i].params[j];\n if (typeof p.var !== \"undefined\") {\n params.push(ctx.vars[p.var] + (p.offset || 0));\n } else if (typeof p.val != \"undefined\") {\n params.push(p.val);\n }\n }\n instance.exports[task[i].fnName](...params);\n break;\n }\n case \"GET\":\n ctx.out[task[i].out] = getBuffer(ctx.vars[task[i].var], task[i].len).slice();\n break;\n default:\n throw new Error(\"Invalid cmd\");\n }\n }\n const u32b = new Uint32Array(memory.buffer, 0, 1);\n u32b[0] = oldAlloc;\n return ctx.out;\n }\n\n\n return runTask;\n}" + ")(self)");
68679
- const workerSource = "data:application/javascript;base64," + threadSource;
68680
-
68681
68692
 
68682
68693
 
68683
68694
  async function buildThreadManager(wasm, singleThread) {
@@ -68694,7 +68705,11 @@ var PolygonIdSdk = (function (exports) {
68694
68705
  "memory": tm.memory
68695
68706
  }
68696
68707
  });
68697
-
68708
+
68709
+ if(!globalThis?.Worker) {
68710
+ singleThread = true;
68711
+ }
68712
+
68698
68713
  tm.singleThread = singleThread;
68699
68714
  tm.initalPFree = tm.u32[0]; // Save the Pointer to free space.
68700
68715
  tm.pq = wasm.pq;
@@ -68708,7 +68723,6 @@ var PolygonIdSdk = (function (exports) {
68708
68723
  // tm.pTmp0 = tm.alloc(curve.G2.F.n8*3);
68709
68724
  // tm.pTmp1 = tm.alloc(curve.G2.F.n8*3);
68710
68725
 
68711
-
68712
68726
  if (singleThread) {
68713
68727
  tm.code = wasm.code;
68714
68728
  tm.taskManager = thread();
@@ -68725,9 +68739,9 @@ var PolygonIdSdk = (function (exports) {
68725
68739
 
68726
68740
  let concurrency = 2;
68727
68741
  {
68728
- if (typeof navigator === "object" && navigator.hardwareConcurrency) {
68729
- concurrency = navigator.hardwareConcurrency;
68730
- }
68742
+ if (typeof navigator === "object" && navigator.hardwareConcurrency) {
68743
+ concurrency = navigator.hardwareConcurrency;
68744
+ }
68731
68745
  }
68732
68746
 
68733
68747
  if(concurrency == 0){
@@ -68740,7 +68754,7 @@ var PolygonIdSdk = (function (exports) {
68740
68754
 
68741
68755
  for (let i = 0; i<concurrency; i++) {
68742
68756
 
68743
- tm.workers[i] = new Worker$1(workerSource);
68757
+ tm.workers[i] = new Worker(workerSource);
68744
68758
 
68745
68759
  tm.workers[i].addEventListener("message", getOnMsg(i));
68746
68760
 
@@ -73886,6 +73900,13 @@ var PolygonIdSdk = (function (exports) {
73886
73900
  }
73887
73901
  }
73888
73902
 
73903
+ // Ref https://github.com/iden3/circom/commit/ec6388cf6eb62463539cb4c40cc3ceae9826de19
73904
+ function normalize(n, prime) {
73905
+ let res = BigInt(n) % prime;
73906
+ if (res < 0) res += prime;
73907
+ return res
73908
+ }
73909
+
73889
73910
  function fnvHash(str) {
73890
73911
  const uint64_max = BigInt(2) ** BigInt(64);
73891
73912
  let hash = BigInt("0xCBF29CE484222325");
@@ -74295,7 +74316,7 @@ var PolygonIdSdk = (function (exports) {
74295
74316
  this.n32 = this.instance.exports.getFieldNumLen32();
74296
74317
 
74297
74318
  this.instance.exports.getRawPrime();
74298
- const arr = new Array(this.n32);
74319
+ const arr = new Uint32Array(this.n32);
74299
74320
  for (let i=0; i<this.n32; i++) {
74300
74321
  arr[this.n32-1-i] = this.instance.exports.readSharedRWMemory(i);
74301
74322
  }
@@ -74320,18 +74341,32 @@ var PolygonIdSdk = (function (exports) {
74320
74341
  const hMSB = parseInt(h.slice(0,8), 16);
74321
74342
  const hLSB = parseInt(h.slice(8,16), 16);
74322
74343
  const fArr = flatArray(input[k]);
74344
+ // Slight deviation from https://github.com/iden3/circom/blob/v2.1.6/code_producers/src/wasm_elements/common/witness_calculator.js
74345
+ // because I don't know when this exported function was added
74346
+ if (typeof this.instance.exports.getInputSignalSize === 'function') {
74347
+ let signalSize = this.instance.exports.getInputSignalSize(hMSB, hLSB);
74348
+ if (signalSize < 0){
74349
+ throw new Error(`Signal ${k} not found\n`);
74350
+ }
74351
+ if (fArr.length < signalSize) {
74352
+ throw new Error(`Not enough values for input signal ${k}\n`);
74353
+ }
74354
+ if (fArr.length > signalSize) {
74355
+ throw new Error(`Too many values for input signal ${k}\n`);
74356
+ }
74357
+ }
74323
74358
  for (let i=0; i<fArr.length; i++) {
74324
- const arrFr = toArray32(fArr[i],this.n32);
74325
- for (let j=0; j<this.n32; j++) {
74326
- this.instance.exports.writeSharedRWMemory(j,arrFr[this.n32-1-j]);
74327
- }
74328
- try {
74359
+ const arrFr = toArray32(normalize(fArr[i],this.prime),this.n32);
74360
+ for (let j=0; j<this.n32; j++) {
74361
+ this.instance.exports.writeSharedRWMemory(j,arrFr[this.n32-1-j]);
74362
+ }
74363
+ try {
74329
74364
  this.instance.exports.setInputSignal(hMSB, hLSB,i);
74330
- input_counter++;
74331
- } catch (err) {
74332
- // console.log(`After adding signal ${i} of ${k}`)
74365
+ input_counter++;
74366
+ } catch (err) {
74367
+ // console.log(`After adding signal ${i} of ${k}`)
74333
74368
  throw new Error(err);
74334
- }
74369
+ }
74335
74370
  }
74336
74371
 
74337
74372
  });
@@ -79042,6 +79077,202 @@ var PolygonIdSdk = (function (exports) {
79042
79077
  }
79043
79078
  }
79044
79079
 
79080
+ /**
79081
+ * @beta
79082
+ * createPaymentRequest is a function to create protocol payment-request message
79083
+ * @param {DID} sender - sender did
79084
+ * @param {DID} receiver - receiver did
79085
+ * @param {string} agent - agent URL
79086
+ * @param {PaymentRequestInfo[]} payments - payments
79087
+ * @returns `PaymentRequestMessage`
79088
+ */
79089
+ function createPaymentRequest(sender, receiver, agent, payments) {
79090
+ const uuidv4 = v4();
79091
+ const request = {
79092
+ id: uuidv4,
79093
+ thid: uuidv4,
79094
+ from: sender.string(),
79095
+ to: receiver.string(),
79096
+ typ: MediaType.PlainMessage,
79097
+ type: PROTOCOL_MESSAGE_TYPE.PAYMENT_REQUEST_MESSAGE_TYPE,
79098
+ body: {
79099
+ agent,
79100
+ payments
79101
+ }
79102
+ };
79103
+ return request;
79104
+ }
79105
+ /**
79106
+ * @beta
79107
+ * createPayment is a function to create protocol payment message
79108
+ * @param {DID} sender - sender did
79109
+ * @param {DID} receiver - receiver did
79110
+ * @param {PaymentInfo[]} payments - payments
79111
+ * @returns `PaymentMessage`
79112
+ */
79113
+ function createPayment(sender, receiver, payments) {
79114
+ const uuidv4 = v4();
79115
+ const request = {
79116
+ id: uuidv4,
79117
+ thid: uuidv4,
79118
+ from: sender.string(),
79119
+ to: receiver.string(),
79120
+ typ: MediaType.PlainMessage,
79121
+ type: PROTOCOL_MESSAGE_TYPE.PAYMENT_MESSAGE_TYPE,
79122
+ body: {
79123
+ payments
79124
+ }
79125
+ };
79126
+ return request;
79127
+ }
79128
+ /**
79129
+ *
79130
+ * Allows to process PaymentRequest protocol message
79131
+ * @beta
79132
+ * @class PaymentHandler
79133
+ * @implements implements IPaymentHandler interface
79134
+ */
79135
+ class PaymentHandler extends AbstractMessageHandler {
79136
+ /**
79137
+ * @beta Creates an instance of PaymentHandler.
79138
+ * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
79139
+ * @param {PaymentHandlerParams} _params - payment handler params
79140
+ *
79141
+ */
79142
+ constructor(_packerMgr, _params) {
79143
+ super();
79144
+ this._packerMgr = _packerMgr;
79145
+ this._params = _params;
79146
+ }
79147
+ async handle(message, context) {
79148
+ switch (message.type) {
79149
+ case PROTOCOL_MESSAGE_TYPE.PAYMENT_REQUEST_MESSAGE_TYPE:
79150
+ return await this.handlePaymentRequestMessage(message, context);
79151
+ case PROTOCOL_MESSAGE_TYPE.PAYMENT_MESSAGE_TYPE:
79152
+ await this.handlePayment(message, context);
79153
+ return null;
79154
+ default:
79155
+ return super.handle(message, context);
79156
+ }
79157
+ }
79158
+ /**
79159
+ * @inheritdoc IPaymentHandler#parsePaymentRequest
79160
+ */
79161
+ async parsePaymentRequest(request) {
79162
+ const { unpackedMessage: message } = await this._packerMgr.unpack(request);
79163
+ const paymentRequest = message;
79164
+ if (message.type !== PROTOCOL_MESSAGE_TYPE.PAYMENT_REQUEST_MESSAGE_TYPE) {
79165
+ throw new Error('Invalid media type');
79166
+ }
79167
+ return paymentRequest;
79168
+ }
79169
+ async handlePaymentRequestMessage(paymentRequest, ctx) {
79170
+ if (!paymentRequest.to) {
79171
+ throw new Error(`failed request. empty 'to' field`);
79172
+ }
79173
+ if (!paymentRequest.from) {
79174
+ throw new Error(`failed request. empty 'from' field`);
79175
+ }
79176
+ if (!paymentRequest.body?.payments?.length) {
79177
+ throw new Error(`failed request. no 'payments' in body`);
79178
+ }
79179
+ if (!ctx.paymentHandler) {
79180
+ throw new Error(`please provide payment handler in context`);
79181
+ }
79182
+ const senderDID = Z$2.parse(paymentRequest.to);
79183
+ const receiverDID = Z$2.parse(paymentRequest.from);
79184
+ const payments = [];
79185
+ for (let i = 0; i < paymentRequest.body.payments.length; i++) {
79186
+ const paymentReq = paymentRequest.body.payments[i];
79187
+ if (paymentReq.type !== exports.PaymentRequestType.PaymentRequest) {
79188
+ throw new Error(`failed request. not supported '${paymentReq.type}' payment type `);
79189
+ }
79190
+ if (paymentReq.data.type !== exports.PaymentRequestDataType.Iden3PaymentRequestCryptoV1) {
79191
+ throw new Error(`failed request. not supported '${paymentReq.data.type}' payment type `);
79192
+ }
79193
+ const txId = await ctx.paymentHandler(paymentReq.data);
79194
+ payments.push({
79195
+ id: paymentReq.data.id,
79196
+ type: exports.PaymentType.Iden3PaymentCryptoV1,
79197
+ paymentData: {
79198
+ txId
79199
+ }
79200
+ });
79201
+ }
79202
+ const paymentMessage = createPayment(senderDID, receiverDID, payments);
79203
+ const response = await this.packMessage(paymentMessage, senderDID);
79204
+ const agentResult = await fetch(paymentRequest.body.agent, {
79205
+ method: 'POST',
79206
+ body: response,
79207
+ headers: {
79208
+ 'Content-Type': 'application/octet-stream'
79209
+ }
79210
+ });
79211
+ const arrayBuffer = await agentResult.arrayBuffer();
79212
+ if (!arrayBuffer.byteLength) {
79213
+ return null;
79214
+ }
79215
+ const { unpackedMessage } = await this._packerMgr.unpack(new Uint8Array(arrayBuffer));
79216
+ return unpackedMessage;
79217
+ }
79218
+ /**
79219
+ * @inheritdoc IPaymentHandler#handlePaymentRequest
79220
+ */
79221
+ async handlePaymentRequest(request, opts) {
79222
+ if (this._params.packerParams.mediaType === MediaType.SignedMessage &&
79223
+ !this._params.packerParams.packerOptions) {
79224
+ throw new Error(`jws packer options are required for ${MediaType.SignedMessage}`);
79225
+ }
79226
+ const paymentRequest = await this.parsePaymentRequest(request);
79227
+ if (!paymentRequest.from) {
79228
+ throw new Error(`failed request. empty 'from' field`);
79229
+ }
79230
+ if (!paymentRequest.to) {
79231
+ throw new Error(`failed request. empty 'to' field`);
79232
+ }
79233
+ const agentMessage = await this.handlePaymentRequestMessage(paymentRequest, opts);
79234
+ if (!agentMessage) {
79235
+ return null;
79236
+ }
79237
+ const senderDID = Z$2.parse(paymentRequest.to);
79238
+ return this.packMessage(agentMessage, senderDID);
79239
+ }
79240
+ /**
79241
+ * @inheritdoc IPaymentHandler#handlePayment
79242
+ */
79243
+ async handlePayment(payment, opts) {
79244
+ if (opts.paymentRequest.from !== payment.to) {
79245
+ throw new Error(`sender of the request is not a target of response - expected ${opts.paymentRequest.from}, given ${payment.to}`);
79246
+ }
79247
+ if (!payment.body?.payments.length) {
79248
+ throw new Error(`failed request. empty 'payments' field in body`);
79249
+ }
79250
+ for (let i = 0; i < payment.body.payments.length; i++) {
79251
+ const p = payment.body?.payments[i];
79252
+ const paymentRequestData = opts.paymentRequest.body?.payments.find((r) => r.data.id === p.id);
79253
+ if (!paymentRequestData) {
79254
+ throw new Error(`can't find payment request for payment id ${p.id}`);
79255
+ }
79256
+ if (!opts.paymentValidationHandler) {
79257
+ throw new Error(`please provide payment validation handler in options`);
79258
+ }
79259
+ await opts.paymentValidationHandler(p.paymentData.txId, paymentRequestData.data);
79260
+ }
79261
+ }
79262
+ async packMessage(message, senderDID) {
79263
+ const responseEncoded = byteEncoder.encode(JSON.stringify(message));
79264
+ const packerOpts = this._params.packerParams.mediaType === MediaType.SignedMessage
79265
+ ? this._params.packerParams.packerOptions
79266
+ : {
79267
+ provingMethodAlg: T.provingMethodGroth16AuthV2Instance.methodAlg
79268
+ };
79269
+ return await this._packerMgr.pack(this._params.packerParams.mediaType, responseEncoded, {
79270
+ senderDID,
79271
+ ...packerOpts
79272
+ });
79273
+ }
79274
+ }
79275
+
79045
79276
  exports.AbstractMessageHandler = AbstractMessageHandler;
79046
79277
  exports.AbstractPrivateKeyStore = AbstractPrivateKeyStore;
79047
79278
  exports.AgentResolver = AgentResolver;
@@ -79120,6 +79351,7 @@ var PolygonIdSdk = (function (exports) {
79120
79351
  exports.PROTOCOL_CONSTANTS = constants;
79121
79352
  exports.PackageManager = PackageManager;
79122
79353
  exports.Parser = Parser;
79354
+ exports.PaymentHandler = PaymentHandler;
79123
79355
  exports.PlainPacker = PlainPacker;
79124
79356
  exports.ProofNode = ProofNode;
79125
79357
  exports.ProofService = ProofService;
@@ -79171,6 +79403,8 @@ var PolygonIdSdk = (function (exports) {
79171
79403
  exports.core = index$1;
79172
79404
  exports.createAuthorizationRequest = createAuthorizationRequest;
79173
79405
  exports.createAuthorizationRequestWithMessage = createAuthorizationRequestWithMessage;
79406
+ exports.createPayment = createPayment;
79407
+ exports.createPaymentRequest = createPaymentRequest;
79174
79408
  exports.createProposal = createProposal;
79175
79409
  exports.createProposalRequest = createProposalRequest;
79176
79410
  exports.createSchemaHash = createSchemaHash;