| 14 | ) {} |
| 15 | |
| 16 | async update(methodName: string, arg: ArrayBuffer | string) { |
| 17 | let argBuffer: ArrayBuffer; |
| 18 | if (typeof arg === 'string') { |
| 19 | arg = encode({ |
| 20 | idl: this.config.idl, |
| 21 | input: arg, |
| 22 | withType: { |
| 23 | kind: 'methodParams', |
| 24 | name: methodName, |
| 25 | }, |
| 26 | targetFormat: 'blob', |
| 27 | }); |
| 28 | |
| 29 | argBuffer = new TextEncoder().encode(arg).buffer; |
| 30 | } else { |
| 31 | argBuffer = arg; |
| 32 | } |
| 33 | |
| 34 | const result = await this.config.agent.call(this.config.canisterId, { |
| 35 | methodName, |
| 36 | arg: argBuffer, |
| 37 | callSync: true, |
| 38 | }); |
| 39 | |
| 40 | if (result.response.ok) { |
| 41 | if (result.response.body && 'certificate' in result.response.body) { |
| 42 | const certificate = await Certificate.create({ |
| 43 | certificate: bufFromBufLike(result.response.body.certificate), |
| 44 | rootKey: this.config.agent.rootKey!, |
| 45 | canisterId: Principal.from(this.config.canisterId), |
| 46 | }); |
| 47 | const path = [new TextEncoder().encode('request_status'), result.requestId]; |
| 48 | const status = new TextDecoder().decode( |
| 49 | lookupResultToBuffer(certificate.lookup([...path, 'status'])), |
| 50 | ); |
| 51 | |
| 52 | switch (status) { |
| 53 | case 'replied': { |
| 54 | const reply = lookupResultToBuffer(certificate.lookup([...path, 'reply']))!; |
| 55 | return decode({ |
| 56 | idl: this.config.idl, |
| 57 | input: uint8ArrayToHexString(new Uint8Array(reply)), |
| 58 | serviceMethod: methodName, |
| 59 | }); |
| 60 | } |
| 61 | case 'rejected': { |
| 62 | const rejectCode = new Uint8Array( |
| 63 | lookupResultToBuffer(certificate.lookup([...path, 'reject_code']))!, |
| 64 | )[0]; |
| 65 | const rejectMessage = new TextDecoder().decode( |
| 66 | lookupResultToBuffer(certificate.lookup([...path, 'reject_message']))!, |
| 67 | ); |
| 68 | const error_code_buf = lookupResultToBuffer( |
| 69 | certificate.lookup([...path, 'error_code']), |
| 70 | ); |
| 71 | const error_code = error_code_buf |
| 72 | ? new TextDecoder().decode(error_code_buf) |
| 73 | : undefined; |