# MotorScript API #### A high-level React Native API for interacting with the Sonr ecosystem This design makes choices based on the following tenets: 1. **It should be easy to use.** A. Operations should be performed in the way they'd typically be performed in the target language/ ecosystem. B. Function names should be self-explanatory if possible. 2. **It should be as cheap as possible to perform operations.** A. Cheap means lowering gas and storage costs. B. This can happen through batch and deduplication of operations. ## Bucket API The Bucket data model, from [Sonr ADR-003](https://docs.sonr.io/posts/architecture/adr-003): > The model for a bucket, which will be stored in IPFS, is as follows. > > ``` > type Bucket struct { > Did string > Label string > IsActive bool > EncryptedJwks map[CID]map[PublicKey]EncryptedJWK > Content map[string]CID > } > > type CID string > type PublicKey string > type EncryptedJWK []byte``` ## Global Types ``` type ChannelAddress = Topic | Multiaddr type ContentMap = Map<Label, ContentBuilder> type EncryptedJwk = byte[] type Multiaddr = string type PublicKey = string type Address = string type byte = 0|1|2|...|254|255 //WIP type CID = string type DID = string type Label = string type Topic = string //WIP interface AuthDetails = { } ``` ## class BucketBuilder ### Class-specific types ``` //WIP: TODO: Should be immutable. Enforce w ts? interface BuiltBucket = { label: Label, isActive: boolean, encryptedJwks: (Map<PublicKey, EncryptedJwk>)[], content: Map<Label, byte[]>, } //WIP interface PushParams = Partial<{ }> ``` ### Fields `label: Label`: The label for this Bucket. `content: Map<Label, ContentBuilder>`: The list of ContentBuilders representing this Bucket's content. ### Functions #### `static new(label: Label) : BucketBuilder` Creates a new, empty BucketBuilder. **label (Label)**: The label for the bucket. **Returns**: a new, empty BucketBuilder. #### `static fromDid(bucketDid: DID) : Promise` Creates a new BucketBuilder initialized to the state of the corresponding Bucket on the chain. Throws an error if the is an error with retreiving the Bucket from blockchain or storage. Requires a blockchain or storage read. **bucketDid (DID)**: The DID used to retreive the Bucket. **Returns**: a Promise that returns a BucketBuilder on a success, and an err message on a failure. #### `static push(bucket: BuiltBucket, params: PushParams) : Promise` Pushes the bucket according to the given params. Requires a blockchain or storage write interaction. **bucket (BuiltBucket)**: The bucket to push. **params (PushParams)**: The parameters for pushing. **Returns**: A Promise that returns the BuiltBucket that was pushed on a success, and a error message on a failure. #### `constructor(label: Label, content: Map<Label, ContentBuilder>)` Creates a BucketBuilder with the parameterized fields. This constructor gives complete control of the BucketBuilder, though easier-to-use methods like NewBucket() and GetBucket() should be used instead when possible. **label (Label)**: The label for the bucket. **content (ContentMap)**: The label for the bucket. #### `addNewContent(label: Label) : ContentBuilder` Creates a new, empty ContentBuilder and adds it to the BucketBuilder with the specified label. **label (Label)**: The label for the Content. **Returns**: a new ContentBuilder that can be utilized. #### `addContent(label: Label, content: SonrObject) : ContentBuilder` Adds the specified ContentBuilder, containing content, to the BucketBuilder. **label (Label)**: The label for the Content. **content (SonrObject)**: The content to add. **Returns**: the ContentBuilder that was added to the BucketBuilder. #### `removeContent(label: Label) : ContentBuilder` Removes the ContentBuilder specified by the label. If the ContentBuilder does not exist, this function returns null. **label (Label)**: The label for the ContentBuilder to be removed. **Returns**: the ContentBuilder that was added to the BucketBuilder. #### `build() : BuiltBucket` Creates a BuiltBucket object, which can be used to push to storage and the blockchain. This function errs if WillBuild() returns false or the Bucket cannot be built for some other reason. **Returns**: an intermediary version of the Bucket in the form of a BuiltBucket object. #### `buildAndPush(params: PushParams) : Promise` A convenience function that performs the Build() and Push() operations at the same time. First the BucketBuilder is built, and then it is pushed using the params. The functions errs if willBuild() returns false or the Bucket cannot be built for some other reason. **Returns**: A Promise that returns the BuiltBucket that was pushed on a success, and a error message on a failure. #### `willBuild() : boolean` Determines whether the BucketBuilder will successfully Build(). A build will fail when (but not only when): - A ContentBuilder fails its WillBuild() - The label is empty **Returns**: Whether the BucketBuilder will successfully Build(). #### `setLabel(label: Label)` Sets the label of the BucketBuilder. An empty label will prevent WillBuild() from passing. **label (Label)**: The label for the bucket. ## class ContentBuilder ### Fields `bucketBuilder: BucketBuilder`: A reference to the parent BucketBuilder. `content: SonrObject`: The actual content held by this ContentBuilder. `sharedMembers: Address[]`: The list of Addresses this content should be shared with. ### Functions #### `constructor(bucket: BucketBuilder, content: SonrObject, sharedMembers: Address[])` Creates a new ContentBuilder initialized to the given state. The constructor should only be used if precise control is needed over the creation of a ContentBuilder. Otherwise, used BucketBuilder.addNewContent(). **bucket (BucketBuilder)**: The BucketBuilder that this ContentBuilder is attached to. **content (SonrObject)**: The content the ContentBuilder represents. **sharedMembers (Address[])**: A list of members who should have access to this content. #### `addSharedMember(member: Address) : ContentBuilder` Adds a member for the content to be shared with. **member (Address)**: The member to share the content with. **Returns**: This ContentBuilder. #### `removeSharedMember(member: Address) : ContentBuilder` Removes a member that the content is shared with. **member (Address)**: The member to share the content with. **Returns**: This ContentBuilder. #### `containsSharedMember(member: Address) : ContentBuilder` Determines whether a this content is shared with a particular member. **member (Address)**: The member to check if the content is shared with. **Returns**: This ContentBuilder. #### `verifySharedMember(member: Address[]) : ContentBuilder` If this member is not a shared member, add it to the list of shared members. **member (Address)**: This ContentBuilder. ## class Schema ### Class-specific Types ``` //WIP interface PushParams = Partial<{ }> ``` ### Fields `did (DID)`: The did of the Schema this schema corresponds to in storage. Optional. `label (Label)`: The label of the Schema. `fields (Map<Label, SonrKind>)`: The fields defined by this Schema. ### Functions #### `fromDid(did: DID) : Promise` Constructs a Schema from the Schema at the provided did. Errs if did is not found, or if the did does not point to a Schema. This functions requires readonly blockchain or storage interaction. **did (DID)**: The did of the Schema to construct. **Returns**: A Promise that returns a Schema on a success, and a error message on failure. #### `new(label: Label, fields: Map<Label, SonrKind>) : Schema` Constructs a Schema from the given parameters. Note that this Schema does not exist in storage until it is pushed. **label (Label)**: The label of the Schema. **fields (Map<Label, SonrKind>)**: The fields for the Schema. **Returns**: A Schema generated from the given parameters. #### `constructor(did: DID, label: Label, fields: Map<Label, SonrKind>)` Constructs a Sonr object with the given did, label, and fields. This constructor is for fine-tuned control of the SonrObject. For general situations, use new() or fromDid(). **did (DID)**: The field label to operate on. **value (SonrKind)**: The value to replace the current value at label. Note this value should be of the same type that is dictated by the fields field. #### `push(did?: DID, params: PushParams) : Promise` Pushes the Schema to storage, If the did parameter is passed and valid, it will attempt to overwrite the Schema at that did. Otherwise, it will attempt to overwrite the did at this Schema’s did. If neither succeed, this function fails. **did (DID)**: An optional way to specify the DID to push to. **params (PushParams)**: Additional parameters to determine the push behavior. **Returns**: A Promise that returns the Schema that is equivalent to the one just written, including the DID, on a success, or an error message on a failure. #### `newInstance() : SonrObject` Creates a mutable instance of this Schema, represented as a SonrObject, that can be passed into Buckets as data. #### `changeLabel(label: Label) : Schema` Creates and returns a Schema identical to this one, except that it’s label is replaced with the one given. This Schema is not changed. **label (Label)**: The new label field. **Returns**: A Schema identical to this one, except that it’s label is replaced with the one given. #### `changeFields(fields: Map<Label, SonrKind>) : Schema` Creates and returns a Schema identical to this one, except that its fields are replaced with the ones given. This Schema is not changed. **fields (Map<Label, SonrKind>)**: The new fields field. **Returns**: A Schema identical to this one, except that its fields are replaced with the ones given. ## class SonrObject ### Fields `schema (Schema)`: The schema this SonrObject uses for field validation. `fields Map<Label, SonrKind>`: The fields that contain the data for this SonrObject. ### Functions #### `constructor(schema: Schema, fields: Map<Label, SonrKind>)` Constructs a SonrObject from scratch. Unless fine-tuned construction is necessary, Schema.newInstance() should be used instead. **schema (Schema)**: The Schema that this SonrObject is constructed from. **fields (Map<Label, SonrKind>)**: The fields for this SonrObject. #### `set(label: Label, newVal: SonrKind) : boolean` Sets the field with the given label to the new value. This method verifies that newVal is of the same type contained in this SonrObject’s corresponding Schema field. **label (Label)**: The label for the fields to change. **newVal (SonrKind)**: The newVal to set the field to. **Returns**: Whether this SonrObject has been modified as a result of this call. #### `get(label: Label) : SonrKind` Returns the value at the given field. **label (Label)**: The label for the field to get the value from. **Returns**: The value at the given field. #### `getCast<T extends SonrKind>(label: Label) : T` Returns the value at the given field. Attempts to cast the return value to the generic type T, and errs on failure. **label (Label)**: The label for the field to get the value from. **Returns**: The value at the given field. ## class Channel ### Class-specific Types ``` //WIP type MessageFilter { } type ChannelOptions { address: ChannelAddress fromTime?: number, toTime?: number, auth?: AuthDetails, filter?: MessageFilter } type ChannelParams = Required<ChannelOptions> type PublishOptions { auth?: AuthDetails, metadata: any, sendAt: number } ``` ### Fields `address ChannelAddress`: The address (either Topic or Multiaddr) of this channel. `ephemeral boolean`: Whether this Channel is ephemeral or not. Readonly. `historicComms SchemaCommunication[]`: A list of historic communications with metadata. Readonly. `fromTime number`: From what time the channel should provide block historic communications. Any time before the channel was created is the same as setting the fromTime equal to the time the channel was created. Readonly. `toTime number`: To what time the channel should provide block historic communications. Readonly. `auth AuthDetails`: Details used to encrypt and decrypt content. `filter MessageFilter`: A filter used by the sender to prevent messages being sent. Readonly. ### Functions #### `static ListenCurrent(options: ChannelOptions) : Channel` Returns a Channel that listens to any live updates from the given `address`. **options (ChannelOptions)** Parameters to determine connection and behavior of the returned channel. **Returns** A `Channel` listening to live messages from the given `address`. <br> #### `static ListenHistory(to number, from? number, options: ChannelOptions) : Channel` Returns a Channel that receives block updates from a given time period from the given `address`. **to (number)** The time at which to stop receiving communications from this Channel. If this time is in the future, the channel will continue to receive live messages until this time has passed. **from (number)** The time to start receiving messages from the channel. **options (ChannelOptions)** Parameters to determine connection and behavior of the returned channel. **Returns** A `Channel` listening to historic messages from the given `address`. <br> #### `static Open(options: ChannelOptions) : Channel` Returns a Channel that can listen or write to the given `address`. Note that write permissions are required to write to any channel. **options (ChannelOptions)** Parameters to determine connection and behavior of the returned channel. **Returns** A `Channel` connected to messages from the given `address`. <br> #### `constructor(params ChannelParams)` Returns a Channel that listens to the given `address`. You should only use the constructor if you need fine-tuned control over the construction of the Channel. **options (ChannelParams)** Parameters to determine connection and behavior of the returned channel. **Returns** A `Channel` listening to messages from the given `address`. <br> #### `OnNewMessage(callback: {(e: MessageEvent) : void}, filter?: MessageFilter)` Returns a Channel that listens to any live updates from the given `address`. **callback (fn)** The function that is called when a new message is received. This function takes in a MessageEvent. **filter (MessageFilter)** A filter determining which messages are passed to the callback. <br> #### `Publish(object: SchemaType, options: PublishOptions)` Publishes the given `object` to this Channel considering the given `options`. **object (SchemaType)** The object to publish to the Channel. **options (PublishOptions)** Parameters to determine how the object is published to the Channel. <br> #### `isMultiaddr(): boolean` Returns whether the `address` field is a Multiaddr. Equivalent to `!isTopic()`. **Returns** Whether the `address` field is a Multiaddr. <br> #### `isTopic(): boolean` Returns whether the `address` field is a Topic. Equivalent to `!isMultiaddr()`. **Returns** Whether the `address` field is a Topic. <br>