@mysten/sui.js
Advanced tools
Comparing version 0.1.1 to 0.1.2
@@ -220,3 +220,3 @@ /** | ||
* let serialized = BCS | ||
* .ser('vector<u8>', [1,2,3,4,5,6]) | ||
* .set('vector<u8>', [1,2,3,4,5,6]) | ||
* .toBytes(); | ||
@@ -231,3 +231,3 @@ * | ||
*/ | ||
static ser(type: string, data: any, size?: number): BcsWriter; | ||
static set(type: string, data: any, size?: number): BcsWriter; | ||
/** | ||
@@ -247,3 +247,3 @@ * Deserialize BCS into a JS type. | ||
/** | ||
* Check whether a TypeInferface has been loaded for the `Type` | ||
* Check whether a TypeInterface has been loaded for the `Type` | ||
* @param type Name of the type to check. | ||
@@ -268,3 +268,3 @@ * @returns | ||
* ); | ||
* console.log(Array.from(BCS.ser('number_string', '12345').toBytes()) == [5,1,2,3,4,5]); | ||
* console.log(Array.from(BCS.set('number_string', '12345').toBytes()) == [5,1,2,3,4,5]); | ||
* | ||
@@ -294,3 +294,3 @@ * @param name | ||
* let array = BCS.de('vector<u8>', new Uint8Array([6,1,2,3,4,5,6])); // [1,2,3,4,5,6]; | ||
* let again = BCS.ser('vector<u8>', [1,2,3,4,5,6]).toBytes(); | ||
* let again = BCS.set('vector<u8>', [1,2,3,4,5,6]).toBytes(); | ||
* | ||
@@ -334,3 +334,3 @@ * @param name Name of the type to register. | ||
* // Let's encode the value as well | ||
* let test_ser = BCS.ser('Coin', { | ||
* let test_set = BCS.set('Coin', { | ||
* owner: 'Big Wallet Guy', | ||
@@ -341,3 +341,3 @@ * value: '412412400000', | ||
* | ||
* console.assert(Array.from(test_ser.toBytes()) === rust_bcs_str, 'Whoopsie, result mismatch'); | ||
* console.assert(Array.from(test_set.toBytes()) === rust_bcs_str, 'Whoopsie, result mismatch'); | ||
* | ||
@@ -370,4 +370,4 @@ * @param name Name of the type to register. | ||
* // and serialization | ||
* BCS.ser('MyEnum', { single: { value: 10000000 } }).toBytes(); | ||
* BCS.ser('MyEnum', { multi: [ { value: 1 }, { value: 2 } ] }); | ||
* BCS.set('MyEnum', { single: { value: 10000000 } }).toBytes(); | ||
* BCS.set('MyEnum', { multi: [ { value: 1 }, { value: 2 } ] }); | ||
* | ||
@@ -374,0 +374,0 @@ * @param name |
@@ -1,2 +0,2 @@ | ||
import { Ed25519KeypairData, Keypair, PublicKeyInitData, PublicKeyData, SignedTransaction, TransactionResponse, TransferTransaction, TxnDataSerializer, TransactionDigest, SuiAddress, ObjectOwner, ObjectRef, ObjectContentField, ObjectContentFields, ObjectContent, MovePackageContent, SuiObject, ObjectExistsInfo, ObjectNotExistsInfo, ObjectStatus, ObjectType, GetOwnedObjectRefsResponse, GetObjectInfoResponse, ObjectDigest, ObjectId, SequenceNumber, RawObjectRef, Transfer, RawAuthoritySignInfo, TransactionKindName, SingleTransactionKind, TransactionKind, TransactionData, EpochId, AuthorityQuorumSignInfo, CertifiedTransaction, GasCostSummary, ExecutionStatusType, ExecutionStatus, ExecutionStatusDetail, OwnedObjectRef, TransactionEffects, TransactionEffectsResponse, GatewayTxSeqNumber, GetTxnDigestsResponse, MoveModulePublish, Event, StructTag, MoveTypeTag, MoveCall, MoveCallArg, EmptySignInfo, AuthorityName, AuthoritySignature } from "./index"; | ||
import { Ed25519KeypairData, Keypair, PublicKeyInitData, PublicKeyData, TransferCoinTransaction, TxnDataSerializer, TransactionDigest, SuiAddress, ObjectOwner, ObjectRef, ObjectContentField, ObjectContentFields, ObjectContent, MovePackageContent, SuiObject, ObjectExistsInfo, ObjectNotExistsInfo, ObjectStatus, ObjectType, GetOwnedObjectRefsResponse, GetObjectInfoResponse, ObjectDigest, ObjectId, SequenceNumber, RawObjectRef, Transfer, RawAuthoritySignInfo, TransactionKindName, SingleTransactionKind, TransactionKind, TransactionData, EpochId, AuthorityQuorumSignInfo, CertifiedTransaction, GasCostSummary, ExecutionStatusType, ExecutionStatus, ExecutionStatusDetail, OwnedObjectRef, TransactionEffects, TransactionEffectsResponse, GatewayTxSeqNumber, GetTxnDigestsResponse, MoveModulePublish, Event, StructTag, MoveTypeTag, MoveCall, MoveCallArg, EmptySignInfo, AuthorityName, AuthoritySignature, TransactionBytes, TransactionResponse, SignedTransaction } from "./index"; | ||
export declare function isEd25519KeypairData(obj: any, _argumentName?: string): obj is Ed25519KeypairData; | ||
@@ -6,5 +6,3 @@ export declare function isKeypair(obj: any, _argumentName?: string): obj is Keypair; | ||
export declare function isPublicKeyData(obj: any, _argumentName?: string): obj is PublicKeyData; | ||
export declare function isSignedTransaction(obj: any, _argumentName?: string): obj is SignedTransaction; | ||
export declare function isTransactionResponse(obj: any, _argumentName?: string): obj is TransactionResponse; | ||
export declare function isTransferTransaction(obj: any, _argumentName?: string): obj is TransferTransaction; | ||
export declare function isTransferCoinTransaction(obj: any, _argumentName?: string): obj is TransferCoinTransaction; | ||
export declare function isTxnDataSerializer(obj: any, _argumentName?: string): obj is TxnDataSerializer; | ||
@@ -57,1 +55,4 @@ export declare function isTransactionDigest(obj: any, _argumentName?: string): obj is TransactionDigest; | ||
export declare function isAuthoritySignature(obj: any, _argumentName?: string): obj is AuthoritySignature; | ||
export declare function isTransactionBytes(obj: any, _argumentName?: string): obj is TransactionBytes; | ||
export declare function isTransactionResponse(obj: any, _argumentName?: string): obj is TransactionResponse; | ||
export declare function isSignedTransaction(obj: any, _argumentName?: string): obj is SignedTransaction; |
@@ -1,4 +0,5 @@ | ||
import { SignedTransaction, TransactionResponse, Provider } from './provider'; | ||
import { CertifiedTransaction, GatewayTxSeqNumber, GetTxnDigestsResponse, GetObjectInfoResponse, ObjectRef, TransactionDigest, TransactionEffectsResponse } from '../types'; | ||
import { Provider } from './provider'; | ||
import { CertifiedTransaction, GatewayTxSeqNumber, GetTxnDigestsResponse, GetObjectInfoResponse, ObjectRef, TransactionDigest, TransactionEffectsResponse, SignedTransaction, TransactionResponse } from '../types'; | ||
export declare class JsonRpcProvider extends Provider { | ||
endpoint: string; | ||
private client; | ||
@@ -17,3 +18,3 @@ /** | ||
getTransaction(digest: TransactionDigest): Promise<CertifiedTransaction>; | ||
executeTransaction(_txn: SignedTransaction): Promise<TransactionResponse>; | ||
executeTransaction(txn: SignedTransaction): Promise<TransactionResponse>; | ||
getTotalTransactionNumber(): Promise<number>; | ||
@@ -20,0 +21,0 @@ getTransactionDigestsInRange(start: GatewayTxSeqNumber, end: GatewayTxSeqNumber): Promise<GetTxnDigestsResponse>; |
@@ -1,8 +0,2 @@ | ||
import { GetObjectInfoResponse, ObjectRef, GatewayTxSeqNumber, GetTxnDigestsResponse } from '../types'; | ||
export interface SignedTransaction { | ||
txBytes: string; | ||
signature: string; | ||
pubKey: string; | ||
} | ||
export declare type TransactionResponse = string; | ||
import { GetObjectInfoResponse, ObjectRef, GatewayTxSeqNumber, GetTxnDigestsResponse, TransactionResponse, SignedTransaction } from '../types'; | ||
export declare abstract class Provider { | ||
@@ -9,0 +3,0 @@ /** |
@@ -1,3 +0,3 @@ | ||
import { CertifiedTransaction, TransactionDigest, GetTxnDigestsResponse, GatewayTxSeqNumber, ObjectRef, GetObjectInfoResponse } from '../types'; | ||
import { Provider, SignedTransaction, TransactionResponse } from './provider'; | ||
import { CertifiedTransaction, TransactionDigest, GetTxnDigestsResponse, GatewayTxSeqNumber, ObjectRef, GetObjectInfoResponse, SignedTransaction, TransactionResponse } from '../types'; | ||
import { Provider } from './provider'; | ||
export declare class VoidProvider extends Provider { | ||
@@ -4,0 +4,0 @@ getOwnedObjectRefs(_address: string): Promise<ObjectRef[]>; |
@@ -1,5 +0,6 @@ | ||
import { Provider, TransactionResponse } from '../providers/provider'; | ||
import { Provider } from '../providers/provider'; | ||
import { Base64DataBuffer } from '../serialization/base64'; | ||
import { TransactionResponse } from '../types'; | ||
import { SignaturePubkeyPair, Signer } from './signer'; | ||
import { TransferTransaction, TxnDataSerializer } from './txn-data-serializers/txn-data-serializer'; | ||
import { TransferCoinTransaction, TxnDataSerializer } from './txn-data-serializers/txn-data-serializer'; | ||
export declare abstract class SignerWithProvider implements Signer { | ||
@@ -22,5 +23,5 @@ readonly provider: Provider; | ||
/** | ||
* Serialize and Sign a `Transfer` transaction and submit to the Gateway for execution | ||
* Serialize and Sign a `TransferCoin` transaction and submit to the Gateway for execution | ||
*/ | ||
transfer(transaction: TransferTransaction): Promise<TransactionResponse>; | ||
transferCoin(transaction: TransferCoinTransaction): Promise<TransactionResponse>; | ||
} |
import { Base64DataBuffer } from '../../serialization/base64'; | ||
import { TransferTransaction, TxnDataSerializer } from './txn-data-serializer'; | ||
import { TransferCoinTransaction, TxnDataSerializer } from './txn-data-serializer'; | ||
/** | ||
@@ -11,3 +11,3 @@ * This is a temporary implementation of the `TxnDataSerializer` class | ||
export declare class RpcTxnDataSerializer implements TxnDataSerializer { | ||
private endpointURL; | ||
private client; | ||
/** | ||
@@ -19,3 +19,3 @@ * Establish a connection to a Sui Gateway endpoint | ||
constructor(endpoint: string); | ||
new_transfer(_transaction: TransferTransaction): Promise<Base64DataBuffer>; | ||
newTransferCoin(t: TransferCoinTransaction): Promise<Base64DataBuffer>; | ||
} |
import { Base64DataBuffer } from '../../serialization/base64'; | ||
export interface TransferTransaction { | ||
fromAddress: string; | ||
objectId: string; | ||
toAddress: string; | ||
gasObjectId: string; | ||
gas_budget: number; | ||
import { ObjectId, SuiAddress } from '../../types'; | ||
export interface TransferCoinTransaction { | ||
signer: SuiAddress; | ||
objectId: ObjectId; | ||
gasPayment: ObjectId; | ||
gasBudget: number; | ||
recipient: SuiAddress; | ||
} | ||
@@ -13,3 +14,3 @@ /** | ||
export interface TxnDataSerializer { | ||
new_transfer(transaction: TransferTransaction): Promise<Base64DataBuffer>; | ||
newTransferCoin(txn: TransferCoinTransaction): Promise<Base64DataBuffer>; | ||
} |
@@ -1,2 +0,2 @@ | ||
"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var e=t(require("tweetnacl")),r=require("buffer"),n=require("bn.js"),o=t(n),i=require("util"),u=t(require("jayson/lib/client/browser")),a=t(require("cross-fetch")),c=function(){function t(t){this.data="string"==typeof t?new Uint8Array(r.Buffer.from(t,"base64")):t}var e=t.prototype;return e.getData=function(){return this.data},e.getLength=function(){return this.data.length},e.toString=function(){return r.Buffer.from(this.data).toString("base64")},t}(),s=function(){function t(t){if(function(t){return void 0!==t._bn}(t))this._bn=t._bn;else{if("string"==typeof t){var e=r.Buffer.from(t,"base64");if(32!==e.length)throw new Error("Invalid public key input");this._bn=new o(e)}else this._bn=new o(t);if(this._bn.byteLength()>32)throw new Error("Invalid public key input")}}var e=t.prototype;return e.equals=function(t){return this._bn.eq(t._bn)},e.toBase64=function(){return this.toBuffer().toString("base64")},e.toBytes=function(){return this.toBuffer()},e.toBuffer=function(){var t=this._bn.toArrayLike(r.Buffer);if(32===t.length)return t;var e=r.Buffer.alloc(32);return t.copy(e,32-t.length),e},e.toString=function(){return this.toBase64()},e.toSuiAddress=function(){throw new Error("Not implemented")},t}(),f=function(){function t(t){this.keypair=t||e.sign.keyPair()}t.generate=function(){return new t(e.sign.keyPair())},t.fromSecretKey=function(r,n){var o=e.sign.keyPair.fromSecretKey(r);if(!n||!n.skipValidation){var u=(new i.TextEncoder).encode("sui validation"),a=e.sign.detached(u,o.secretKey);if(!e.sign.detached.verify(u,a,o.publicKey))throw new Error("provided secretKey is invalid")}return new t(o)},t.fromSeed=function(r){return new t(e.sign.keyPair.fromSeed(r))};var r=t.prototype;return r.getPublicKey=function(){return new s(this.keypair.publicKey)},r.signData=function(t){return new c(e.sign.detached(t.getData(),this.keypair.secretKey))},t}(),p=function(){};function h(t,e,r,n,o,i,u){try{var a=t[i](u),c=a.value}catch(t){return void r(t)}a.done?e(c):Promise.resolve(c).then(n,o)}function y(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function u(t){h(i,n,o,u,a,"next",t)}function a(t){h(i,n,o,u,a,"throw",t)}u(void 0)}))}}function l(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,(Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function d(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function v(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,e){if(t){if("string"==typeof t)return d(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?d(t,void 0):void 0}}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var g,w=(function(t){var e=function(t){var e=Object.prototype,r=e.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",i=n.asyncIterator||"@@asyncIterator",u=n.toStringTag||"@@toStringTag";function a(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{a({},"")}catch(t){a=function(t,e,r){return t[e]=r}}function c(t,e,r,n){var o=Object.create((e&&e.prototype instanceof p?e:p).prototype),i=new T(n||[]);return o._invoke=function(t,e,r){var n="suspendedStart";return function(o,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw i;return{value:void 0,done:!0}}for(r.method=o,r.arg=i;;){var u=r.delegate;if(u){var a=x(u,r);if(a){if(a===f)continue;return a}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=s(t,e,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===f)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}(t,r,i),o}function s(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=c;var f={};function p(){}function h(){}function y(){}var l={};a(l,o,(function(){return this}));var d=Object.getPrototypeOf,v=d&&d(d(E([])));v&&v!==e&&r.call(v,o)&&(l=v);var g=y.prototype=p.prototype=Object.create(l);function w(t){["next","throw","return"].forEach((function(e){a(t,e,(function(t){return this._invoke(e,t)}))}))}function b(t,e){var n;this._invoke=function(o,i){function u(){return new e((function(n,u){!function n(o,i,u,a){var c=s(t[o],t,i);if("throw"!==c.type){var f=c.arg,p=f.value;return p&&"object"==typeof p&&r.call(p,"__await")?e.resolve(p.__await).then((function(t){n("next",t,u,a)}),(function(t){n("throw",t,u,a)})):e.resolve(p).then((function(t){f.value=t,u(f)}),(function(t){return n("throw",t,u,a)}))}a(c.arg)}(o,i,n,u)}))}return n=n?n.then(u,u):u()}}function x(t,e){var r=t.iterator[e.method];if(void 0===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=void 0,x(t,e),"throw"===e.method))return f;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return f}var n=s(r,t.iterator,e.arg);if("throw"===n.type)return e.method="throw",e.arg=n.arg,e.delegate=null,f;var o=n.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,f):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,f)}function m(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 j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function T(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(m,this),this.reset(!0)}function E(t){if(t){var e=t[o];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,i=function e(){for(;++n<t.length;)if(r.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=void 0,e.done=!0,e};return i.next=i}}return{next:S}}function S(){return{value:void 0,done:!0}}return h.prototype=y,a(g,"constructor",y),a(y,"constructor",h),h.displayName=a(y,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===h||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,y):(t.__proto__=y,a(t,u,"GeneratorFunction")),t.prototype=Object.create(g),t},t.awrap=function(t){return{__await:t}},w(b.prototype),a(b.prototype,i,(function(){return this})),t.AsyncIterator=b,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var u=new b(c(e,r,n,o),i);return t.isGeneratorFunction(r)?u:u.next().then((function(t){return t.done?t.value:u.next()}))},w(g),a(g,u,"Generator"),a(g,o,(function(){return this})),a(g,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var e=[];for(var r in t)e.push(r);return e.reverse(),function r(){for(;e.length;){var n=e.pop();if(n in t)return r.value=n,r.done=!1,r}return r.done=!0,r}},t.values=E,T.prototype={constructor:T,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(j),!t)for(var e in this)"t"===e.charAt(0)&&r.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function n(r,n){return u.type="throw",u.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],u=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var a=r.call(i,"catchLoc"),c=r.call(i,"finallyLoc");if(a&&c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(a){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.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 u=i?i.completion:{};return u.type=t,u.arg=e,i?(this.method="next",this.next=i.finallyLoc,f):this.complete(u)},complete:function(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),f},finish:function(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),j(r),f}},catch:function(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;j(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:E(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},t}(t.exports);try{regeneratorRuntime=e}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}}(g={exports:{}}),g.exports);function b(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&t._bn instanceof n.BN}function x(t,e){return"string"==typeof t}function m(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&x(t.AddressOwner)||(null!==t&&"object"==typeof t||"function"==typeof t)&&x(t.ObjectOwner)||"Shared"===t||"Immutable"===t}function j(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&x(t.digest)&&x(t.objectId)&&C(t.version)}function T(t,e){return x(t)||C(t)||!1===t||!0===t||Array.isArray(t)&&t.every((function(t){return C(t)}))||S(t)||Array.isArray(t)&&t.every((function(t){return S(t)}))}function E(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&Object.entries(t).every((function(t){var e=t[0];return T(t[1])&&x(e)}))}function S(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&E(t.fields)&&x(t.type)}function A(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&Object.entries(t).every((function(t){var e=t[0];return x(t[1])&&x(e)}))}function _(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&(S(t.contents)||A(t.contents))&&m(t.owner)&&x(t.tx_digest)}function O(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&j(t.objectRef)&&B(t.objectType)&&_(t.object)}function k(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&x(t.objectId)}function R(t,e){return"Exists"===t||"NotExists"===t||"Deleted"===t}function B(t,e){return"moveObject"===t||"movePackage"===t}function P(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&Array.isArray(t.objects)&&t.objects.every((function(t){return j(t)}))}function I(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&R(t.status)&&(j(t.details)||O(t.details)||k(t.details))}function C(t,e){return"number"==typeof t}function L(t,e){return Array.isArray(t)&&x(t[0])&&C(t[1])&&x(t[2])}function U(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&x(t.recipient)&&L(t.object_ref)}function N(t,e){return Array.isArray(t)&&x(t[0])&&x(t[1])}function D(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&U(t.Transfer)||(null!==t&&"object"==typeof t||"function"==typeof t)&&H(t.Publish)||(null!==t&&"object"==typeof t||"function"==typeof t)&&tt(t.Call)}function V(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&D(t.Single)||(null!==t&&"object"==typeof t||"function"==typeof t)&&Array.isArray(t.Batch)&&t.Batch.every((function(t){return D(t)}))}function q(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&V(t.kind)&&x(t.sender)&&L(t.gas_payment)&&C(t.gas_budget)}function K(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&C(t.epoch)&&Array.isArray(t.signatures)&&t.signatures.every((function(t){return N(t)}))}function F(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&q(t.data)&&x(t.tx_signature)&&K(t.auth_sign_info)}function G(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&C(t.computation_cost)&&C(t.storage_cost)&&C(t.storage_rebate)}function W(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&M(t.Success)||(null!==t&&"object"==typeof t||"function"==typeof t)&&M(t.Failure)}function M(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&G(t.gas_cost)}function z(t,e){return Array.isArray(t)&&L(t[0])&&m(t[1])}function Y(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&W(t.status)&&Array.isArray(t.shared_objects)&&t.shared_objects.every((function(t){return L(t)}))&&x(t.transaction_digest)&&Array.isArray(t.created)&&t.created.every((function(t){return z(t)}))&&Array.isArray(t.mutated)&&t.mutated.every((function(t){return z(t)}))&&Array.isArray(t.unwrapped)&&t.unwrapped.every((function(t){return z(t)}))&&Array.isArray(t.deleted)&&t.deleted.every((function(t){return L(t)}))&&Array.isArray(t.wrapped)&&t.wrapped.every((function(t){return L(t)}))&&z(t.gas_object)&&Array.isArray(t.events)&&t.events.every((function(t){return Q(t)}))&&Array.isArray(t.dependencies)&&t.dependencies.every((function(t){return x(t)}))}function J(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&F(t.certificate)&&Y(t.effects)}function $(t,e){return Array.isArray(t)&&t.every((function(t){return Array.isArray(t)&&C(t[0])&&x(t[1])}))}function H(t,e){return null!==t&&"object"==typeof t||"function"==typeof t}function Q(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&Z(t.type_)&&x(t.contents)}function Z(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&x(t.address)&&x(t.module)&&x(t.name)&&Array.isArray(t.type_args)&&t.type_args.every((function(t){return X(t)}))}function X(t,e){return"bool"===t||"u8"===t||"u64"===t||"u128"===t||"address"===t||"signer"===t||(null!==t&&"object"==typeof t||"function"==typeof t)&&Array.isArray(t.vector)&&t.vector.every((function(t){return X(t)}))||(null!==t&&"object"==typeof t||"function"==typeof t)&&Z(t.struct)}function tt(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&L(t.package)&&x(t.module)&&x(t.function)&&Array.isArray(t.type_arguments)&&t.type_arguments.every((function(t){return X(t)}))&&Array.isArray(t.arguments)&&t.arguments.every((function(t){return et(t)}))}function et(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&Array.isArray(t.Pure)&&t.Pure.every((function(t){return C(t)}))||(null!==t&&"object"==typeof t||"function"==typeof t)&&L(t.ImmOrOwnedObject)||(null!==t&&"object"==typeof t||"function"==typeof t)&&x(t.SharedObject)}function rt(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&"2.0"===t.jsonrpc&&x(t.id)}var nt=function(){function t(t,e){this.rpcClient=this.createRpcClient(t,e)}var e=t.prototype;return e.createRpcClient=function(t,e){return new u(function(){var r=y(w.mark((function r(n,o){var i,u,c;return w.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return i={method:"POST",body:n,headers:Object.assign({"Content-Type":"application/json"},e||{})},r.prev=1,r.next=4,a(t,i);case 4:return u=r.sent,r.next=7,u.text();case 7:c=r.sent,u.ok?o(null,c):o(new Error(u.status+" "+u.statusText+": "+c)),r.next=14;break;case 11:r.prev=11,r.t0=r.catch(1),r.t0 instanceof Error&&o(r.t0);case 14:case"end":return r.stop()}}),r,null,[[1,11]])})));return function(t,e){return r.apply(this,arguments)}}(),{})},e.requestWithType=function(){var t=y(w.mark((function t(e,r,n){var o;return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.request(e,r);case 2:if((null===(i=o=t.sent)||"object"!=typeof i)&&"function"!=typeof i||"2.0"!==i.jsonrpc||!x(i.id)||(null===i.error||"object"!=typeof i.error)&&"function"!=typeof i.error||!x(i.error.message)){t.next=7;break}throw new Error("RPC Error: "+o.error.message);case 7:if(!rt(o)){t.next=13;break}if(!n(o.result)){t.next=12;break}return t.abrupt("return",o.result);case 12:throw new Error("RPC Error: result not of expected type. Result received was: "+JSON.stringify(o.result));case 13:throw new Error("Unexpected RPC Response: "+o);case 14:case"end":return t.stop()}var i}),t,this)})));return function(e,r,n){return t.apply(this,arguments)}}(),e.request=function(){var t=y(w.mark((function t(e,r){var n=this;return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",new Promise((function(t,o){n.rpcClient.request(e,r,(function(e,r){e?o(e):t(r)}))})));case 1:case"end":return t.stop()}}),t)})));return function(e,r){return t.apply(this,arguments)}}(),e.batchRequestWithType=function(){var t=y(w.mark((function t(e,r){var n;return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.batchRequest(e);case 2:return n=t.sent.filter((function(t){return rt(t)&&r(t.result)})),t.abrupt("return",n.map((function(t){return t.result})));case 5:case"end":return t.stop()}}),t,this)})));return function(e,r){return t.apply(this,arguments)}}(),e.batchRequest=function(){var t=y(w.mark((function t(e){var r=this;return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",new Promise((function(t,n){0===e.length&&t([]);var o=e.map((function(t){return r.rpcClient.request(t.method,t.args)}));r.rpcClient.request(o,(function(e,r){e?n(e):t(r)}))})));case 1:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}(),t}();function ot(t){return"Exists"!==t.status?void 0:t.details}function it(t){var e=ot(t);if(null!=e)return"moveObject"===e.objectType?e.object.contents:void 0}function ut(t){var e=it(t);return null!=e&&(t.details.object.contents=function t(e){var r={};return Object.entries(e.fields).forEach((function(e){var n=e[0],o=e[1];if(S(o)){for(var i=!1,u=0,a=[ft,ct,st];u<a.length;u++){var c=a[u];if(c.canTransform(o)){r[n]=c.toFieldValue(o),i=!0;break}}i||(r[n]=t(o))}else r[n]=o})),{fields:r,type:e.type}}(e)),t}var at=function(){function t(){}return t.toFieldValue=function(t){throw new Error("Children classes must override")},t.canTransform=function(t){throw new Error("Children classes must override")},t}(),ct=function(t){function e(){return t.apply(this,arguments)||this}return l(e,t),e.toFieldValue=function(t){var e=t.fields.bytes;switch(t.type){case"0x1::ASCII::String":return e.map((function(t){return String.fromCharCode(t)})).join("");case"0x2::UTF8::String":return function(t){for(var e=[1,1,1,1,2,2,3,0],r=t.length,n="",o=0;o<r;){var i=t[o++];if(128&i){var u=e[i>>3&7];if(!(64&i)||!u||o+u>r)return null;for(i&=63>>u;u>0;u-=1){var a=t[o++];if(128!=(192&a))return null;i=i<<6|63&a}}n+=String.fromCharCode(i)}return n}(new Uint8Array(e))}return t},e.canTransform=function(t){return"0x2::UTF8::String"===t.type||"0x1::ASCII::String"===t.type},e}(at),st=function(t){function e(){return t.apply(this,arguments)||this}return l(e,t),e.toFieldValue=function(t){return e.canTransform(t)?t.fields.id.fields.bytes:t},e.canTransform=function(t){return"0x2::ID::UniqueID"===t.type&&S(t.fields.id)&&"0x2::ID::ID"===t.fields.id.type},e}(at),ft=function(t){function e(){return t.apply(this,arguments)||this}return l(e,t),e.toFieldValue=function(t){return e.canTransform(t)?t.fields.value:t},e.canTransform=function(t){return t.type.startsWith("0x2::Balance::Balance")},e}(at),pt=function(t){return"number"==typeof t},ht=function(t){function e(e){var r;return(r=t.call(this)||this).client=new nt(e),r}l(e,t);var r=e.prototype;return r.getOwnedObjectRefs=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getOwnedObjects",[e],P);case 3:return t.abrupt("return",t.sent.objects);case 7:throw t.prev=7,t.t0=t.catch(0),new Error("Error fetching owned object refs: "+t.t0+" for address "+e);case 10:case"end":return t.stop()}}),t,this,[[0,7]])})));return function(e){return t.apply(this,arguments)}}(),r.getObjectInfo=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getObjectTypedInfo",[e],I);case 3:return t.abrupt("return",ut(t.sent));case 7:throw t.prev=7,t.t0=t.catch(0),new Error("Error fetching object info: "+t.t0+" for id "+e);case 10:case"end":return t.stop()}}),t,this,[[0,7]])})));return function(e){return t.apply(this,arguments)}}(),r.getObjectInfoBatch=function(){var t=y(w.mark((function t(e){var r;return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=e.map((function(t){return{method:"sui_getObjectTypedInfo",args:[t]}})),t.prev=1,t.next=4,this.client.batchRequestWithType(r,I);case 4:return t.abrupt("return",t.sent.map((function(t){return ut(t)})));case 8:throw t.prev=8,t.t0=t.catch(1),new Error("Error fetching object info: "+t.t0+" for id "+e);case 11:case"end":return t.stop()}}),t,this,[[1,8]])})));return function(e){return t.apply(this,arguments)}}(),r.getTransactionWithEffects=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getTransaction",[e],J);case 3:return t.abrupt("return",t.sent);case 7:throw t.prev=7,t.t0=t.catch(0),new Error("Error getting transaction with effects: "+t.t0+" for digest "+e);case 10:case"end":return t.stop()}}),t,this,[[0,7]])})));return function(e){return t.apply(this,arguments)}}(),r.getTransactionWithEffectsBatch=function(){var t=y(w.mark((function t(e){var r,n;return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=e.map((function(t){return{method:"sui_getTransaction",args:[t]}})),t.prev=1,t.next=4,this.client.batchRequestWithType(r,J);case 4:return t.abrupt("return",t.sent);case 7:throw t.prev=7,t.t0=t.catch(1),n=e.join(", ").substring(0,-2),new Error("Error getting transaction effects: "+t.t0+" for digests ["+n+"]");case 11:case"end":return t.stop()}}),t,this,[[1,7]])})));return function(e){return t.apply(this,arguments)}}(),r.getTransaction=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getTransaction",[e],J);case 3:return t.abrupt("return",t.sent.certificate);case 7:throw t.prev=7,t.t0=t.catch(0),new Error("Error getting transaction: "+t.t0+" for digest "+e);case 10:case"end":return t.stop()}}),t,this,[[0,7]])})));return function(e){return t.apply(this,arguments)}}(),r.executeTransaction=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw new Error("Method not implemented.");case 1:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}(),r.getTotalTransactionNumber=function(){var t=y(w.mark((function t(){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getTotalTransactionNumber",[],pt);case 3:return t.abrupt("return",t.sent);case 7:throw t.prev=7,t.t0=t.catch(0),new Error("Error fetching total transaction number: "+t.t0);case 10:case"end":return t.stop()}}),t,this,[[0,7]])})));return function(){return t.apply(this,arguments)}}(),r.getTransactionDigestsInRange=function(){var t=y(w.mark((function t(e,r){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getTransactionsInRange",[e,r],$);case 3:return t.abrupt("return",t.sent);case 6:throw t.prev=6,t.t0=t.catch(0),new Error("Error fetching transaction digests in range: "+t.t0+" for range "+e+"-"+r);case 9:case"end":return t.stop()}}),t,this,[[0,6]])})));return function(e,r){return t.apply(this,arguments)}}(),r.getRecentTransactions=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getRecentTransactions",[e],$);case 3:return t.abrupt("return",t.sent);case 6:throw t.prev=6,t.t0=t.catch(0),new Error("Error fetching recent transactions: "+t.t0+" for count "+e);case 9:case"end":return t.stop()}}),t,this,[[0,6]])})));return function(e){return t.apply(this,arguments)}}(),e}(p),yt=function(){function t(t){this._data="string"==typeof t?new Uint8Array(r.Buffer.from(t,"hex")):t}var e=t.prototype;return e.getData=function(){return this._data},e.getLength=function(){return this._data.length},e.toString=function(){return r.Buffer.from(this._data).toString("hex")},t}(),lt=function(){function t(t){this.endpointURL=t}return t.prototype.new_transfer=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw new Error("Method not implemented.");case 1:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}(),t}(),dt=function(t){function e(){return t.apply(this,arguments)||this}l(e,t);var r=e.prototype;return r.getOwnedObjectRefs=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("getOwnedObjectRefs");case 1:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),r.getObjectInfo=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("getObjectInfo");case 1:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),r.getTransaction=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("getTransaction");case 1:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),r.executeTransaction=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("executeTransaction");case 1:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),r.getTotalTransactionNumber=function(){var t=y(w.mark((function t(){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("getTotalTransactionNumber");case 1:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),r.getTransactionDigestsInRange=function(){var t=y(w.mark((function t(e,r){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("getTransactionDigestsInRange");case 1:case"end":return t.stop()}}),t,this)})));return function(e,r){return t.apply(this,arguments)}}(),r.getRecentTransactions=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("getRecentTransactions");case 1:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),r.newError=function(t){return new Error("Please use a valid provider for "+t)},e}(p),vt=function(){function t(t,e){this.provider=t||new dt,this.serializer=e||new lt("")}var e=t.prototype;return e.signAndExecuteTransaction=function(){var t=y(w.mark((function t(e){var r;return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.signData(e);case 2:return r=t.sent,t.next=5,this.provider.executeTransaction({txBytes:e.toString(),signature:r.signature.toString(),pubKey:r.pubKey.toString()});case 5:return t.abrupt("return",t.sent);case 6:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),e.transfer=function(){var t=y(w.mark((function t(e){var r;return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.serializer.new_transfer(e);case 2:return r=t.sent,t.next=5,this.signAndExecuteTransaction(r);case 5:return t.abrupt("return",t.sent);case 6:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),t}(),gt=function(t){function e(e,r,n){var o;return(o=t.call(this,r,n)||this).keypair=e,o}l(e,t);var r=e.prototype;return r.getAddress=function(){var t=y(w.mark((function t(){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.keypair.getPublicKey().toSuiAddress();case 1:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),r.signData=function(){var t=y(w.mark((function t(e){return w.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",{signature:this.keypair.signData(e),pubKey:this.keypair.getPublicKey()});case 1:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),r.connect=function(t){return new e(this.keypair,t)},e}(vt);function wt(t){return"Single"in t.kind?t.kind.Single:void 0}function bt(t){return xt(t).gas_cost}function xt(t){return"Success"in t?t.Success:"Failure"in t?t.Failure:(console.error("Unrecognized ExecutionStatus:",t),t[Object.keys(t)[0]])}var mt=function(){function t(t){this.bytePosition=0,this.dataView=new DataView(t.buffer)}var e=t.prototype;return e.shift=function(t){return this.bytePosition+=t,this},e.read8=function(){var t=this.dataView.getUint8(this.bytePosition);return this.shift(1),new n.BN(t,10)},e.read16=function(){var t=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),new n.BN(t,10)},e.read32=function(){var t=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),new n.BN(t,10)},e.read64=function(){var t=this.read32(),e=this.read32().toString(16)+t.toString(16).padStart(8,"0");return new n.BN(e,16)},e.read128=function(){var t=this.read64(),e=this.read64().toString(16)+t.toString(16).padStart(8,"0");return new n.BN(e,16)},e.readBytes=function(t){var e=new Uint8Array(this.dataView.buffer,this.bytePosition+this.dataView.byteOffset,t);return this.shift(t),e},e.readULEB=function(){var t=function(t){for(var e=0,r=0,n=0;;){var o=t[n];if(n+=1,e|=(127&o)<<r,0==(128&o))break;r+=7}return{value:e,length:n}}(new Uint8Array(this.dataView.buffer,this.bytePosition+this.dataView.byteOffset)),e=t.value;return this.shift(t.length),e},e.readVec=function(t){for(var e=this.readULEB(),r=[],n=0;n<e;n++)r.push(t(this,n,e));return r},t}(),jt=function(){function t(t){void 0===t&&(t=1024),this.bytePosition=0,this.dataView=new DataView(new ArrayBuffer(t))}t.toBN=function(t){switch(typeof t){case"bigint":return new n.BN(t.toString());default:return new n.BN(t)}};var e=t.prototype;return e.shift=function(t){return this.bytePosition+=t,this},e.write8=function(e){return this.dataView.setUint8(this.bytePosition,+t.toBN(e)),this.shift(1)},e.write16=function(e){return this.dataView.setUint16(this.bytePosition,+t.toBN(e),!0),this.shift(2)},e.write32=function(e){return this.dataView.setUint32(this.bytePosition,+t.toBN(e),!0),this.shift(4)},e.write64=function(e){var r=this;return t.toBN(e).toArray("le",8).forEach((function(t){return r.write8(t)})),this},e.write128=function(e){var r=this;return t.toBN(e).toArray("le",16).forEach((function(t){return r.write8(t)})),this},e.writeULEB=function(t){var e=this;return function(t){var e=[],r=0;if(0===t)return[0];for(;t>0;)e[r]=127&t,(t>>=7)&&(e[r]|=128),r+=1;return e}(t).forEach((function(t){return e.write8(t)})),this},e.writeVec=function(t,e){var r=this;return this.writeULEB(t.length),Array.from(t).forEach((function(n,o){return e(r,n,o,t.length)})),this},e.toBytes=function(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))},e.toString=function(t){switch(t){case"base64":return new c(this.toBytes()).toString();case"hex":return new yt(this.toBytes()).toString();default:throw new Error("Unsupported encoding, supported values are: base64, hex")}},t}(),Tt=function(){function t(){}return t.ser=function(t,e,r){return void 0===r&&(r=1024),this.getTypeInterface(t).encode(e,r)},t.de=function(t,e){return this.getTypeInterface(t).decode(e)},t.hasType=function(t){return this.types.has(t)},t.registerType=function(t,e,r,n){return void 0===n&&(n=function(){return!0}),this.types.set(t,{encode:function(t,e){return void 0===e&&(e=1024),this._encodeRaw(new jt(e),t)},decode:function(t){return this._decodeRaw(new mt(t))},_encodeRaw:function(r,o){if(n(o))return e(r,o);throw new Error("Validation failed for type "+t+", data: "+o)},_decodeRaw:function(t){return r(t)}}),this},t.registerAddressType=function(t,e){return this.registerType(t,(function(t,e){return new yt(e).getData().reduce((function(t,e){return t.write8(e)}),t)}),(function(t){return new yt(t.readBytes(e)).toString()}))},t.registerVectorType=function(e,r){return this.registerType(e,(function(e,n){return e.writeVec(n,(function(e,n){return t.getTypeInterface(r)._encodeRaw(e,n)}))}),(function(e){return e.readVec((function(e){return t.getTypeInterface(r)._decodeRaw(e)}))}))},t.registerStructType=function(e,r){var n=Object.freeze(r),o=Object.keys(n);return this.registerType(e,(function(e,r){for(var i,u=v(o);!(i=u()).done;){var a=i.value;t.getTypeInterface(n[a])._encodeRaw(e,r[a])}return e}),(function(e){for(var r,i={},u=v(o);!(r=u()).done;){var a=r.value;i[a]=t.getTypeInterface(n[a])._decodeRaw(e)}return i}))},t.registerEnumType=function(e,r){var n=Object.freeze(r),o=Object.keys(n);return this.registerType(e,(function(r,i){var u=Object.keys(i)[0];if(void 0===u)throw new Error("Unknown invariant of the enum "+e);var a=o.indexOf(u);if(-1===a)throw new Error("Unknown invariant of the enum "+e+", allowed values: "+o);var c=n[o[a]];return r.write8(a),null!==c?t.getTypeInterface(c)._encodeRaw(r,i[u]):r}),(function(r){var i,u=r.readULEB(),a=o[u],c=n[a];if(-1===u)throw new Error("Decoding type mismatch, expected enum "+e+" invariant index, received "+u);return(i={})[a]=null===c||t.getTypeInterface(c)._decodeRaw(r),i}))},t.getTypeInterface=function(e){var r=t.types.get(e);if(void 0===r)throw new Error("Type "+e+" is not registered");return r},t}();Tt.U8="u8",Tt.U32="u32",Tt.U64="u64",Tt.U128="u128",Tt.BOOL="bool",Tt.VECTOR="vector",Tt.ADDRESS="address",Tt.STRING="string",Tt.types=new Map,Tt.registerType(Tt.U8,(function(t,e){return t.write8(e)}),(function(t){return t.read8()}),(function(t){return t<256})),Tt.registerType(Tt.U32,(function(t,e){return t.write32(e)}),(function(t){return t.read32()}),(function(t){return t<4294967296})),Tt.registerType(Tt.U64,(function(t,e){return t.write64(e)}),(function(t){return t.read64()}),(function(t){return!0})),Tt.registerType(Tt.U128,(function(t,e){return t.write128(e)}),(function(t){return t.read128()}),(function(t){return!0})),Tt.registerType(Tt.BOOL,(function(t,e){return t.write8(e)}),(function(t){return"1"==t.read8().toString(10)}),(function(t){return!0})),Tt.registerType(Tt.STRING,(function(t,e){return t.writeVec(Array.from(e),(function(t,e){return t.write8(e.charCodeAt(0))}))}),(function(t){return t.readVec((function(t){return t.read8()})).map((function(t){return String.fromCharCode(t)})).join("")}),(function(t){return/^[\x00-\x7F]*$/.test(t)})),exports.BCS={__proto__:null,BcsReader:mt,BcsWriter:jt,BCS:Tt},exports.Base64DataBuffer=c,exports.Ed25519Keypair=f,exports.HexDataBuffer=yt,exports.JsonRpcProvider=ht,exports.PUBLIC_KEY_SIZE=32,exports.Provider=p,exports.PublicKey=s,exports.RawSigner=gt,exports.RpcTxnDataSerializer=lt,exports.SignerWithProvider=vt,exports.getExecutionDetails=xt,exports.getExecutionStatusType=function(t){return Object.keys(t)[0]},exports.getGasSummary=bt,exports.getMoveCallTransaction=function(t){var e=wt(t);return e&&"Call"in e?e.Call:void 0},exports.getMovePackageContent=function(t){var e=ot(t);if(null!=e)return"movePackage"===e.objectType?e.object.contents:void 0},exports.getObjectContent=it,exports.getObjectExistsResponse=ot,exports.getObjectType=function(t){var e;return null==(e=ot(t))?void 0:e.objectType},exports.getPublishTransaction=function(t){var e=wt(t);return e&&"Publish"in e?e.Publish:void 0},exports.getSingleTransactionKind=wt,exports.getTotalGasUsed=function(t){var e=bt(t);return e?e.computation_cost+e.storage_cost-e.storage_rebate:0},exports.getTransactionKind=function(t){var e=wt(t);return e&&Object.keys(e)[0]},exports.getTransferTransaction=function(t){var e=wt(t);return e&&"Transfer"in e?e.Transfer:void 0},exports.isAuthorityName=function(t,e){return"string"==typeof t},exports.isAuthorityQuorumSignInfo=K,exports.isAuthoritySignature=function(t,e){return"string"==typeof t},exports.isCertifiedTransaction=F,exports.isEd25519KeypairData=function(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&t.publicKey instanceof Uint8Array&&t.secretKey instanceof Uint8Array},exports.isEmptySignInfo=function(t,e){return"object"==typeof t},exports.isEpochId=function(t,e){return"number"==typeof t},exports.isEvent=Q,exports.isExecutionStatus=W,exports.isExecutionStatusDetail=M,exports.isExecutionStatusType=function(t,e){return"Success"===t||"Failure"===t},exports.isGasCostSummary=G,exports.isGatewayTxSeqNumber=function(t,e){return"number"==typeof t},exports.isGetObjectInfoResponse=I,exports.isGetOwnedObjectRefsResponse=P,exports.isGetTxnDigestsResponse=$,exports.isKeypair=function(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&"function"==typeof t.getPublicKey&&"function"==typeof t.signData},exports.isMoveCall=tt,exports.isMoveCallArg=et,exports.isMoveModulePublish=H,exports.isMovePackageContent=A,exports.isMoveTypeTag=X,exports.isObjectContent=S,exports.isObjectContentField=T,exports.isObjectContentFields=E,exports.isObjectDigest=function(t,e){return"string"==typeof t},exports.isObjectExistsInfo=O,exports.isObjectId=function(t,e){return"string"==typeof t},exports.isObjectNotExistsInfo=k,exports.isObjectOwner=m,exports.isObjectRef=j,exports.isObjectStatus=R,exports.isObjectType=B,exports.isOwnedObjectRef=z,exports.isPublicKeyData=b,exports.isPublicKeyInitData=function(t,e){return x(t)||C(t)||t instanceof Buffer||t instanceof Uint8Array||Array.isArray(t)&&t.every((function(t){return C(t)}))||b(t)},exports.isRawAuthoritySignInfo=N,exports.isRawObjectRef=L,exports.isSequenceNumber=C,exports.isSignedTransaction=function(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&x(t.txBytes)&&x(t.signature)&&x(t.pubKey)},exports.isSingleTransactionKind=D,exports.isStructTag=Z,exports.isSuiAddress=function(t,e){return"string"==typeof t},exports.isSuiObject=_,exports.isTransactionData=q,exports.isTransactionDigest=function(t,e){return"string"==typeof t},exports.isTransactionEffects=Y,exports.isTransactionEffectsResponse=J,exports.isTransactionKind=V,exports.isTransactionKindName=function(t,e){return"Transfer"===t||"Publish"===t||"Call"===t},exports.isTransactionResponse=x,exports.isTransfer=U,exports.isTransferTransaction=function(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&x(t.fromAddress)&&x(t.objectId)&&x(t.toAddress)&&x(t.gasObjectId)&&C(t.gas_budget)},exports.isTxnDataSerializer=function(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&"function"==typeof t.new_transfer}; | ||
"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var e=t(require("tweetnacl")),r=require("buffer"),n=require("bn.js"),o=t(n),i=require("js-sha3"),u=require("util"),c=t(require("jayson/lib/client/browser")),a=t(require("cross-fetch")),s=function(){function t(t){this.data="string"==typeof t?new Uint8Array(r.Buffer.from(t,"base64")):t}var e=t.prototype;return e.getData=function(){return this.data},e.getLength=function(){return this.data.length},e.toString=function(){return r.Buffer.from(this.data).toString("base64")},t}(),f=function(){function t(t){if(function(t){return void 0!==t._bn}(t))this._bn=t._bn;else{if("string"==typeof t){var e=r.Buffer.from(t,"base64");if(32!==e.length)throw new Error("Invalid public key input. Expected 32 bytes, got "+e.length);this._bn=new o(e)}else this._bn=new o(t);if(this._bn.byteLength()>32)throw new Error("Invalid public key input")}}var e=t.prototype;return e.equals=function(t){return this._bn.eq(t._bn)},e.toBase64=function(){return this.toBuffer().toString("base64")},e.toBytes=function(){return this.toBuffer()},e.toBuffer=function(){var t=this._bn.toArrayLike(r.Buffer);if(32===t.length)return t;var e=r.Buffer.alloc(32);return t.copy(e,32-t.length),e},e.toString=function(){return this.toBase64()},e.toSuiAddress=function(){var t=i.sha3_256(this.toBytes());return new o(t,16).toArray(void 0,32).slice(0,20).reduce((function(t,e){return t+("0"+e.toString(16)).slice(-2)}),"")},t}(),p=function(){function t(t){this.keypair=t||e.sign.keyPair()}t.generate=function(){return new t(e.sign.keyPair())},t.fromSecretKey=function(r,n){var o=e.sign.keyPair.fromSecretKey(r);if(!n||!n.skipValidation){var i=(new u.TextEncoder).encode("sui validation"),c=e.sign.detached(i,o.secretKey);if(!e.sign.detached.verify(i,c,o.publicKey))throw new Error("provided secretKey is invalid")}return new t(o)},t.fromSeed=function(r){return new t(e.sign.keyPair.fromSeed(r))};var r=t.prototype;return r.getPublicKey=function(){return new f(this.keypair.publicKey)},r.signData=function(t){return new s(e.sign.detached(t.getData(),this.keypair.secretKey))},t}(),h=function(){};function y(t,e,r,n,o,i,u){try{var c=t[i](u),a=c.value}catch(t){return void r(t)}c.done?e(a):Promise.resolve(a).then(n,o)}function l(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function u(t){y(i,n,o,u,c,"next",t)}function c(t){y(i,n,o,u,c,"throw",t)}u(void 0)}))}}function d(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,(Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function v(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function g(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,e){if(t){if("string"==typeof t)return v(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?v(t,void 0):void 0}}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var w,b=(function(t){var e=function(t){var e=Object.prototype,r=e.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",i=n.asyncIterator||"@@asyncIterator",u=n.toStringTag||"@@toStringTag";function c(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{c({},"")}catch(t){c=function(t,e,r){return t[e]=r}}function a(t,e,r,n){var o=Object.create((e&&e.prototype instanceof p?e:p).prototype),i=new T(n||[]);return o._invoke=function(t,e,r){var n="suspendedStart";return function(o,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw i;return{value:void 0,done:!0}}for(r.method=o,r.arg=i;;){var u=r.delegate;if(u){var c=x(u,r);if(c){if(c===f)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var a=s(t,e,r);if("normal"===a.type){if(n=r.done?"completed":"suspendedYield",a.arg===f)continue;return{value:a.arg,done:r.done}}"throw"===a.type&&(n="completed",r.method="throw",r.arg=a.arg)}}}(t,r,i),o}function s(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=a;var f={};function p(){}function h(){}function y(){}var l={};c(l,o,(function(){return this}));var d=Object.getPrototypeOf,v=d&&d(d(E([])));v&&v!==e&&r.call(v,o)&&(l=v);var g=y.prototype=p.prototype=Object.create(l);function w(t){["next","throw","return"].forEach((function(e){c(t,e,(function(t){return this._invoke(e,t)}))}))}function b(t,e){var n;this._invoke=function(o,i){function u(){return new e((function(n,u){!function n(o,i,u,c){var a=s(t[o],t,i);if("throw"!==a.type){var f=a.arg,p=f.value;return p&&"object"==typeof p&&r.call(p,"__await")?e.resolve(p.__await).then((function(t){n("next",t,u,c)}),(function(t){n("throw",t,u,c)})):e.resolve(p).then((function(t){f.value=t,u(f)}),(function(t){return n("throw",t,u,c)}))}c(a.arg)}(o,i,n,u)}))}return n=n?n.then(u,u):u()}}function x(t,e){var r=t.iterator[e.method];if(void 0===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=void 0,x(t,e),"throw"===e.method))return f;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return f}var n=s(r,t.iterator,e.arg);if("throw"===n.type)return e.method="throw",e.arg=n.arg,e.delegate=null,f;var o=n.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,f):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,f)}function m(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 j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function T(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(m,this),this.reset(!0)}function E(t){if(t){var e=t[o];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,i=function e(){for(;++n<t.length;)if(r.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=void 0,e.done=!0,e};return i.next=i}}return{next:S}}function S(){return{value:void 0,done:!0}}return h.prototype=y,c(g,"constructor",y),c(y,"constructor",h),h.displayName=c(y,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===h||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,y):(t.__proto__=y,c(t,u,"GeneratorFunction")),t.prototype=Object.create(g),t},t.awrap=function(t){return{__await:t}},w(b.prototype),c(b.prototype,i,(function(){return this})),t.AsyncIterator=b,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var u=new b(a(e,r,n,o),i);return t.isGeneratorFunction(r)?u:u.next().then((function(t){return t.done?t.value:u.next()}))},w(g),c(g,u,"Generator"),c(g,o,(function(){return this})),c(g,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var e=[];for(var r in t)e.push(r);return e.reverse(),function r(){for(;e.length;){var n=e.pop();if(n in t)return r.value=n,r.done=!1,r}return r.done=!0,r}},t.values=E,T.prototype={constructor:T,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(j),!t)for(var e in this)"t"===e.charAt(0)&&r.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function n(r,n){return u.type="throw",u.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],u=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var c=r.call(i,"catchLoc"),a=r.call(i,"finallyLoc");if(c&&a){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!a)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.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 u=i?i.completion:{};return u.type=t,u.arg=e,i?(this.method="next",this.next=i.finallyLoc,f):this.complete(u)},complete:function(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),f},finish:function(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),j(r),f}},catch:function(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;j(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:E(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},t}(t.exports);try{regeneratorRuntime=e}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}}(w={exports:{}}),w.exports);function x(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&t._bn instanceof n.BN}function m(t,e){return"string"==typeof t}function j(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&m(t.AddressOwner)||(null!==t&&"object"==typeof t||"function"==typeof t)&&m(t.ObjectOwner)||"Shared"===t||"Immutable"===t}function T(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&m(t.digest)&&m(t.objectId)&&L(t.version)}function E(t,e){return m(t)||L(t)||!1===t||!0===t||Array.isArray(t)&&t.every((function(t){return L(t)}))||_(t)||Array.isArray(t)&&t.every((function(t){return _(t)}))}function S(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&Object.entries(t).every((function(t){var e=t[0];return E(t[1])&&m(e)}))}function _(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&S(t.fields)&&m(t.type)}function A(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&Object.entries(t).every((function(t){var e=t[0];return m(t[1])&&m(e)}))}function O(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&(_(t.contents)||A(t.contents))&&j(t.owner)&&m(t.tx_digest)}function k(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&T(t.objectRef)&&R(t.objectType)&&O(t.object)}function B(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&m(t.objectId)}function P(t,e){return"Exists"===t||"NotExists"===t||"Deleted"===t}function R(t,e){return"moveObject"===t||"movePackage"===t}function I(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&Array.isArray(t.objects)&&t.objects.every((function(t){return T(t)}))}function C(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&P(t.status)&&(T(t.details)||k(t.details)||B(t.details))}function L(t,e){return"number"==typeof t}function U(t,e){return Array.isArray(t)&&m(t[0])&&L(t[1])&&m(t[2])}function N(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&m(t.recipient)&&U(t.object_ref)}function D(t,e){return Array.isArray(t)&&m(t[0])&&m(t[1])}function q(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&N(t.Transfer)||(null!==t&&"object"==typeof t||"function"==typeof t)&&Q(t.Publish)||(null!==t&&"object"==typeof t||"function"==typeof t)&&et(t.Call)}function V(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&q(t.Single)||(null!==t&&"object"==typeof t||"function"==typeof t)&&Array.isArray(t.Batch)&&t.Batch.every((function(t){return q(t)}))}function K(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&V(t.kind)&&m(t.sender)&&U(t.gas_payment)&&L(t.gas_budget)}function F(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&L(t.epoch)&&Array.isArray(t.signatures)&&t.signatures.every((function(t){return D(t)}))}function W(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&K(t.data)&&m(t.tx_signature)&&F(t.auth_sign_info)}function G(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&L(t.computation_cost)&&L(t.storage_cost)&&L(t.storage_rebate)}function M(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&z(t.Success)||(null!==t&&"object"==typeof t||"function"==typeof t)&&z(t.Failure)}function z(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&G(t.gas_cost)}function J(t,e){return Array.isArray(t)&&U(t[0])&&j(t[1])}function Y(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&M(t.status)&&Array.isArray(t.shared_objects)&&t.shared_objects.every((function(t){return U(t)}))&&m(t.transaction_digest)&&Array.isArray(t.created)&&t.created.every((function(t){return J(t)}))&&Array.isArray(t.mutated)&&t.mutated.every((function(t){return J(t)}))&&Array.isArray(t.unwrapped)&&t.unwrapped.every((function(t){return J(t)}))&&Array.isArray(t.deleted)&&t.deleted.every((function(t){return U(t)}))&&Array.isArray(t.wrapped)&&t.wrapped.every((function(t){return U(t)}))&&J(t.gas_object)&&Array.isArray(t.events)&&t.events.every((function(t){return Z(t)}))&&Array.isArray(t.dependencies)&&t.dependencies.every((function(t){return m(t)}))}function $(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&W(t.certificate)&&Y(t.effects)}function H(t,e){return Array.isArray(t)&&t.every((function(t){return Array.isArray(t)&&L(t[0])&&m(t[1])}))}function Q(t,e){return null!==t&&"object"==typeof t||"function"==typeof t}function Z(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&X(t.type_)&&m(t.contents)}function X(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&m(t.address)&&m(t.module)&&m(t.name)&&Array.isArray(t.type_args)&&t.type_args.every((function(t){return tt(t)}))}function tt(t,e){return"bool"===t||"u8"===t||"u64"===t||"u128"===t||"address"===t||"signer"===t||(null!==t&&"object"==typeof t||"function"==typeof t)&&Array.isArray(t.vector)&&t.vector.every((function(t){return tt(t)}))||(null!==t&&"object"==typeof t||"function"==typeof t)&&X(t.struct)}function et(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&U(t.package)&&m(t.module)&&m(t.function)&&Array.isArray(t.type_arguments)&&t.type_arguments.every((function(t){return tt(t)}))&&Array.isArray(t.arguments)&&t.arguments.every((function(t){return rt(t)}))}function rt(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&Array.isArray(t.Pure)&&t.Pure.every((function(t){return L(t)}))||(null!==t&&"object"==typeof t||"function"==typeof t)&&U(t.ImmOrOwnedObject)||(null!==t&&"object"==typeof t||"function"==typeof t)&&m(t.SharedObject)}function nt(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&m(t.tx_bytes)}function ot(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&$(t.EffectResponse)}function it(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&"2.0"===t.jsonrpc&&m(t.id)}var ut=function(){function t(t,e){this.rpcClient=this.createRpcClient(t,e)}var e=t.prototype;return e.createRpcClient=function(t,e){return new c(function(){var r=l(b.mark((function r(n,o){var i,u,c;return b.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return i={method:"POST",body:n,headers:Object.assign({"Content-Type":"application/json"},e||{})},r.prev=1,r.next=4,a(t,i);case 4:return u=r.sent,r.next=7,u.text();case 7:c=r.sent,u.ok?o(null,c):o(new Error(u.status+" "+u.statusText+": "+c)),r.next=14;break;case 11:r.prev=11,r.t0=r.catch(1),r.t0 instanceof Error&&o(r.t0);case 14:case"end":return r.stop()}}),r,null,[[1,11]])})));return function(t,e){return r.apply(this,arguments)}}(),{})},e.requestWithType=function(){var t=l(b.mark((function t(e,r,n){var o;return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.request(e,r);case 2:if((null===(i=o=t.sent)||"object"!=typeof i)&&"function"!=typeof i||"2.0"!==i.jsonrpc||!m(i.id)||(null===i.error||"object"!=typeof i.error)&&"function"!=typeof i.error||!m(i.error.message)){t.next=7;break}throw new Error("RPC Error: "+o.error.message);case 7:if(!it(o)){t.next=13;break}if(!n(o.result)){t.next=12;break}return t.abrupt("return",o.result);case 12:throw new Error("RPC Error: result not of expected type. Result received was: "+JSON.stringify(o.result));case 13:throw new Error("Unexpected RPC Response: "+o);case 14:case"end":return t.stop()}var i}),t,this)})));return function(e,r,n){return t.apply(this,arguments)}}(),e.request=function(){var t=l(b.mark((function t(e,r){var n=this;return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",new Promise((function(t,o){n.rpcClient.request(e,r,(function(e,r){e?o(e):t(r)}))})));case 1:case"end":return t.stop()}}),t)})));return function(e,r){return t.apply(this,arguments)}}(),e.batchRequestWithType=function(){var t=l(b.mark((function t(e,r){var n;return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.batchRequest(e);case 2:return n=t.sent.filter((function(t){return it(t)&&r(t.result)})),t.abrupt("return",n.map((function(t){return t.result})));case 5:case"end":return t.stop()}}),t,this)})));return function(e,r){return t.apply(this,arguments)}}(),e.batchRequest=function(){var t=l(b.mark((function t(e){var r=this;return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",new Promise((function(t,n){0===e.length&&t([]);var o=e.map((function(t){return r.rpcClient.request(t.method,t.args)}));r.rpcClient.request(o,(function(e,r){e?n(e):t(r)}))})));case 1:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}(),t}();function ct(t){return"Exists"!==t.status?void 0:t.details}function at(t){var e=ct(t);if(null!=e)return"moveObject"===e.objectType?e.object.contents:void 0}function st(t){var e=at(t);return null!=e&&(t.details.object.contents=function t(e){var r={};return Object.entries(e.fields).forEach((function(e){var n=e[0],o=e[1];if(_(o)){for(var i=!1,u=0,c=[yt,pt,ht];u<c.length;u++){var a=c[u];if(a.canTransform(o)){r[n]=a.toFieldValue(o),i=!0;break}}i||(r[n]=t(o))}else r[n]=o})),{fields:r,type:e.type}}(e)),t}var ft=function(){function t(){}return t.toFieldValue=function(t){throw new Error("Children classes must override")},t.canTransform=function(t){throw new Error("Children classes must override")},t}(),pt=function(t){function e(){return t.apply(this,arguments)||this}return d(e,t),e.toFieldValue=function(t){var e=t.fields.bytes;switch(t.type){case"0x1::ASCII::String":return e.map((function(t){return String.fromCharCode(t)})).join("");case"0x2::UTF8::String":return function(t){for(var e=[1,1,1,1,2,2,3,0],r=t.length,n="",o=0;o<r;){var i=t[o++];if(128&i){var u=e[i>>3&7];if(!(64&i)||!u||o+u>r)return null;for(i&=63>>u;u>0;u-=1){var c=t[o++];if(128!=(192&c))return null;i=i<<6|63&c}}n+=String.fromCharCode(i)}return n}(new Uint8Array(e))}return t},e.canTransform=function(t){return"0x2::UTF8::String"===t.type||"0x1::ASCII::String"===t.type},e}(ft),ht=function(t){function e(){return t.apply(this,arguments)||this}return d(e,t),e.toFieldValue=function(t){return e.canTransform(t)?t.fields.id.fields.bytes:t},e.canTransform=function(t){return"0x2::ID::UniqueID"===t.type&&_(t.fields.id)&&"0x2::ID::ID"===t.fields.id.type},e}(ft),yt=function(t){function e(){return t.apply(this,arguments)||this}return d(e,t),e.toFieldValue=function(t){return e.canTransform(t)?t.fields.value:t},e.canTransform=function(t){return t.type.startsWith("0x2::Balance::Balance")},e}(ft),lt=function(t){return"number"==typeof t},dt=function(t){function e(e){var r;return(r=t.call(this)||this).endpoint=e,r.client=new ut(e),r}d(e,t);var r=e.prototype;return r.getOwnedObjectRefs=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getOwnedObjects",[e],I);case 3:return t.abrupt("return",t.sent.objects);case 7:throw t.prev=7,t.t0=t.catch(0),new Error("Error fetching owned object refs: "+t.t0+" for address "+e);case 10:case"end":return t.stop()}}),t,this,[[0,7]])})));return function(e){return t.apply(this,arguments)}}(),r.getObjectInfo=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getObjectTypedInfo",[e],C);case 3:return t.abrupt("return",st(t.sent));case 7:throw t.prev=7,t.t0=t.catch(0),new Error("Error fetching object info: "+t.t0+" for id "+e);case 10:case"end":return t.stop()}}),t,this,[[0,7]])})));return function(e){return t.apply(this,arguments)}}(),r.getObjectInfoBatch=function(){var t=l(b.mark((function t(e){var r;return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=e.map((function(t){return{method:"sui_getObjectTypedInfo",args:[t]}})),t.prev=1,t.next=4,this.client.batchRequestWithType(r,C);case 4:return t.abrupt("return",t.sent.map((function(t){return st(t)})));case 8:throw t.prev=8,t.t0=t.catch(1),new Error("Error fetching object info: "+t.t0+" for id "+e);case 11:case"end":return t.stop()}}),t,this,[[1,8]])})));return function(e){return t.apply(this,arguments)}}(),r.getTransactionWithEffects=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getTransaction",[e],$);case 3:return t.abrupt("return",t.sent);case 7:throw t.prev=7,t.t0=t.catch(0),new Error("Error getting transaction with effects: "+t.t0+" for digest "+e);case 10:case"end":return t.stop()}}),t,this,[[0,7]])})));return function(e){return t.apply(this,arguments)}}(),r.getTransactionWithEffectsBatch=function(){var t=l(b.mark((function t(e){var r,n;return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=e.map((function(t){return{method:"sui_getTransaction",args:[t]}})),t.prev=1,t.next=4,this.client.batchRequestWithType(r,$);case 4:return t.abrupt("return",t.sent);case 7:throw t.prev=7,t.t0=t.catch(1),n=e.join(", ").substring(0,-2),new Error("Error getting transaction effects: "+t.t0+" for digests ["+n+"]");case 11:case"end":return t.stop()}}),t,this,[[1,7]])})));return function(e){return t.apply(this,arguments)}}(),r.getTransaction=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getTransaction",[e],$);case 3:return t.abrupt("return",t.sent.certificate);case 7:throw t.prev=7,t.t0=t.catch(0),new Error("Error getting transaction: "+t.t0+" for digest "+e);case 10:case"end":return t.stop()}}),t,this,[[0,7]])})));return function(e){return t.apply(this,arguments)}}(),r.executeTransaction=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_executeTransaction",[e],ot);case 3:return t.abrupt("return",t.sent);case 7:throw t.prev=7,t.t0=t.catch(0),new Error("Error executing transaction: "+t.t0+" for txn "+JSON.stringify(e));case 10:case"end":return t.stop()}}),t,this,[[0,7]])})));return function(e){return t.apply(this,arguments)}}(),r.getTotalTransactionNumber=function(){var t=l(b.mark((function t(){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getTotalTransactionNumber",[],lt);case 3:return t.abrupt("return",t.sent);case 7:throw t.prev=7,t.t0=t.catch(0),new Error("Error fetching total transaction number: "+t.t0);case 10:case"end":return t.stop()}}),t,this,[[0,7]])})));return function(){return t.apply(this,arguments)}}(),r.getTransactionDigestsInRange=function(){var t=l(b.mark((function t(e,r){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getTransactionsInRange",[e,r],H);case 3:return t.abrupt("return",t.sent);case 6:throw t.prev=6,t.t0=t.catch(0),new Error("Error fetching transaction digests in range: "+t.t0+" for range "+e+"-"+r);case 9:case"end":return t.stop()}}),t,this,[[0,6]])})));return function(e,r){return t.apply(this,arguments)}}(),r.getRecentTransactions=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_getRecentTransactions",[e],H);case 3:return t.abrupt("return",t.sent);case 6:throw t.prev=6,t.t0=t.catch(0),new Error("Error fetching recent transactions: "+t.t0+" for count "+e);case 9:case"end":return t.stop()}}),t,this,[[0,6]])})));return function(e){return t.apply(this,arguments)}}(),e}(h),vt=function(){function t(t){this._data="string"==typeof t?new Uint8Array(r.Buffer.from(t,"hex")):t}var e=t.prototype;return e.getData=function(){return this._data},e.getLength=function(){return this._data.length},e.toString=function(){return r.Buffer.from(this._data).toString("hex")},t}(),gt=function(){function t(t){this.client=new ut(t)}return t.prototype.newTransferCoin=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,this.client.requestWithType("sui_transferCoin",[e.signer,e.objectId,e.gasPayment,e.gasBudget,e.recipient],nt);case 3:return t.abrupt("return",new s(t.sent.tx_bytes));case 7:throw t.prev=7,t.t0=t.catch(0),new Error("Error transferring coin: "+t.t0);case 10:case"end":return t.stop()}}),t,this,[[0,7]])})));return function(e){return t.apply(this,arguments)}}(),t}(),wt=function(t){function e(){return t.apply(this,arguments)||this}d(e,t);var r=e.prototype;return r.getOwnedObjectRefs=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("getOwnedObjectRefs");case 1:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),r.getObjectInfo=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("getObjectInfo");case 1:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),r.getTransaction=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("getTransaction");case 1:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),r.executeTransaction=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("executeTransaction");case 1:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),r.getTotalTransactionNumber=function(){var t=l(b.mark((function t(){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("getTotalTransactionNumber");case 1:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),r.getTransactionDigestsInRange=function(){var t=l(b.mark((function t(e,r){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("getTransactionDigestsInRange");case 1:case"end":return t.stop()}}),t,this)})));return function(e,r){return t.apply(this,arguments)}}(),r.getRecentTransactions=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.newError("getRecentTransactions");case 1:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),r.newError=function(t){return new Error("Please use a valid provider for "+t)},e}(h),bt=function(){function t(t,e){this.provider=t||new wt;var r="";this.provider instanceof dt&&(r=this.provider.endpoint),this.serializer=e||new gt(r)}var e=t.prototype;return e.signAndExecuteTransaction=function(){var t=l(b.mark((function t(e){var r;return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.signData(e);case 2:return r=t.sent,t.next=5,this.provider.executeTransaction({tx_bytes:e.toString(),signature:r.signature.toString(),pub_key:r.pubKey.toString()});case 5:return t.abrupt("return",t.sent);case 6:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),e.transferCoin=function(){var t=l(b.mark((function t(e){var r;return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.serializer.newTransferCoin(e);case 2:return r=t.sent,t.next=5,this.signAndExecuteTransaction(r);case 5:return t.abrupt("return",t.sent);case 6:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),t}(),xt=function(t){function e(e,r,n){var o;return(o=t.call(this,r,n)||this).keypair=e,o}d(e,t);var r=e.prototype;return r.getAddress=function(){var t=l(b.mark((function t(){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:throw this.keypair.getPublicKey().toSuiAddress();case 1:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),r.signData=function(){var t=l(b.mark((function t(e){return b.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",{signature:this.keypair.signData(e),pubKey:this.keypair.getPublicKey()});case 1:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),r.connect=function(t){return new e(this.keypair,t)},e}(bt);function mt(t){return"Single"in t.kind?t.kind.Single:void 0}function jt(t){return Tt(t).gas_cost}function Tt(t){return"Success"in t?t.Success:"Failure"in t?t.Failure:(console.error("Unrecognized ExecutionStatus:",t),t[Object.keys(t)[0]])}var Et=function(){function t(t){this.bytePosition=0,this.dataView=new DataView(t.buffer)}var e=t.prototype;return e.shift=function(t){return this.bytePosition+=t,this},e.read8=function(){var t=this.dataView.getUint8(this.bytePosition);return this.shift(1),new n.BN(t,10)},e.read16=function(){var t=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),new n.BN(t,10)},e.read32=function(){var t=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),new n.BN(t,10)},e.read64=function(){var t=this.read32(),e=this.read32().toString(16)+t.toString(16).padStart(8,"0");return new n.BN(e,16)},e.read128=function(){var t=this.read64(),e=this.read64().toString(16)+t.toString(16).padStart(8,"0");return new n.BN(e,16)},e.readBytes=function(t){var e=new Uint8Array(this.dataView.buffer,this.bytePosition+this.dataView.byteOffset,t);return this.shift(t),e},e.readULEB=function(){var t=function(t){for(var e=0,r=0,n=0;;){var o=t[n];if(n+=1,e|=(127&o)<<r,0==(128&o))break;r+=7}return{value:e,length:n}}(new Uint8Array(this.dataView.buffer,this.bytePosition+this.dataView.byteOffset)),e=t.value;return this.shift(t.length),e},e.readVec=function(t){for(var e=this.readULEB(),r=[],n=0;n<e;n++)r.push(t(this,n,e));return r},t}(),St=function(){function t(t){void 0===t&&(t=1024),this.bytePosition=0,this.dataView=new DataView(new ArrayBuffer(t))}t.toBN=function(t){switch(typeof t){case"bigint":return new n.BN(t.toString());default:return new n.BN(t)}};var e=t.prototype;return e.shift=function(t){return this.bytePosition+=t,this},e.write8=function(e){return this.dataView.setUint8(this.bytePosition,+t.toBN(e)),this.shift(1)},e.write16=function(e){return this.dataView.setUint16(this.bytePosition,+t.toBN(e),!0),this.shift(2)},e.write32=function(e){return this.dataView.setUint32(this.bytePosition,+t.toBN(e),!0),this.shift(4)},e.write64=function(e){var r=this;return t.toBN(e).toArray("le",8).forEach((function(t){return r.write8(t)})),this},e.write128=function(e){var r=this;return t.toBN(e).toArray("le",16).forEach((function(t){return r.write8(t)})),this},e.writeULEB=function(t){var e=this;return function(t){var e=[],r=0;if(0===t)return[0];for(;t>0;)e[r]=127&t,(t>>=7)&&(e[r]|=128),r+=1;return e}(t).forEach((function(t){return e.write8(t)})),this},e.writeVec=function(t,e){var r=this;return this.writeULEB(t.length),Array.from(t).forEach((function(n,o){return e(r,n,o,t.length)})),this},e.toBytes=function(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))},e.toString=function(t){switch(t){case"base64":return new s(this.toBytes()).toString();case"hex":return new vt(this.toBytes()).toString();default:throw new Error("Unsupported encoding, supported values are: base64, hex")}},t}(),_t=function(){function t(){}return t.set=function(t,e,r){return void 0===r&&(r=1024),this.getTypeInterface(t).encode(e,r)},t.de=function(t,e){return this.getTypeInterface(t).decode(e)},t.hasType=function(t){return this.types.has(t)},t.registerType=function(t,e,r,n){return void 0===n&&(n=function(){return!0}),this.types.set(t,{encode:function(t,e){return void 0===e&&(e=1024),this._encodeRaw(new St(e),t)},decode:function(t){return this._decodeRaw(new Et(t))},_encodeRaw:function(r,o){if(n(o))return e(r,o);throw new Error("Validation failed for type "+t+", data: "+o)},_decodeRaw:function(t){return r(t)}}),this},t.registerAddressType=function(t,e){return this.registerType(t,(function(t,e){return new vt(e).getData().reduce((function(t,e){return t.write8(e)}),t)}),(function(t){return new vt(t.readBytes(e)).toString()}))},t.registerVectorType=function(e,r){return this.registerType(e,(function(e,n){return e.writeVec(n,(function(e,n){return t.getTypeInterface(r)._encodeRaw(e,n)}))}),(function(e){return e.readVec((function(e){return t.getTypeInterface(r)._decodeRaw(e)}))}))},t.registerStructType=function(e,r){var n=Object.freeze(r),o=Object.keys(n);return this.registerType(e,(function(e,r){for(var i,u=g(o);!(i=u()).done;){var c=i.value;t.getTypeInterface(n[c])._encodeRaw(e,r[c])}return e}),(function(e){for(var r,i={},u=g(o);!(r=u()).done;){var c=r.value;i[c]=t.getTypeInterface(n[c])._decodeRaw(e)}return i}))},t.registerEnumType=function(e,r){var n=Object.freeze(r),o=Object.keys(n);return this.registerType(e,(function(r,i){var u=Object.keys(i)[0];if(void 0===u)throw new Error("Unknown invariant of the enum "+e);var c=o.indexOf(u);if(-1===c)throw new Error("Unknown invariant of the enum "+e+", allowed values: "+o);var a=n[o[c]];return r.write8(c),null!==a?t.getTypeInterface(a)._encodeRaw(r,i[u]):r}),(function(r){var i,u=r.readULEB(),c=o[u],a=n[c];if(-1===u)throw new Error("Decoding type mismatch, expected enum "+e+" invariant index, received "+u);return(i={})[c]=null===a||t.getTypeInterface(a)._decodeRaw(r),i}))},t.getTypeInterface=function(e){var r=t.types.get(e);if(void 0===r)throw new Error("Type "+e+" is not registered");return r},t}();_t.U8="u8",_t.U32="u32",_t.U64="u64",_t.U128="u128",_t.BOOL="bool",_t.VECTOR="vector",_t.ADDRESS="address",_t.STRING="string",_t.types=new Map,_t.registerType(_t.U8,(function(t,e){return t.write8(e)}),(function(t){return t.read8()}),(function(t){return t<256})),_t.registerType(_t.U32,(function(t,e){return t.write32(e)}),(function(t){return t.read32()}),(function(t){return t<4294967296})),_t.registerType(_t.U64,(function(t,e){return t.write64(e)}),(function(t){return t.read64()}),(function(t){return!0})),_t.registerType(_t.U128,(function(t,e){return t.write128(e)}),(function(t){return t.read128()}),(function(t){return!0})),_t.registerType(_t.BOOL,(function(t,e){return t.write8(e)}),(function(t){return"1"==t.read8().toString(10)}),(function(t){return!0})),_t.registerType(_t.STRING,(function(t,e){return t.writeVec(Array.from(e),(function(t,e){return t.write8(e.charCodeAt(0))}))}),(function(t){return t.readVec((function(t){return t.read8()})).map((function(t){return String.fromCharCode(t)})).join("")}),(function(t){return/^[\x00-\x7F]*$/.test(t)})),exports.BCS={__proto__:null,BcsReader:Et,BcsWriter:St,BCS:_t},exports.Base64DataBuffer=s,exports.Ed25519Keypair=p,exports.HexDataBuffer=vt,exports.JsonRpcProvider=dt,exports.PUBLIC_KEY_SIZE=32,exports.Provider=h,exports.PublicKey=f,exports.RawSigner=xt,exports.RpcTxnDataSerializer=gt,exports.SignerWithProvider=bt,exports.getExecutionDetails=Tt,exports.getExecutionStatusType=function(t){return Object.keys(t)[0]},exports.getGasSummary=jt,exports.getMoveCallTransaction=function(t){var e=mt(t);return e&&"Call"in e?e.Call:void 0},exports.getMovePackageContent=function(t){var e=ct(t);if(null!=e)return"movePackage"===e.objectType?e.object.contents:void 0},exports.getObjectContent=at,exports.getObjectExistsResponse=ct,exports.getObjectType=function(t){var e;return null==(e=ct(t))?void 0:e.objectType},exports.getPublishTransaction=function(t){var e=mt(t);return e&&"Publish"in e?e.Publish:void 0},exports.getSingleTransactionKind=mt,exports.getTotalGasUsed=function(t){var e=jt(t);return e?e.computation_cost+e.storage_cost-e.storage_rebate:0},exports.getTransactionKind=function(t){var e=mt(t);return e&&Object.keys(e)[0]},exports.getTransferTransaction=function(t){var e=mt(t);return e&&"Transfer"in e?e.Transfer:void 0},exports.isAuthorityName=function(t,e){return"string"==typeof t},exports.isAuthorityQuorumSignInfo=F,exports.isAuthoritySignature=function(t,e){return"string"==typeof t},exports.isCertifiedTransaction=W,exports.isEd25519KeypairData=function(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&t.publicKey instanceof Uint8Array&&t.secretKey instanceof Uint8Array},exports.isEmptySignInfo=function(t,e){return"object"==typeof t},exports.isEpochId=function(t,e){return"number"==typeof t},exports.isEvent=Z,exports.isExecutionStatus=M,exports.isExecutionStatusDetail=z,exports.isExecutionStatusType=function(t,e){return"Success"===t||"Failure"===t},exports.isGasCostSummary=G,exports.isGatewayTxSeqNumber=function(t,e){return"number"==typeof t},exports.isGetObjectInfoResponse=C,exports.isGetOwnedObjectRefsResponse=I,exports.isGetTxnDigestsResponse=H,exports.isKeypair=function(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&"function"==typeof t.getPublicKey&&"function"==typeof t.signData},exports.isMoveCall=et,exports.isMoveCallArg=rt,exports.isMoveModulePublish=Q,exports.isMovePackageContent=A,exports.isMoveTypeTag=tt,exports.isObjectContent=_,exports.isObjectContentField=E,exports.isObjectContentFields=S,exports.isObjectDigest=function(t,e){return"string"==typeof t},exports.isObjectExistsInfo=k,exports.isObjectId=function(t,e){return"string"==typeof t},exports.isObjectNotExistsInfo=B,exports.isObjectOwner=j,exports.isObjectRef=T,exports.isObjectStatus=P,exports.isObjectType=R,exports.isOwnedObjectRef=J,exports.isPublicKeyData=x,exports.isPublicKeyInitData=function(t,e){return m(t)||L(t)||t instanceof Buffer||t instanceof Uint8Array||Array.isArray(t)&&t.every((function(t){return L(t)}))||x(t)},exports.isRawAuthoritySignInfo=D,exports.isRawObjectRef=U,exports.isSequenceNumber=L,exports.isSignedTransaction=function(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&m(t.tx_bytes)&&m(t.signature)&&m(t.pub_key)},exports.isSingleTransactionKind=q,exports.isStructTag=X,exports.isSuiAddress=function(t,e){return"string"==typeof t},exports.isSuiObject=O,exports.isTransactionBytes=nt,exports.isTransactionData=K,exports.isTransactionDigest=m,exports.isTransactionEffects=Y,exports.isTransactionEffectsResponse=$,exports.isTransactionKind=V,exports.isTransactionKindName=function(t,e){return"Transfer"===t||"Publish"===t||"Call"===t},exports.isTransactionResponse=ot,exports.isTransfer=N,exports.isTransferCoinTransaction=function(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&m(t.signer)&&m(t.objectId)&&m(t.gasPayment)&&L(t.gasBudget)&&m(t.recipient)},exports.isTxnDataSerializer=function(t,e){return(null!==t&&"object"==typeof t||"function"==typeof t)&&"function"==typeof t.newTransferCoin}; | ||
//# sourceMappingURL=sui.js.cjs.production.min.js.map |
@@ -107,2 +107,13 @@ import { ObjectOwner, SuiAddress, TransactionDigest } from './common'; | ||
export declare type AuthoritySignature = string; | ||
export declare type TransactionBytes = { | ||
tx_bytes: string; | ||
}; | ||
export declare type TransactionResponse = { | ||
EffectResponse: TransactionEffectsResponse; | ||
}; | ||
export declare type SignedTransaction = { | ||
tx_bytes: string; | ||
signature: string; | ||
pub_key: string; | ||
}; | ||
export declare function getSingleTransactionKind(data: TransactionData): SingleTransactionKind | undefined; | ||
@@ -109,0 +120,0 @@ export declare function getTransferTransaction(data: TransactionData): Transfer | undefined; |
{ | ||
"version": "0.1.1", | ||
"version": "0.1.2", | ||
"license": "Apache-2.0", | ||
@@ -70,2 +70,3 @@ "main": "dist/index.js", | ||
"jayson": "^3.6.6", | ||
"js-sha3": "^0.8.0", | ||
"tweetnacl": "^1.0.3", | ||
@@ -72,0 +73,0 @@ "util": "^0.12.4" |
@@ -21,9 +21,9 @@ # Sui TypeScript SDK | ||
Fetch objects owned by the address `C5206DD02C86A510C4848516229B02ADDFACBE55` | ||
Fetch objects owned by the address `0xbff6ccc8707aa517b4f1b95750a2a8c666012df3` | ||
```typescript | ||
import { JsonRpcProvider } from '@mysten/sui.js'; | ||
const provider = new JsonRpcProvider('http://127.0.0.1:5001/'); | ||
const provider = new JsonRpcProvider('https://gateway.devnet.sui.io:9000/'); | ||
const objects = await provider.getOwnedObjectRefs( | ||
'C5206DD02C86A510C4848516229B02ADDFACBE55' | ||
'0xbff6ccc8707aa517b4f1b95750a2a8c666012df3' | ||
); | ||
@@ -36,3 +36,3 @@ ``` | ||
import { JsonRpcProvider } from '@mysten/sui.js'; | ||
const provider = new JsonRpcProvider('http://127.0.0.1:5001/'); | ||
const provider = new JsonRpcProvider('https://gateway.devnet.sui.io:9000/'); | ||
const txn = await provider.getTransaction( | ||
@@ -45,6 +45,22 @@ '6mn5W1CczLwitHCO9OIUbqirNrQ0cuKdyxaNe16SAME=' | ||
To transfer a Coin<SUI>: | ||
```typescript | ||
import { Ed25519Keypair, JsonRpcProvider, RawSigner } from '@mysten/sui.js'; | ||
// Generate a new Keypair | ||
const keypair = new Ed25519Keypair(); | ||
const signer = new RawSigner( | ||
keypair, | ||
new JsonRpcProvider('https://gateway.devnet.sui.io:9000/') | ||
); | ||
const txn = await signer.transferCoin({ | ||
signer: keypair.getPublicKey().toSuiAddress(), | ||
objectId: '0x5015b016ab570df14c87649eda918e09e5cc61e0', | ||
gasPayment: '0x0a8c2a0fd59bf41678b2e22c3dd2b84425fb3673', | ||
gasBudget: 10000, | ||
recipient: '0xBFF6CCC8707AA517B4F1B95750A2A8C666012DF3', | ||
}); | ||
``` | ||
To sign a raw message: | ||
TODO | ||
To transfer a Coin<SUI>: | ||
TODO |
1199
src/bcs/index.ts
@@ -14,3 +14,3 @@ // Copyright (c) 2022, Mysten Labs, Inc. | ||
import * as BN from 'bn.js' | ||
import * as BN from 'bn.js'; | ||
import { HexDataBuffer as HEX } from '../serialization/hex'; | ||
@@ -50,112 +50,111 @@ import { Base64DataBuffer as B64 } from '../serialization/base64'; | ||
export class BcsReader { | ||
private dataView: DataView; | ||
private bytePosition: number = 0; | ||
private dataView: DataView; | ||
private bytePosition: number = 0; | ||
/** | ||
* @param {Uint8Array} data Data to use as a buffer. | ||
*/ | ||
constructor(data: Uint8Array) { | ||
this.dataView = new DataView(data.buffer); | ||
} | ||
/** | ||
* Shift current cursor position by `bytes`. | ||
* | ||
* @param {Number} bytes Number of bytes to | ||
* @returns {this} Self for possible chaining. | ||
*/ | ||
shift(bytes: number) { | ||
this.bytePosition += bytes; | ||
return this; | ||
} | ||
/** | ||
* Read U8 value from the buffer and shift cursor by 1. | ||
* @returns | ||
*/ | ||
read8(): BN { | ||
let value = this.dataView.getUint8(this.bytePosition); | ||
this.shift(1); | ||
return new BN.BN(value, 10); | ||
} | ||
/** | ||
* Read U16 value from the buffer and shift cursor by 2. | ||
* @returns | ||
*/ | ||
read16(): BN { | ||
let value = this.dataView.getUint16(this.bytePosition, true); | ||
this.shift(2); | ||
return new BN.BN(value, 10); | ||
} | ||
/** | ||
* Read U32 value from the buffer and shift cursor by 4. | ||
* @returns | ||
*/ | ||
read32(): BN { | ||
let value = this.dataView.getUint32(this.bytePosition, true); | ||
this.shift(4); | ||
return new BN.BN(value, 10); | ||
} | ||
/** | ||
* Read U64 value from the buffer and shift cursor by 8. | ||
* @returns | ||
*/ | ||
read64(): BN { | ||
let value1 = this.read32(); | ||
let value2 = this.read32(); | ||
let result = value2.toString(16) + value1.toString(16).padStart(8, '0'); | ||
/** | ||
* @param {Uint8Array} data Data to use as a buffer. | ||
*/ | ||
constructor(data: Uint8Array) { | ||
this.dataView = new DataView(data.buffer); | ||
} | ||
/** | ||
* Shift current cursor position by `bytes`. | ||
* | ||
* @param {Number} bytes Number of bytes to | ||
* @returns {this} Self for possible chaining. | ||
*/ | ||
shift(bytes: number) { | ||
this.bytePosition += bytes; | ||
return this; | ||
} | ||
/** | ||
* Read U8 value from the buffer and shift cursor by 1. | ||
* @returns | ||
*/ | ||
read8(): BN { | ||
let value = this.dataView.getUint8(this.bytePosition); | ||
this.shift(1); | ||
return new BN.BN(value, 10); | ||
} | ||
/** | ||
* Read U16 value from the buffer and shift cursor by 2. | ||
* @returns | ||
*/ | ||
read16(): BN { | ||
let value = this.dataView.getUint16(this.bytePosition, true); | ||
this.shift(2); | ||
return new BN.BN(value, 10); | ||
} | ||
/** | ||
* Read U32 value from the buffer and shift cursor by 4. | ||
* @returns | ||
*/ | ||
read32(): BN { | ||
let value = this.dataView.getUint32(this.bytePosition, true); | ||
this.shift(4); | ||
return new BN.BN(value, 10); | ||
} | ||
/** | ||
* Read U64 value from the buffer and shift cursor by 8. | ||
* @returns | ||
*/ | ||
read64(): BN { | ||
let value1 = this.read32(); | ||
let value2 = this.read32(); | ||
let result = value2.toString(16) + value1.toString(16).padStart(8, '0'); | ||
return new BN.BN(result, 16); | ||
} | ||
/** | ||
* Read U128 value from the buffer and shift cursor by 16. | ||
* @returns | ||
*/ | ||
read128(): BN { | ||
let value1 = this.read64(); | ||
let value2 = this.read64(); | ||
let result = value2.toString(16) + value1.toString(16).padStart(8, '0'); | ||
return new BN.BN(result, 16); | ||
} | ||
/** | ||
* Read U128 value from the buffer and shift cursor by 16. | ||
* @returns | ||
*/ | ||
read128(): BN { | ||
let value1 = this.read64(); | ||
let value2 = this.read64(); | ||
let result = value2.toString(16) + value1.toString(16).padStart(8, '0'); | ||
return new BN.BN(result, 16); | ||
} | ||
/** | ||
* Read `num` number of bytes from the buffer and shift cursor by `num`. | ||
* @param num Number of bytes to read. | ||
* @returns Selected Buffer. | ||
*/ | ||
readBytes(num: number): Uint8Array { | ||
let start = this.bytePosition + this.dataView.byteOffset; | ||
let value = new Uint8Array(this.dataView.buffer, start, num); | ||
return new BN.BN(result, 16); | ||
} | ||
/** | ||
* Read `num` number of bytes from the buffer and shift cursor by `num`. | ||
* @param num Number of bytes to read. | ||
* @returns Selected Buffer. | ||
*/ | ||
readBytes(num: number): Uint8Array { | ||
let start = this.bytePosition + this.dataView.byteOffset; | ||
let value = new Uint8Array(this.dataView.buffer, start, num); | ||
this.shift(num); | ||
this.shift(num); | ||
return value; | ||
} | ||
/** | ||
* Read ULEB value - an integer of varying size. Used for enum indexes and | ||
* vector lengths. | ||
* @returns {Number} The ULEB value. | ||
*/ | ||
readULEB(): number { | ||
let start = this.bytePosition + this.dataView.byteOffset; | ||
let buffer = new Uint8Array(this.dataView.buffer, start); | ||
let { value, length } = ulebDecode(buffer); | ||
return value; | ||
} | ||
/** | ||
* Read ULEB value - an integer of varying size. Used for enum indexes and | ||
* vector lengths. | ||
* @returns {Number} The ULEB value. | ||
*/ | ||
readULEB(): number { | ||
let start = this.bytePosition + this.dataView.byteOffset; | ||
let buffer = new Uint8Array(this.dataView.buffer, start); | ||
let { value, length } = ulebDecode(buffer); | ||
this.shift(length); | ||
this.shift(length); | ||
return value; | ||
return value; | ||
} | ||
/** | ||
* Read a BCS vector: read a length and then apply function `cb` X times | ||
* where X is the length of the vector, defined as ULEB in BCS bytes. | ||
* @param cb Callback to process elements of vector. | ||
* @returns {Array<Any>} Array of the resulting values, returned by callback. | ||
*/ | ||
readVec(cb: (reader: BcsReader, i: number, length: number) => any): any[] { | ||
let length = this.readULEB(); | ||
let result = []; | ||
for (let i = 0; i < length; i++) { | ||
result.push(cb(this, i, length)); | ||
} | ||
/** | ||
* Read a BCS vector: read a length and then apply function `cb` X times | ||
* where X is the length of the vector, defined as ULEB in BCS bytes. | ||
* @param cb Callback to process elements of vector. | ||
* @returns {Array<Any>} Array of the resulting values, returned by callback. | ||
*/ | ||
readVec(cb: (reader: BcsReader, i: number, length: number) => any): any[] { | ||
let length = this.readULEB(); | ||
let result = []; | ||
for (let i = 0; i < length; i++) { | ||
result.push(cb(this, i, length)); | ||
} | ||
return result; | ||
} | ||
return result; | ||
} | ||
} | ||
@@ -177,129 +176,138 @@ | ||
export class BcsWriter { | ||
private dataView: DataView; | ||
private bytePosition: number = 0; | ||
private dataView: DataView; | ||
private bytePosition: number = 0; | ||
/** | ||
* @param {Number} [size=1024] Size of the buffer to reserve for serialization. | ||
*/ | ||
constructor(size = 1024) { | ||
this.dataView = new DataView(new ArrayBuffer(size)); | ||
} | ||
/** | ||
* @param {Number} [size=1024] Size of the buffer to reserve for serialization. | ||
*/ | ||
constructor(size = 1024) { | ||
this.dataView = new DataView(new ArrayBuffer(size)); | ||
/** | ||
* Unify argument types by converting them to BN. | ||
*/ | ||
static toBN(number: number | BN | bigint | string): BN { | ||
switch (typeof number) { | ||
case 'bigint': | ||
return new BN.BN(number.toString()); | ||
default: | ||
return new BN.BN(number); | ||
} | ||
} | ||
/** | ||
* Unify argument types by converting them to BN. | ||
*/ | ||
static toBN(number: number | BN | bigint | string): BN { | ||
switch (typeof number) { | ||
case 'bigint': return new BN.BN(number.toString()); | ||
default: return new BN.BN(number); | ||
} | ||
} | ||
/** | ||
* Shift current cursor position by `bytes`. | ||
* | ||
* @param {Number} bytes Number of bytes to | ||
* @returns {this} Self for possible chaining. | ||
*/ | ||
shift(bytes: number): this { | ||
this.bytePosition += bytes; | ||
return this; | ||
} | ||
/** | ||
* Write a U8 value into a buffer and shift cursor position by 1. | ||
* @param {Number} value Value to write. | ||
* @returns {this} | ||
*/ | ||
write8(value: number | bigint | BN): this { | ||
this.dataView.setUint8(this.bytePosition, +BcsWriter.toBN(value)); | ||
return this.shift(1); | ||
} | ||
/** | ||
* Write a U16 value into a buffer and shift cursor position by 2. | ||
* @param {Number} value Value to write. | ||
* @returns {this} | ||
*/ | ||
write16(value: number | bigint | BN): this { | ||
this.dataView.setUint16(this.bytePosition, +BcsWriter.toBN(value), true); | ||
return this.shift(2); | ||
} | ||
/** | ||
* Write a U32 value into a buffer and shift cursor position by 4. | ||
* @param {Number} value Value to write. | ||
* @returns {this} | ||
*/ | ||
write32(value: number | bigint | BN): this { | ||
this.dataView.setUint32(this.bytePosition, +BcsWriter.toBN(value), true); | ||
return this.shift(4); | ||
} | ||
/** | ||
* Write a U64 value into a buffer and shift cursor position by 8. | ||
* @param {bigint} value Value to write. | ||
* @returns {this} | ||
*/ | ||
write64(value: bigint | BN): this { | ||
BcsWriter.toBN(value) | ||
.toArray('le', 8) | ||
.forEach(el => this.write8(el)); | ||
/** | ||
* Shift current cursor position by `bytes`. | ||
* | ||
* @param {Number} bytes Number of bytes to | ||
* @returns {this} Self for possible chaining. | ||
*/ | ||
shift(bytes: number): this { | ||
this.bytePosition += bytes; | ||
return this; | ||
} | ||
/** | ||
* Write a U8 value into a buffer and shift cursor position by 1. | ||
* @param {Number} value Value to write. | ||
* @returns {this} | ||
*/ | ||
write8(value: number | bigint | BN): this { | ||
this.dataView.setUint8(this.bytePosition, +BcsWriter.toBN(value)); | ||
return this.shift(1); | ||
} | ||
/** | ||
* Write a U16 value into a buffer and shift cursor position by 2. | ||
* @param {Number} value Value to write. | ||
* @returns {this} | ||
*/ | ||
write16(value: number | bigint | BN): this { | ||
this.dataView.setUint16(this.bytePosition, +BcsWriter.toBN(value), true); | ||
return this.shift(2); | ||
} | ||
/** | ||
* Write a U32 value into a buffer and shift cursor position by 4. | ||
* @param {Number} value Value to write. | ||
* @returns {this} | ||
*/ | ||
write32(value: number | bigint | BN): this { | ||
this.dataView.setUint32(this.bytePosition, +BcsWriter.toBN(value), true); | ||
return this.shift(4); | ||
} | ||
/** | ||
* Write a U64 value into a buffer and shift cursor position by 8. | ||
* @param {bigint} value Value to write. | ||
* @returns {this} | ||
*/ | ||
write64(value: bigint | BN): this { | ||
BcsWriter.toBN(value) | ||
.toArray('le', 8) | ||
.forEach((el) => this.write8(el)); | ||
return this; | ||
} | ||
/** | ||
* Write a U128 value into a buffer and shift cursor position by 16. | ||
* | ||
* @unimplemented | ||
* @param {bigint} value Value to write. | ||
* @returns {this} | ||
*/ | ||
write128(value: bigint | BN): this { | ||
BcsWriter.toBN(value) | ||
.toArray('le', 16) | ||
.forEach(el => this.write8(el)); | ||
return this; | ||
} | ||
/** | ||
* Write a U128 value into a buffer and shift cursor position by 16. | ||
* | ||
* @unimplemented | ||
* @param {bigint} value Value to write. | ||
* @returns {this} | ||
*/ | ||
write128(value: bigint | BN): this { | ||
BcsWriter.toBN(value) | ||
.toArray('le', 16) | ||
.forEach((el) => this.write8(el)); | ||
return this; | ||
} | ||
/** | ||
* Write a ULEB value into a buffer and shift cursor position by number of bytes | ||
* written. | ||
* @param {Number} value Value to write. | ||
* @returns {this} | ||
*/ | ||
writeULEB(value: number): this { | ||
ulebEncode(value).forEach(el => this.write8(el)); | ||
return this; | ||
} | ||
/** | ||
* Write a vector into a buffer by first writing the vector length and then calling | ||
* a callback on each passed value. | ||
* | ||
* @param {Array<Any>} vector Array of elements to write. | ||
* @param {WriteVecCb} cb Callback to call on each element of the vector. | ||
* @returns {this} | ||
*/ | ||
writeVec( | ||
vector: Array<any>, | ||
cb: (writer: BcsWriter, el: any, i: number, len: number) => {} | ||
): this { | ||
this.writeULEB(vector.length); | ||
Array.from(vector).forEach((el, i) => cb(this, el, i, vector.length)); | ||
return this; | ||
} | ||
return this; | ||
} | ||
/** | ||
* Write a ULEB value into a buffer and shift cursor position by number of bytes | ||
* written. | ||
* @param {Number} value Value to write. | ||
* @returns {this} | ||
*/ | ||
writeULEB(value: number): this { | ||
ulebEncode(value).forEach((el) => this.write8(el)); | ||
return this; | ||
} | ||
/** | ||
* Write a vector into a buffer by first writing the vector length and then calling | ||
* a callback on each passed value. | ||
* | ||
* @param {Array<Any>} vector Array of elements to write. | ||
* @param {WriteVecCb} cb Callback to call on each element of the vector. | ||
* @returns {this} | ||
*/ | ||
writeVec(vector: Array<any>, cb: (writer: BcsWriter, el: any, i: number, len: number) => {}): this { | ||
this.writeULEB(vector.length); | ||
Array.from(vector).forEach((el, i) => cb(this, el, i, vector.length)); | ||
return this; | ||
} | ||
/** | ||
* Get underlying buffer taking only value bytes (in case initial buffer size was bigger). | ||
* @returns {Uint8Array} Resulting BCS. | ||
*/ | ||
toBytes() { | ||
return new Uint8Array(this.dataView.buffer.slice(0, this.bytePosition)); | ||
} | ||
/** | ||
* Get underlying buffer taking only value bytes (in case initial buffer size was bigger). | ||
* @returns {Uint8Array} Resulting BCS. | ||
*/ | ||
toBytes() { | ||
return new Uint8Array(this.dataView.buffer.slice(0, this.bytePosition)); | ||
/** | ||
* Represent data as 'hex' or 'base64' | ||
* @param encoding Encoding to use: 'base64' or 'hex' | ||
*/ | ||
toString(encoding: string): string { | ||
switch (encoding) { | ||
case 'base64': | ||
return new B64(this.toBytes()).toString(); | ||
case 'hex': | ||
return new HEX(this.toBytes()).toString(); | ||
default: | ||
throw new Error( | ||
'Unsupported encoding, supported values are: base64, hex' | ||
); | ||
} | ||
/** | ||
* Represent data as 'hex' or 'base64' | ||
* @param encoding Encoding to use: 'base64' or 'hex' | ||
*/ | ||
toString(encoding: string): string { | ||
switch (encoding) { | ||
case 'base64': return new B64(this.toBytes()).toString(); | ||
case 'hex': return new HEX(this.toBytes()).toString(); | ||
default: throw new Error('Unsupported encoding, supported values are: base64, hex'); | ||
} | ||
} | ||
} | ||
} | ||
@@ -310,18 +318,18 @@ | ||
function ulebEncode(num: number): Array<number> { | ||
let arr = []; | ||
let len = 0; | ||
let arr = []; | ||
let len = 0; | ||
if (num === 0) { | ||
return [0]; | ||
} | ||
if (num === 0) { | ||
return [0]; | ||
} | ||
while (num > 0) { | ||
arr[len] = num & 0x7F; | ||
if (num >>= 7) { | ||
arr[len] |= 0x80 | ||
}; | ||
len += 1; | ||
while (num > 0) { | ||
arr[len] = num & 0x7f; | ||
if ((num >>= 7)) { | ||
arr[len] |= 0x80; | ||
} | ||
len += 1; | ||
} | ||
return arr; | ||
return arr; | ||
} | ||
@@ -331,21 +339,23 @@ | ||
// Original code is taken from: https://www.npmjs.com/package/uleb128 (no longer exists) | ||
function ulebDecode(arr: Array<number> | Uint8Array): { value: number, length: number } { | ||
let total = 0; | ||
let shift = 0; | ||
let len = 0; | ||
function ulebDecode( | ||
arr: Array<number> | Uint8Array | ||
): { value: number; length: number } { | ||
let total = 0; | ||
let shift = 0; | ||
let len = 0; | ||
while (true) { | ||
let byte = arr[len]; | ||
len += 1; | ||
total |= ((byte & 0x7F) << shift); | ||
if ((byte & 0x80) === 0) { | ||
break; | ||
} | ||
shift += 7; | ||
while (true) { | ||
let byte = arr[len]; | ||
len += 1; | ||
total |= (byte & 0x7f) << shift; | ||
if ((byte & 0x80) === 0) { | ||
break; | ||
} | ||
shift += 7; | ||
} | ||
return { | ||
value: total, | ||
length: len | ||
}; | ||
return { | ||
value: total, | ||
length: len, | ||
}; | ||
} | ||
@@ -358,7 +368,7 @@ | ||
interface TypeInterface { | ||
encode: (data: any, size: number) => BcsWriter, | ||
decode: (data: Uint8Array) => any, | ||
encode: (data: any, size: number) => BcsWriter; | ||
decode: (data: Uint8Array) => any; | ||
_encodeRaw: (writer: BcsWriter, data: any) => BcsWriter, | ||
_decodeRaw: (reader: BcsReader) => any | ||
_encodeRaw: (writer: BcsWriter, data: any) => BcsWriter; | ||
_decodeRaw: (reader: BcsReader) => any; | ||
} | ||
@@ -370,364 +380,387 @@ | ||
export class BCS { | ||
// Prefefined types constants | ||
static readonly U8: string = 'u8'; | ||
static readonly U32: string = 'u32'; | ||
static readonly U64: string = 'u64'; | ||
static readonly U128: string = 'u128'; | ||
static readonly BOOL: string = 'bool'; | ||
static readonly VECTOR: string = 'vector'; | ||
static readonly ADDRESS: string = 'address'; | ||
static readonly STRING: string = 'string'; | ||
// Prefefined types constants | ||
static readonly U8: string = 'u8'; | ||
static readonly U32: string = 'u32'; | ||
static readonly U64: string = 'u64'; | ||
static readonly U128: string = 'u128'; | ||
static readonly BOOL: string = 'bool'; | ||
static readonly VECTOR: string = 'vector'; | ||
static readonly ADDRESS: string = 'address'; | ||
static readonly STRING: string = 'string'; | ||
private static types: Map<string, TypeInterface> = new Map(); | ||
private static types: Map<string, TypeInterface> = new Map(); | ||
/** | ||
* Serialize data into BCS. | ||
* | ||
* @example | ||
* BCS.registerVectorType('vector<u8>', 'u8'); | ||
* | ||
* let serialized = BCS | ||
* .set('vector<u8>', [1,2,3,4,5,6]) | ||
* .toBytes(); | ||
* | ||
* console.assert(BCS.util.toHex(serialized) === '06010203040506'); | ||
* | ||
* @param type Name of the type to serialize (must be registered). | ||
* @param data Data to serialize. | ||
* @param size Serialization buffer size. Default 1024 = 1KB. | ||
* @return A BCS reader instance. Usually you'd want to call `.toBytes()` | ||
*/ | ||
public static set(type: string, data: any, size: number = 1024): BcsWriter { | ||
return this.getTypeInterface(type).encode(data, size); | ||
} | ||
/** | ||
* Serialize data into BCS. | ||
* | ||
* @example | ||
* BCS.registerVectorType('vector<u8>', 'u8'); | ||
* | ||
* let serialized = BCS | ||
* .ser('vector<u8>', [1,2,3,4,5,6]) | ||
* .toBytes(); | ||
* | ||
* console.assert(BCS.util.toHex(serialized) === '06010203040506'); | ||
* | ||
* @param type Name of the type to serialize (must be registered). | ||
* @param data Data to serialize. | ||
* @param size Serialization buffer size. Default 1024 = 1KB. | ||
* @return A BCS reader instance. Usually you'd want to call `.toBytes()` | ||
*/ | ||
public static ser(type: string, data: any, size: number = 1024): BcsWriter { | ||
return this.getTypeInterface(type).encode(data, size); | ||
} | ||
/** | ||
* Deserialize BCS into a JS type. | ||
* | ||
* @example | ||
* // use util to form an Uint8Array buffer | ||
* let data = BCS.de(BCS.U32, new Uint8Array([255, 255, 255, 255])); | ||
* console.assert(data.toString() == '4294967295'); | ||
* | ||
* @param type Name of the type to deserialize (must be registered). | ||
* @param data Data to deserialize. | ||
* @return Deserialized data. | ||
*/ | ||
public static de(type: string, data: Uint8Array): any { | ||
return this.getTypeInterface(type).decode(data); | ||
} | ||
/** | ||
* Deserialize BCS into a JS type. | ||
* | ||
* @example | ||
* // use util to form an Uint8Array buffer | ||
* let data = BCS.de(BCS.U32, new Uint8Array([255, 255, 255, 255])); | ||
* console.assert(data.toString() == '4294967295'); | ||
* | ||
* @param type Name of the type to deserialize (must be registered). | ||
* @param data Data to deserialize. | ||
* @return Deserialized data. | ||
*/ | ||
public static de(type: string, data: Uint8Array): any { | ||
return this.getTypeInterface(type).decode(data); | ||
} | ||
/** | ||
* Check whether a TypeInterface has been loaded for the `Type` | ||
* @param type Name of the type to check. | ||
* @returns | ||
*/ | ||
public static hasType(type: string): boolean { | ||
return this.types.has(type); | ||
} | ||
/** | ||
* Check whether a TypeInferface has been loaded for the `Type` | ||
* @param type Name of the type to check. | ||
* @returns | ||
*/ | ||
public static hasType(type: string): boolean { | ||
return this.types.has(type); | ||
} | ||
/** | ||
* Method to register new types for BCS internal representation. | ||
* For each registered type 2 callbacks must be specified and one is optional: | ||
* | ||
* - encodeCb(writer, data) - write a way to serialize data with BcsWriter; | ||
* - decodeCb(reader) - write a way to deserialize data with BcsReader; | ||
* - validateCb(data) - validate data - either return bool or throw an error | ||
* | ||
* @example | ||
* // our type would be a string that consists only of numbers | ||
* BCS.registerType('number_string', | ||
* (writer, data) => writer.writeVec(data, (w, el) => w.write8(el)), | ||
* (reader) => reader.readVec((r) => r.read8()).join(''), // read each value as u8 | ||
* (value) => /[0-9]+/.test(value) // test that it has at least one digit | ||
* ); | ||
* console.log(Array.from(BCS.set('number_string', '12345').toBytes()) == [5,1,2,3,4,5]); | ||
* | ||
* @param name | ||
* @param encodeCb Callback to encode a value. | ||
* @param decodeCb Callback to decode a value. | ||
* @param validateCb Optional validator Callback to check type before serialization. | ||
*/ | ||
public static registerType( | ||
name: string, | ||
encodeCb: (writer: BcsWriter, data: any) => BcsWriter, | ||
decodeCb: (reader: BcsReader) => any, | ||
validateCb: (data: any) => boolean = () => true | ||
): typeof BCS { | ||
this.types.set(name, { | ||
encode(data, size = 1024) { | ||
return this._encodeRaw(new BcsWriter(size), data); | ||
}, | ||
decode(data) { | ||
return this._decodeRaw(new BcsReader(data)); | ||
}, | ||
/** | ||
* Method to register new types for BCS internal representation. | ||
* For each registered type 2 callbacks must be specified and one is optional: | ||
* | ||
* - encodeCb(writer, data) - write a way to serialize data with BcsWriter; | ||
* - decodeCb(reader) - write a way to deserialize data with BcsReader; | ||
* - validateCb(data) - validate data - either return bool or throw an error | ||
* | ||
* @example | ||
* // our type would be a string that consists only of numbers | ||
* BCS.registerType('number_string', | ||
* (writer, data) => writer.writeVec(data, (w, el) => w.write8(el)), | ||
* (reader) => reader.readVec((r) => r.read8()).join(''), // read each value as u8 | ||
* (value) => /[0-9]+/.test(value) // test that it has at least one digit | ||
* ); | ||
* console.log(Array.from(BCS.ser('number_string', '12345').toBytes()) == [5,1,2,3,4,5]); | ||
* | ||
* @param name | ||
* @param encodeCb Callback to encode a value. | ||
* @param decodeCb Callback to decode a value. | ||
* @param validateCb Optional validator Callback to check type before serialization. | ||
*/ | ||
public static registerType( | ||
name: string, | ||
encodeCb: (writer: BcsWriter, data: any) => BcsWriter, | ||
decodeCb: (reader: BcsReader) => any, | ||
validateCb: (data: any) => boolean = () => true | ||
): typeof BCS { | ||
this.types.set(name, { | ||
encode(data, size = 1024) { return this._encodeRaw(new BcsWriter(size), data); }, | ||
decode(data) { return this._decodeRaw(new BcsReader(data)); }, | ||
// these methods should always be used with caution as they require pre-defined | ||
// reader and writer and mainly exist to allow multi-field (de)serialization; | ||
_encodeRaw(writer, data) { | ||
if (validateCb(data)) { | ||
return encodeCb(writer, data); | ||
} else { | ||
throw new Error(`Validation failed for type ${name}, data: ${data}`); | ||
} | ||
}, | ||
_decodeRaw(reader) { | ||
return decodeCb(reader); | ||
}, | ||
}); | ||
// these methods should always be used with caution as they require pre-defined | ||
// reader and writer and mainly exist to allow multi-field (de)serialization; | ||
_encodeRaw(writer, data) { | ||
if (validateCb(data)) { | ||
return encodeCb(writer, data) | ||
} else { | ||
throw new Error(`Validation failed for type ${name}, data: ${data}`); | ||
} | ||
}, | ||
_decodeRaw(reader) { return decodeCb(reader); } | ||
}); | ||
return this; | ||
} | ||
return this; | ||
} | ||
/** | ||
* Register an address type which is a sequence of U8s of specified length. | ||
* @example | ||
* BCS.registerAddressType('address', 20); | ||
* let addr = BCS.de('address', 'ca27601ec5d915dd40d42e36c395d4a156b24026'); | ||
* | ||
* @param name Name of the address type. | ||
* @param length Byte length of the address. | ||
* @returns | ||
*/ | ||
public static registerAddressType(name: string, length: number): typeof BCS { | ||
return this.registerType( | ||
name, | ||
(writer, data) => | ||
new HEX(data) | ||
.getData() | ||
.reduce((writer, el) => writer.write8(el), writer), | ||
reader => new HEX(reader.readBytes(length)).toString() | ||
); | ||
} | ||
/** | ||
* Register an address type which is a sequence of U8s of specified length. | ||
* @example | ||
* BCS.registerAddressType('address', 20); | ||
* let addr = BCS.de('address', 'ca27601ec5d915dd40d42e36c395d4a156b24026'); | ||
* | ||
* @param name Name of the address type. | ||
* @param length Byte length of the address. | ||
* @returns | ||
*/ | ||
public static registerAddressType( | ||
name: string, | ||
length: number | ||
): typeof BCS { | ||
return this.registerType(name, | ||
(writer, data) => new HEX(data).getData().reduce((writer, el) => writer.write8(el), writer), | ||
(reader) => new HEX(reader.readBytes(length)).toString() | ||
); | ||
} | ||
/** | ||
* Register custom vector type inside the BCS. | ||
* | ||
* @example | ||
* BCS.registerVectorType('vector<u8>', 'u8'); | ||
* let array = BCS.de('vector<u8>', new Uint8Array([6,1,2,3,4,5,6])); // [1,2,3,4,5,6]; | ||
* let again = BCS.set('vector<u8>', [1,2,3,4,5,6]).toBytes(); | ||
* | ||
* @param name Name of the type to register. | ||
* @param elementType Name of the inner type of the vector. | ||
* @return Returns self for chaining. | ||
*/ | ||
public static registerVectorType( | ||
name: string, | ||
elementType: string | ||
): typeof BCS { | ||
// OMITTING SAFETY CHECK TO ALLOW RECURSIVE DEFINITIONS | ||
// if (!BCS.hasType(elementType)) { | ||
// throw new Error(`Type ${elementType} is not registered`); | ||
// } | ||
/** | ||
* Register custom vector type inside the BCS. | ||
* | ||
* @example | ||
* BCS.registerVectorType('vector<u8>', 'u8'); | ||
* let array = BCS.de('vector<u8>', new Uint8Array([6,1,2,3,4,5,6])); // [1,2,3,4,5,6]; | ||
* let again = BCS.ser('vector<u8>', [1,2,3,4,5,6]).toBytes(); | ||
* | ||
* @param name Name of the type to register. | ||
* @param elementType Name of the inner type of the vector. | ||
* @return Returns self for chaining. | ||
*/ | ||
public static registerVectorType( | ||
name: string, | ||
elementType: string | ||
): typeof BCS { | ||
// OMITTING SAFETY CHECK TO ALLOW RECURSIVE DEFINITIONS | ||
// if (!BCS.hasType(elementType)) { | ||
// throw new Error(`Type ${elementType} is not registered`); | ||
// } | ||
return this.registerType( | ||
name, | ||
(writer, data) => | ||
writer.writeVec(data, (writer, el) => { | ||
return BCS.getTypeInterface(elementType)._encodeRaw(writer, el); | ||
}), | ||
reader => | ||
reader.readVec(reader => { | ||
return BCS.getTypeInterface(elementType)._decodeRaw(reader); | ||
}) | ||
); | ||
} | ||
return this.registerType(name, | ||
(writer, data) => writer.writeVec(data, (writer, el) => { | ||
return BCS.getTypeInterface(elementType)._encodeRaw(writer, el); | ||
}), | ||
(reader) => reader.readVec((reader) => { | ||
return BCS.getTypeInterface(elementType)._decodeRaw(reader); | ||
}) | ||
); | ||
} | ||
/** | ||
* Safe method to register a custom Move struct. The first argument is a name of the | ||
* struct which is only used on the FrontEnd and has no affect on serialization results, | ||
* and the second is a struct description passed as an Object. | ||
* | ||
* The description object MUST have the same order on all of the platforms (ie in Move | ||
* or in Rust). | ||
* | ||
* @example | ||
* // Move / Rust struct | ||
* // struct Coin { | ||
* // value: u64, | ||
* // owner: vector<u8>, // name // Vec<u8> in Rust | ||
* // is_locked: bool, | ||
* // } | ||
* | ||
* BCS.registerStructType('Coin', { | ||
* value: BCS.U64, | ||
* owner: BCS.STRING, | ||
* is_locked: BCS.BOOL | ||
* }); | ||
* | ||
* // Created in Rust with diem/bcs | ||
* // let rust_bcs_str = '80d1b105600000000e4269672057616c6c65742047757900'; | ||
* let rust_bcs_str = [ // using an Array here as BCS works with Uint8Buffer | ||
* 128, 209, 177, 5, 96, 0, 0, | ||
* 0, 14, 66, 105, 103, 32, 87, | ||
* 97, 108, 108, 101, 116, 32, 71, | ||
* 117, 121, 0 | ||
* ]; | ||
* | ||
* // Let's encode the value as well | ||
* let test_set = BCS.set('Coin', { | ||
* owner: 'Big Wallet Guy', | ||
* value: '412412400000', | ||
* is_locked: false, | ||
* }); | ||
* | ||
* console.assert(Array.from(test_set.toBytes()) === rust_bcs_str, 'Whoopsie, result mismatch'); | ||
* | ||
* @param name Name of the type to register. | ||
* @param fields Fields of the struct. Must be in the correct order. | ||
* @return Returns BCS for chaining. | ||
*/ | ||
public static registerStructType( | ||
name: string, | ||
fields: { [key: string]: string } | ||
): typeof BCS { | ||
let struct = Object.freeze(fields); // Make sure the order doesn't get changed | ||
/** | ||
* Safe method to register a custom Move struct. The first argument is a name of the | ||
* struct which is only used on the FrontEnd and has no affect on serialization results, | ||
* and the second is a struct description passed as an Object. | ||
* | ||
* The description object MUST have the same order on all of the platforms (ie in Move | ||
* or in Rust). | ||
* | ||
* @example | ||
* // Move / Rust struct | ||
* // struct Coin { | ||
* // value: u64, | ||
* // owner: vector<u8>, // name // Vec<u8> in Rust | ||
* // is_locked: bool, | ||
* // } | ||
* | ||
* BCS.registerStructType('Coin', { | ||
* value: BCS.U64, | ||
* owner: BCS.STRING, | ||
* is_locked: BCS.BOOL | ||
* }); | ||
* | ||
* // Created in Rust with diem/bcs | ||
* // let rust_bcs_str = '80d1b105600000000e4269672057616c6c65742047757900'; | ||
* let rust_bcs_str = [ // using an Array here as BCS works with Uint8Buffer | ||
* 128, 209, 177, 5, 96, 0, 0, | ||
* 0, 14, 66, 105, 103, 32, 87, | ||
* 97, 108, 108, 101, 116, 32, 71, | ||
* 117, 121, 0 | ||
* ]; | ||
* | ||
* // Let's encode the value as well | ||
* let test_ser = BCS.ser('Coin', { | ||
* owner: 'Big Wallet Guy', | ||
* value: '412412400000', | ||
* is_locked: false, | ||
* }); | ||
* | ||
* console.assert(Array.from(test_ser.toBytes()) === rust_bcs_str, 'Whoopsie, result mismatch'); | ||
* | ||
* @param name Name of the type to register. | ||
* @param fields Fields of the struct. Must be in the correct order. | ||
* @return Returns BCS for chaining. | ||
*/ | ||
public static registerStructType(name: string, fields: { [key: string]: string }): typeof BCS { | ||
let struct = Object.freeze(fields); // Make sure the order doesn't get changed | ||
// IMPORTANT: we need to store canonical order of fields for each registered | ||
// struct so we maintain it and allow developers to use any field ordering in | ||
// their code (and not cause mismatches based on field order). | ||
let canonicalOrder = Object.keys(struct); | ||
// IMPORTANT: we need to store canonical order of fields for each registered | ||
// struct so we maintain it and allow developers to use any field ordering in | ||
// their code (and not cause mismatches based on field order). | ||
let canonicalOrder = Object.keys(struct); | ||
// Make sure all the types in the fields description are already known | ||
// and that all the field types are strings. | ||
// OMITTING this check to allow recursive definitions and dynamic typing. | ||
// for (let type of Object.values(struct)) { | ||
// throw new Error(`Type ${type} is not registered`); | ||
// } | ||
// } | ||
// Make sure all the types in the fields description are already known | ||
// and that all the field types are strings. | ||
// OMITTING this check to allow recursive definitions and dynamic typing. | ||
// for (let type of Object.values(struct)) { | ||
// throw new Error(`Type ${type} is not registered`); | ||
// } | ||
// } | ||
return this.registerType( | ||
name, | ||
(writer, data) => { | ||
for (let key of canonicalOrder) { | ||
BCS.getTypeInterface(struct[key])._encodeRaw(writer, data[key]); | ||
} | ||
return writer; | ||
}, | ||
reader => { | ||
let result: { [key: string]: any } = {}; | ||
for (let key of canonicalOrder) { | ||
result[key] = BCS.getTypeInterface(struct[key])._decodeRaw(reader); | ||
} | ||
return result; | ||
} | ||
); | ||
} | ||
return this.registerType(name, | ||
(writer, data) => { | ||
for (let key of canonicalOrder) { | ||
BCS.getTypeInterface(struct[key])._encodeRaw(writer, data[key]); | ||
} | ||
return writer; | ||
}, | ||
(reader) => { | ||
let result: { [key: string]: any } = {}; | ||
for (let key of canonicalOrder) { | ||
result[key] = BCS.getTypeInterface(struct[key])._decodeRaw(reader); | ||
} | ||
return result; | ||
} | ||
); | ||
} | ||
/** | ||
* Safe method to register custom enum type where each invariant holds the value of another type. | ||
* @example | ||
* BCS.registerStructType('Coin', { value: 'u64' }); | ||
* BCS.registerVectorType('vector<Coin>', 'Coin'); | ||
* BCS.registerEnumType('MyEnum', { | ||
* single: 'Coin', | ||
* multi: 'vector<Coin>' | ||
* }); | ||
* | ||
* let example1 = Buffer.from('AICWmAAAAAAA', 'base64'); | ||
* let example2 = Buffer.from('AQIBAAAAAAAAAAIAAAAAAAAA', 'base64'); | ||
* | ||
* console.log( | ||
* BCS.de('MyEnum', new Uint8Array(example1)), // { single: { value: 10000000 } } | ||
* BCS.de('MyEnum', new Uint8Array(example2)) // { multi: [ { value: 1 }, { value: 2 } ] } | ||
* } | ||
* | ||
* // and serialization | ||
* BCS.set('MyEnum', { single: { value: 10000000 } }).toBytes(); | ||
* BCS.set('MyEnum', { multi: [ { value: 1 }, { value: 2 } ] }); | ||
* | ||
* @param name | ||
* @param variants | ||
*/ | ||
public static registerEnumType( | ||
name: string, | ||
variants: { [key: string]: string | null } | ||
) { | ||
let struct = Object.freeze(variants); // Make sure the order doesn't get changed | ||
/** | ||
* Safe method to register custom enum type where each invariant holds the value of another type. | ||
* @example | ||
* BCS.registerStructType('Coin', { value: 'u64' }); | ||
* BCS.registerVectorType('vector<Coin>', 'Coin'); | ||
* BCS.registerEnumType('MyEnum', { | ||
* single: 'Coin', | ||
* multi: 'vector<Coin>' | ||
* }); | ||
* | ||
* let example1 = Buffer.from('AICWmAAAAAAA', 'base64'); | ||
* let example2 = Buffer.from('AQIBAAAAAAAAAAIAAAAAAAAA', 'base64'); | ||
* | ||
* console.log( | ||
* BCS.de('MyEnum', new Uint8Array(example1)), // { single: { value: 10000000 } } | ||
* BCS.de('MyEnum', new Uint8Array(example2)) // { multi: [ { value: 1 }, { value: 2 } ] } | ||
* } | ||
* | ||
* // and serialization | ||
* BCS.ser('MyEnum', { single: { value: 10000000 } }).toBytes(); | ||
* BCS.ser('MyEnum', { multi: [ { value: 1 }, { value: 2 } ] }); | ||
* | ||
* @param name | ||
* @param variants | ||
*/ | ||
public static registerEnumType(name: string, variants: { [key: string]: string|null }) { | ||
let struct = Object.freeze(variants); // Make sure the order doesn't get changed | ||
// IMPORTANT: enum is an ordered type and we have to preserve ordering in BCS | ||
let canonicalOrder = Object.keys(struct); | ||
// IMPORTANT: enum is an ordered type and we have to preserve ordering in BCS | ||
let canonicalOrder = Object.keys(struct); | ||
return this.registerType( | ||
name, | ||
(writer, data) => { | ||
let key = Object.keys(data)[0]; | ||
if (key === undefined) { | ||
throw new Error(`Unknown invariant of the enum ${name}`); | ||
} | ||
let orderByte = canonicalOrder.indexOf(key); | ||
if (orderByte === -1) { | ||
throw new Error( | ||
`Unknown invariant of the enum ${name}, allowed values: ${canonicalOrder}` | ||
); | ||
} | ||
let invariant = canonicalOrder[orderByte]; | ||
let invariantType = struct[invariant]; | ||
return this.registerType(name, | ||
(writer, data) => { | ||
let key = Object.keys(data)[0]; | ||
if (key === undefined) { | ||
throw new Error(`Unknown invariant of the enum ${name}`); | ||
} | ||
writer.write8(orderByte); // write order byte | ||
let orderByte = canonicalOrder.indexOf(key); | ||
if (orderByte === -1) { | ||
throw new Error(`Unknown invariant of the enum ${name}, allowed values: ${canonicalOrder}`); | ||
} | ||
let invariant = canonicalOrder[orderByte]; | ||
let invariantType = struct[invariant]; | ||
// Allow empty Enum values! | ||
return invariantType !== null | ||
? BCS.getTypeInterface(invariantType)._encodeRaw(writer, data[key]) | ||
: writer; | ||
}, | ||
reader => { | ||
let orderByte = reader.readULEB(); | ||
let invariant = canonicalOrder[orderByte]; | ||
let invariantType = struct[invariant]; | ||
writer.write8(orderByte); // write order byte | ||
if (orderByte === -1) { | ||
throw new Error( | ||
`Decoding type mismatch, expected enum ${name} invariant index, received ${orderByte}` | ||
); | ||
} | ||
return { | ||
[invariant]: | ||
invariantType !== null | ||
? BCS.getTypeInterface(invariantType)._decodeRaw(reader) | ||
: true, | ||
}; | ||
} | ||
); | ||
} | ||
// Allow empty Enum values! | ||
return (invariantType !== null) | ||
? BCS.getTypeInterface(invariantType)._encodeRaw(writer, data[key]) | ||
: writer; | ||
}, | ||
(reader) => { | ||
let orderByte = reader.readULEB(); | ||
let invariant = canonicalOrder[orderByte]; | ||
let invariantType = struct[invariant]; | ||
if (orderByte === -1) { | ||
throw new Error(`Decoding type mismatch, expected enum ${name} invariant index, received ${orderByte}`); | ||
} | ||
return { | ||
[invariant]: invariantType !== null | ||
? BCS.getTypeInterface(invariantType)._decodeRaw(reader) | ||
: true | ||
}; | ||
} | ||
); | ||
static getTypeInterface(type: string): TypeInterface { | ||
let typeInterface = BCS.types.get(type); | ||
if (typeInterface === undefined) { | ||
throw new Error(`Type ${type} is not registered`); | ||
} | ||
static getTypeInterface(type: string): TypeInterface { | ||
let typeInterface = BCS.types.get(type); | ||
if (typeInterface === undefined) { | ||
throw new Error(`Type ${type} is not registered`); | ||
} | ||
return typeInterface; | ||
} | ||
return typeInterface; | ||
} | ||
} | ||
(function registerPrimitives(): void { | ||
BCS.registerType( | ||
BCS.U8, | ||
(writer, data) => writer.write8(data), | ||
(reader) => reader.read8(), | ||
(u8) => (u8 < 256) | ||
); | ||
BCS.registerType( | ||
BCS.U8, | ||
(writer, data) => writer.write8(data), | ||
reader => reader.read8(), | ||
u8 => u8 < 256 | ||
); | ||
BCS.registerType( | ||
BCS.U32, | ||
(writer, data) => writer.write32(data), | ||
(reader) => reader.read32(), | ||
(u32) => (u32 < 4294967296) | ||
); | ||
BCS.registerType( | ||
BCS.U32, | ||
(writer, data) => writer.write32(data), | ||
reader => reader.read32(), | ||
u32 => u32 < 4294967296 | ||
); | ||
BCS.registerType( | ||
BCS.U64, | ||
(writer, data) => writer.write64(data), | ||
(reader) => reader.read64(), | ||
(_u64) => true | ||
); | ||
BCS.registerType( | ||
BCS.U64, | ||
(writer, data) => writer.write64(data), | ||
reader => reader.read64(), | ||
_u64 => true | ||
); | ||
BCS.registerType( | ||
BCS.U128, | ||
(writer, data) => writer.write128(data), | ||
(reader) => reader.read128(), | ||
(_u128) => true | ||
); | ||
BCS.registerType( | ||
BCS.U128, | ||
(writer, data) => writer.write128(data), | ||
reader => reader.read128(), | ||
_u128 => true | ||
); | ||
BCS.registerType( | ||
BCS.BOOL, | ||
(writer, data) => writer.write8(data), | ||
(reader) => reader.read8().toString(10) == '1', | ||
(_bool: boolean) => true | ||
); | ||
BCS.registerType( | ||
BCS.BOOL, | ||
(writer, data) => writer.write8(data), | ||
reader => reader.read8().toString(10) == '1', | ||
(_bool: boolean) => true | ||
); | ||
BCS.registerType( | ||
BCS.STRING, | ||
(writer, data) => writer.writeVec(Array.from(data), (writer, el) => writer.write8(el.charCodeAt(0))), | ||
(reader) => { | ||
return reader | ||
.readVec((reader) => reader.read8()) | ||
.map((el) => String.fromCharCode(el)) | ||
.join(''); | ||
}, | ||
(str: string) => /^[\x00-\x7F]*$/.test(str) | ||
) | ||
BCS.registerType( | ||
BCS.STRING, | ||
(writer, data) => | ||
writer.writeVec(Array.from(data), (writer, el) => | ||
writer.write8(el.charCodeAt(0)) | ||
), | ||
reader => { | ||
return reader | ||
.readVec(reader => reader.read8()) | ||
.map(el => String.fromCharCode(el)) | ||
.join(''); | ||
}, | ||
(str: string) => /^[\x00-\x7F]*$/.test(str) | ||
); | ||
})(); |
@@ -6,2 +6,3 @@ // Copyright (c) 2022, Mysten Labs, Inc. | ||
import { Buffer } from 'buffer'; | ||
import { sha3_256 } from 'js-sha3'; | ||
@@ -51,3 +52,5 @@ /** | ||
if (buffer.length !== 32) { | ||
throw new Error(`Invalid public key input`); | ||
throw new Error( | ||
`Invalid public key input. Expected 32 bytes, got ${buffer.length}` | ||
); | ||
} | ||
@@ -110,5 +113,16 @@ this._bn = new BN(buffer); | ||
toSuiAddress(): string { | ||
// TODO: implement this by apply sha256 hashing and take the first 20 bytes | ||
throw new Error('Not implemented'); | ||
const hexHash = sha3_256(this.toBytes()); | ||
const publicKeyBytes = new BN(hexHash, 16).toArray(undefined, 32); | ||
// Only take the first 20 bytes | ||
const addressBytes = publicKeyBytes.slice(0, 20); | ||
return toHexString(addressBytes); | ||
} | ||
} | ||
// https://stackoverflow.com/questions/34309988/byte-array-to-hex-string-conversion-in-javascript | ||
function toHexString(byteArray: number[]) { | ||
return byteArray.reduce( | ||
(output, elem) => output + ('0' + elem.toString(16)).slice(-2), | ||
'' | ||
); | ||
} |
@@ -8,3 +8,3 @@ // Copyright (c) 2022, Mysten Labs, Inc. | ||
*/ | ||
import { Ed25519KeypairData, Keypair, PublicKeyInitData, PublicKeyData, SignedTransaction, TransactionResponse, TransferTransaction, TxnDataSerializer, TransactionDigest, SuiAddress, ObjectOwner, ObjectRef, ObjectContentField, ObjectContentFields, ObjectContent, MovePackageContent, SuiObject, ObjectExistsInfo, ObjectNotExistsInfo, ObjectStatus, ObjectType, GetOwnedObjectRefsResponse, GetObjectInfoResponse, ObjectDigest, ObjectId, SequenceNumber, RawObjectRef, Transfer, RawAuthoritySignInfo, TransactionKindName, SingleTransactionKind, TransactionKind, TransactionData, EpochId, AuthorityQuorumSignInfo, CertifiedTransaction, GasCostSummary, ExecutionStatusType, ExecutionStatus, ExecutionStatusDetail, OwnedObjectRef, TransactionEffects, TransactionEffectsResponse, GatewayTxSeqNumber, GetTxnDigestsResponse, MoveModulePublish, Event, StructTag, MoveTypeTag, MoveCall, MoveCallArg, EmptySignInfo, AuthorityName, AuthoritySignature } from "./index"; | ||
import { Ed25519KeypairData, Keypair, PublicKeyInitData, PublicKeyData, TransferCoinTransaction, TxnDataSerializer, TransactionDigest, SuiAddress, ObjectOwner, ObjectRef, ObjectContentField, ObjectContentFields, ObjectContent, MovePackageContent, SuiObject, ObjectExistsInfo, ObjectNotExistsInfo, ObjectStatus, ObjectType, GetOwnedObjectRefsResponse, GetObjectInfoResponse, ObjectDigest, ObjectId, SequenceNumber, RawObjectRef, Transfer, RawAuthoritySignInfo, TransactionKindName, SingleTransactionKind, TransactionKind, TransactionData, EpochId, AuthorityQuorumSignInfo, CertifiedTransaction, GasCostSummary, ExecutionStatusType, ExecutionStatus, ExecutionStatusDetail, OwnedObjectRef, TransactionEffects, TransactionEffectsResponse, GatewayTxSeqNumber, GetTxnDigestsResponse, MoveModulePublish, Event, StructTag, MoveTypeTag, MoveCall, MoveCallArg, EmptySignInfo, AuthorityName, AuthoritySignature, TransactionBytes, TransactionResponse, SignedTransaction } from "./index"; | ||
import { BN } from "bn.js"; | ||
@@ -34,3 +34,3 @@ | ||
return ( | ||
(isTransactionResponse(obj) as boolean || | ||
(isTransactionDigest(obj) as boolean || | ||
isSequenceNumber(obj) as boolean || | ||
@@ -56,3 +56,3 @@ obj instanceof Buffer || | ||
export function isSignedTransaction(obj: any, _argumentName?: string): obj is SignedTransaction { | ||
export function isTransferCoinTransaction(obj: any, _argumentName?: string): obj is TransferCoinTransaction { | ||
return ( | ||
@@ -62,27 +62,10 @@ (obj !== null && | ||
typeof obj === "function") && | ||
isTransactionResponse(obj.txBytes) as boolean && | ||
isTransactionResponse(obj.signature) as boolean && | ||
isTransactionResponse(obj.pubKey) as boolean | ||
isTransactionDigest(obj.signer) as boolean && | ||
isTransactionDigest(obj.objectId) as boolean && | ||
isTransactionDigest(obj.gasPayment) as boolean && | ||
isSequenceNumber(obj.gasBudget) as boolean && | ||
isTransactionDigest(obj.recipient) as boolean | ||
) | ||
} | ||
export function isTransactionResponse(obj: any, _argumentName?: string): obj is TransactionResponse { | ||
return ( | ||
typeof obj === "string" | ||
) | ||
} | ||
export function isTransferTransaction(obj: any, _argumentName?: string): obj is TransferTransaction { | ||
return ( | ||
(obj !== null && | ||
typeof obj === "object" || | ||
typeof obj === "function") && | ||
isTransactionResponse(obj.fromAddress) as boolean && | ||
isTransactionResponse(obj.objectId) as boolean && | ||
isTransactionResponse(obj.toAddress) as boolean && | ||
isTransactionResponse(obj.gasObjectId) as boolean && | ||
isSequenceNumber(obj.gas_budget) as boolean | ||
) | ||
} | ||
export function isTxnDataSerializer(obj: any, _argumentName?: string): obj is TxnDataSerializer { | ||
@@ -93,3 +76,3 @@ return ( | ||
typeof obj === "function") && | ||
typeof obj.new_transfer === "function" | ||
typeof obj.newTransferCoin === "function" | ||
) | ||
@@ -115,7 +98,7 @@ } | ||
typeof obj === "function") && | ||
isTransactionResponse(obj.AddressOwner) as boolean || | ||
isTransactionDigest(obj.AddressOwner) as boolean || | ||
(obj !== null && | ||
typeof obj === "object" || | ||
typeof obj === "function") && | ||
isTransactionResponse(obj.ObjectOwner) as boolean || | ||
isTransactionDigest(obj.ObjectOwner) as boolean || | ||
obj === "Shared" || | ||
@@ -131,4 +114,4 @@ obj === "Immutable") | ||
typeof obj === "function") && | ||
isTransactionResponse(obj.digest) as boolean && | ||
isTransactionResponse(obj.objectId) as boolean && | ||
isTransactionDigest(obj.digest) as boolean && | ||
isTransactionDigest(obj.objectId) as boolean && | ||
isSequenceNumber(obj.version) as boolean | ||
@@ -140,3 +123,3 @@ ) | ||
return ( | ||
(isTransactionResponse(obj) as boolean || | ||
(isTransactionDigest(obj) as boolean || | ||
isSequenceNumber(obj) as boolean || | ||
@@ -164,3 +147,3 @@ obj === false || | ||
.every(([key, value]) => (isObjectContentField(value) as boolean && | ||
isTransactionResponse(key) as boolean)) | ||
isTransactionDigest(key) as boolean)) | ||
) | ||
@@ -175,3 +158,3 @@ } | ||
isObjectContentFields(obj.fields) as boolean && | ||
isTransactionResponse(obj.type) as boolean | ||
isTransactionDigest(obj.type) as boolean | ||
) | ||
@@ -186,4 +169,4 @@ } | ||
Object.entries<any>(obj) | ||
.every(([key, value]) => (isTransactionResponse(value) as boolean && | ||
isTransactionResponse(key) as boolean)) | ||
.every(([key, value]) => (isTransactionDigest(value) as boolean && | ||
isTransactionDigest(key) as boolean)) | ||
) | ||
@@ -200,3 +183,3 @@ } | ||
isObjectOwner(obj.owner) as boolean && | ||
isTransactionResponse(obj.tx_digest) as boolean | ||
isTransactionDigest(obj.tx_digest) as boolean | ||
) | ||
@@ -221,3 +204,3 @@ } | ||
typeof obj === "function") && | ||
isTransactionResponse(obj.objectId) as boolean | ||
isTransactionDigest(obj.objectId) as boolean | ||
) | ||
@@ -286,5 +269,5 @@ } | ||
Array.isArray(obj) && | ||
isTransactionResponse(obj[0]) as boolean && | ||
isTransactionDigest(obj[0]) as boolean && | ||
isSequenceNumber(obj[1]) as boolean && | ||
isTransactionResponse(obj[2]) as boolean | ||
isTransactionDigest(obj[2]) as boolean | ||
) | ||
@@ -298,3 +281,3 @@ } | ||
typeof obj === "function") && | ||
isTransactionResponse(obj.recipient) as boolean && | ||
isTransactionDigest(obj.recipient) as boolean && | ||
isRawObjectRef(obj.object_ref) as boolean | ||
@@ -307,4 +290,4 @@ ) | ||
Array.isArray(obj) && | ||
isTransactionResponse(obj[0]) as boolean && | ||
isTransactionResponse(obj[1]) as boolean | ||
isTransactionDigest(obj[0]) as boolean && | ||
isTransactionDigest(obj[1]) as boolean | ||
) | ||
@@ -360,3 +343,3 @@ } | ||
isTransactionKind(obj.kind) as boolean && | ||
isTransactionResponse(obj.sender) as boolean && | ||
isTransactionDigest(obj.sender) as boolean && | ||
isRawObjectRef(obj.gas_payment) as boolean && | ||
@@ -392,3 +375,3 @@ isSequenceNumber(obj.gas_budget) as boolean | ||
isTransactionData(obj.data) as boolean && | ||
isTransactionResponse(obj.tx_signature) as boolean && | ||
isTransactionDigest(obj.tx_signature) as boolean && | ||
isAuthorityQuorumSignInfo(obj.auth_sign_info) as boolean | ||
@@ -456,3 +439,3 @@ ) | ||
) && | ||
isTransactionResponse(obj.transaction_digest) as boolean && | ||
isTransactionDigest(obj.transaction_digest) as boolean && | ||
Array.isArray(obj.created) && | ||
@@ -485,3 +468,3 @@ obj.created.every((e: any) => | ||
obj.dependencies.every((e: any) => | ||
isTransactionResponse(e) as boolean | ||
isTransactionDigest(e) as boolean | ||
) | ||
@@ -513,3 +496,3 @@ ) | ||
isSequenceNumber(e[0]) as boolean && | ||
isTransactionResponse(e[1]) as boolean | ||
isTransactionDigest(e[1]) as boolean | ||
) | ||
@@ -533,3 +516,3 @@ ) | ||
isStructTag(obj.type_) as boolean && | ||
isTransactionResponse(obj.contents) as boolean | ||
isTransactionDigest(obj.contents) as boolean | ||
) | ||
@@ -543,5 +526,5 @@ } | ||
typeof obj === "function") && | ||
isTransactionResponse(obj.address) as boolean && | ||
isTransactionResponse(obj.module) as boolean && | ||
isTransactionResponse(obj.name) as boolean && | ||
isTransactionDigest(obj.address) as boolean && | ||
isTransactionDigest(obj.module) as boolean && | ||
isTransactionDigest(obj.name) as boolean && | ||
Array.isArray(obj.type_args) && | ||
@@ -582,4 +565,4 @@ obj.type_args.every((e: any) => | ||
isRawObjectRef(obj.package) as boolean && | ||
isTransactionResponse(obj.module) as boolean && | ||
isTransactionResponse(obj.function) as boolean && | ||
isTransactionDigest(obj.module) as boolean && | ||
isTransactionDigest(obj.function) as boolean && | ||
Array.isArray(obj.type_arguments) && | ||
@@ -612,3 +595,3 @@ obj.type_arguments.every((e: any) => | ||
typeof obj === "function") && | ||
isTransactionResponse(obj.SharedObject) as boolean) | ||
isTransactionDigest(obj.SharedObject) as boolean) | ||
) | ||
@@ -634,1 +617,30 @@ } | ||
} | ||
export function isTransactionBytes(obj: any, _argumentName?: string): obj is TransactionBytes { | ||
return ( | ||
(obj !== null && | ||
typeof obj === "object" || | ||
typeof obj === "function") && | ||
isTransactionDigest(obj.tx_bytes) as boolean | ||
) | ||
} | ||
export function isTransactionResponse(obj: any, _argumentName?: string): obj is TransactionResponse { | ||
return ( | ||
(obj !== null && | ||
typeof obj === "object" || | ||
typeof obj === "function") && | ||
isTransactionEffectsResponse(obj.EffectResponse) as boolean | ||
) | ||
} | ||
export function isSignedTransaction(obj: any, _argumentName?: string): obj is SignedTransaction { | ||
return ( | ||
(obj !== null && | ||
typeof obj === "object" || | ||
typeof obj === "function") && | ||
isTransactionDigest(obj.tx_bytes) as boolean && | ||
isTransactionDigest(obj.signature) as boolean && | ||
isTransactionDigest(obj.pub_key) as boolean | ||
) | ||
} |
// Copyright (c) 2022, Mysten Labs, Inc. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
import { SignedTransaction, TransactionResponse, Provider } from './provider'; | ||
import { Provider } from './provider'; | ||
import { JsonRpcClient } from '../rpc/client'; | ||
@@ -11,2 +11,3 @@ import { | ||
isTransactionEffectsResponse, | ||
isTransactionResponse, | ||
} from '../index.guard'; | ||
@@ -21,2 +22,4 @@ import { | ||
TransactionEffectsResponse, | ||
SignedTransaction, | ||
TransactionResponse, | ||
} from '../types'; | ||
@@ -35,3 +38,3 @@ import { transformGetObjectInfoResponse } from '../types/framework/transformer'; | ||
*/ | ||
constructor(endpoint: string) { | ||
constructor(public endpoint: string) { | ||
super(); | ||
@@ -120,3 +123,5 @@ this.client = new JsonRpcClient(endpoint); | ||
const list = digests.join(', ').substring(0, -2); | ||
throw new Error(`Error getting transaction effects: ${err} for digests [${list}]`); | ||
throw new Error( | ||
`Error getting transaction effects: ${err} for digests [${list}]` | ||
); | ||
} | ||
@@ -141,5 +146,16 @@ } | ||
async executeTransaction( | ||
_txn: SignedTransaction | ||
txn: SignedTransaction | ||
): Promise<TransactionResponse> { | ||
throw new Error('Method not implemented.'); | ||
try { | ||
const resp = await this.client.requestWithType( | ||
'sui_executeTransaction', | ||
[txn], | ||
isTransactionResponse | ||
); | ||
return resp; | ||
} catch (err) { | ||
throw new Error( | ||
`Error executing transaction: ${err} for txn ${JSON.stringify(txn)}` | ||
); | ||
} | ||
} | ||
@@ -190,4 +206,2 @@ | ||
} | ||
// TODO: add more interface methods | ||
} |
@@ -9,13 +9,6 @@ // Copyright (c) 2022, Mysten Labs, Inc. | ||
GetTxnDigestsResponse, | ||
TransactionResponse, | ||
SignedTransaction, | ||
} from '../types'; | ||
export interface SignedTransaction { | ||
txBytes: string; | ||
signature: string; | ||
pubKey: string; | ||
} | ||
// TODO: use correct types here | ||
export type TransactionResponse = string; | ||
/////////////////////////////// | ||
@@ -22,0 +15,0 @@ // Exported Abstracts |
@@ -11,4 +11,6 @@ // Copyright (c) 2022, Mysten Labs, Inc. | ||
GetObjectInfoResponse, | ||
SignedTransaction, | ||
TransactionResponse, | ||
} from '../types'; | ||
import { Provider, SignedTransaction, TransactionResponse } from './provider'; | ||
import { Provider } from './provider'; | ||
@@ -15,0 +17,0 @@ export class VoidProvider extends Provider { |
@@ -9,3 +9,3 @@ // Copyright (c) 2022, Mysten Labs, Inc. | ||
import { HttpHeaders, RpcParams, ValidResponse, ErrorResponse } from "./client"; | ||
import { isTransactionResponse } from "../index.guard"; | ||
import { isTransactionDigest } from "../index.guard"; | ||
@@ -25,3 +25,3 @@ export function isHttpHeaders(obj: any, _argumentName?: string): obj is HttpHeaders { | ||
typeof obj === "function") && | ||
isTransactionResponse(obj.method) as boolean && | ||
isTransactionDigest(obj.method) as boolean && | ||
Array.isArray(obj.args) | ||
@@ -37,3 +37,3 @@ ) | ||
obj.jsonrpc === "2.0" && | ||
isTransactionResponse(obj.id) as boolean | ||
isTransactionDigest(obj.id) as boolean | ||
) | ||
@@ -48,8 +48,8 @@ } | ||
obj.jsonrpc === "2.0" && | ||
isTransactionResponse(obj.id) as boolean && | ||
isTransactionDigest(obj.id) as boolean && | ||
(obj.error !== null && | ||
typeof obj.error === "object" || | ||
typeof obj.error === "function") && | ||
isTransactionResponse(obj.error.message) as boolean | ||
isTransactionDigest(obj.error.message) as boolean | ||
) | ||
} |
// Copyright (c) 2022, Mysten Labs, Inc. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
import { Provider, TransactionResponse } from '../providers/provider'; | ||
import { JsonRpcProvider } from '../providers/json-rpc-provider'; | ||
import { Provider } from '../providers/provider'; | ||
import { VoidProvider } from '../providers/void-provider'; | ||
import { Base64DataBuffer } from '../serialization/base64'; | ||
import { TransactionResponse } from '../types'; | ||
import { SignaturePubkeyPair, Signer } from './signer'; | ||
import { RpcTxnDataSerializer } from './txn-data-serializers/rpc-txn-data-serializer'; | ||
import { | ||
TransferTransaction, | ||
TransferCoinTransaction, | ||
TxnDataSerializer, | ||
@@ -40,3 +42,7 @@ } from './txn-data-serializers/txn-data-serializer'; | ||
this.provider = provider || new VoidProvider(); | ||
this.serializer = serializer || new RpcTxnDataSerializer(''); | ||
let endpoint = ''; | ||
if (this.provider instanceof JsonRpcProvider) { | ||
endpoint = this.provider.endpoint; | ||
} | ||
this.serializer = serializer || new RpcTxnDataSerializer(endpoint); | ||
} | ||
@@ -54,5 +60,5 @@ | ||
return await this.provider.executeTransaction({ | ||
txBytes: txBytes.toString(), | ||
tx_bytes: txBytes.toString(), | ||
signature: sig.signature.toString(), | ||
pubKey: sig.pubKey.toString(), | ||
pub_key: sig.pubKey.toString(), | ||
}); | ||
@@ -62,10 +68,10 @@ } | ||
/** | ||
* Serialize and Sign a `Transfer` transaction and submit to the Gateway for execution | ||
* Serialize and Sign a `TransferCoin` transaction and submit to the Gateway for execution | ||
*/ | ||
async transfer( | ||
transaction: TransferTransaction | ||
async transferCoin( | ||
transaction: TransferCoinTransaction | ||
): Promise<TransactionResponse> { | ||
const txBytes = await this.serializer.new_transfer(transaction); | ||
const txBytes = await this.serializer.newTransferCoin(transaction); | ||
return await this.signAndExecuteTransaction(txBytes); | ||
} | ||
} |
// Copyright (c) 2022, Mysten Labs, Inc. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
import { isTransactionBytes } from '../../index.guard'; | ||
import { JsonRpcClient } from '../../rpc/client'; | ||
import { Base64DataBuffer } from '../../serialization/base64'; | ||
import { TransferTransaction, TxnDataSerializer } from './txn-data-serializer'; | ||
import { | ||
TransferCoinTransaction, | ||
TxnDataSerializer, | ||
} from './txn-data-serializer'; | ||
@@ -15,4 +20,3 @@ /** | ||
export class RpcTxnDataSerializer implements TxnDataSerializer { | ||
//@ts-ignore | ||
private endpointURL: string; | ||
private client: JsonRpcClient; | ||
@@ -25,9 +29,16 @@ /** | ||
constructor(endpoint: string) { | ||
this.endpointURL = endpoint; | ||
this.client = new JsonRpcClient(endpoint); | ||
} | ||
async new_transfer( | ||
_transaction: TransferTransaction | ||
): Promise<Base64DataBuffer> { | ||
throw new Error('Method not implemented.'); | ||
async newTransferCoin(t: TransferCoinTransaction): Promise<Base64DataBuffer> { | ||
try { | ||
const resp = await this.client.requestWithType( | ||
'sui_transferCoin', | ||
[t.signer, t.objectId, t.gasPayment, t.gasBudget, t.recipient], | ||
isTransactionBytes | ||
); | ||
return new Base64DataBuffer(resp.tx_bytes); | ||
} catch (err) { | ||
throw new Error(`Error transferring coin: ${err}`); | ||
} | ||
} | ||
@@ -34,0 +45,0 @@ |
@@ -5,11 +5,12 @@ // Copyright (c) 2022, Mysten Labs, Inc. | ||
import { Base64DataBuffer } from '../../serialization/base64'; | ||
import { ObjectId, SuiAddress } from '../../types'; | ||
/////////////////////////////// | ||
// Exported Types | ||
export interface TransferTransaction { | ||
fromAddress: string; | ||
objectId: string; | ||
toAddress: string; | ||
gasObjectId: string; | ||
gas_budget: number; | ||
export interface TransferCoinTransaction { | ||
signer: SuiAddress; | ||
objectId: ObjectId; | ||
gasPayment: ObjectId; | ||
gasBudget: number; | ||
recipient: SuiAddress; | ||
} | ||
@@ -23,5 +24,5 @@ | ||
export interface TxnDataSerializer { | ||
new_transfer(transaction: TransferTransaction): Promise<Base64DataBuffer>; | ||
newTransferCoin(txn: TransferCoinTransaction): Promise<Base64DataBuffer>; | ||
// TODO: add more interface methods | ||
} |
@@ -124,2 +124,17 @@ // Copyright (c) 2022, Mysten Labs, Inc. | ||
export type TransactionBytes = { | ||
tx_bytes: string; | ||
}; | ||
export type TransactionResponse = { | ||
EffectResponse: TransactionEffectsResponse; | ||
// TODO: Add Publish, MergeCoin, SplitCoin Response | ||
}; | ||
export type SignedTransaction = { | ||
tx_bytes: string; | ||
signature: string; | ||
pub_key: string; | ||
}; | ||
/* ---------------------------- Helper functions ---------------------------- */ | ||
@@ -126,0 +141,0 @@ |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
910915
9621
64
7
+ Addedjs-sha3@^0.8.0
+ Addedjs-sha3@0.8.0(transitive)