npm package: @malloc-protocol/sdk
Description: ## Installation ``` yarn add @malloc-protocol/sdk ```
Latest version: 1.0.73

# Malloc Protocol SDK

## Installation
```
yarn add @malloc-protocol/sdk
```

# Usage
First, instantiate the Malloc SDK
```typescript
 const malloc = new MallocSdk(
      constants.PIDS.mainnet.MALLOC,
      provider,
      "mainnet-beta"
    );
```

We currently only support running "ephemeral" constructions. This means that
the construction does not stick around past one run. 

## Non Specific Construction
A code-facing construction (called a non-specific construction) has the following interface
```typescript
{
  actionDatas: {
		// The id of an action
		[actionId: string]: {
			action: {
				// A unique id specifying the action type, see the section on action libs
				actionTypeUID: string;
				// The program id for the action, see the section on action libs
				actionPID: string;
				// The input for the action
				inputs: any;
				// The next set of actions. Each map within the array corresponds
				// to a different output mint. Then the map key's correspond to what the 
				// next action is and the value corresponds to the fraction of the total
				nextActions: { [actionId: string]: number }[];
				opts?:  {
					// a number to multiply the estimate amounts out by to set to the minimum
					// This will usually be 0 to 1
					minimumOutToEstimateRatio?: number[];
				};
			}
		}
	};
	source: {
		// The initial fractional splits between the actions
    nextActions: { [actionId: string]: number };
		// The initial amounts and the associated amount (in the minimum denominated value for a token)
		// Here the mint is the base58 string of the public key for a mint
    mints: {
      [mint: string]: string;
    };
	}
};
```
## Action Libraries
Action libraries need to be passed into Malloc calls to tell the protocol
which actions to use and how to properly format them. In most cases, you
can find the action libraries in the package `@malloc-protocol/spl`. The spl exports an
object `splConstants` which has all the unique IDs per action type and the program
ID's for the given action. 

## Calling the construction
Calling a construction can be done in 3 easy steps.
### Building
Building correlates to converting the basic input into a format more fleshed out
with market data, minimum outs, and a built out graph.
```typescript
// The common action map here would be MallocSPLBuildActionMap
const built = await malloc.build(<nonSpecificConstruction>, <actionMap>, <opts>)
```
The options correspond to 
```typescript
{
	// A preferred token account for malloc to use of derived accounts
  preferredTokenAccounts?: {
    [mint: string]: PublicKey;
  };
	// The authority for the whole construction
  authority?: Signer | Wallet;
	// An alternate authority for the initial funds transfer
  amountInAuthority?: Signer;
}
```

#### Getting estimates
A built construction can then be used to get estimates. You can get the amount out
by calling  
```typescript
const { estimateIns, estimateOuts } = malloc.getEstimates(built, actionName)
```
where both estimateIns and estimateOuts have the interface
```typescript
{
	mint: PublicKey,
	amount: BN
}[]
```

### Compiling
Compiling correlates to taking Malloc structures into objects that Solana SDK
can understand
```typescript
const amountInAccounts: PublicKey[] = [MY_SOL_ACCOUNT, MY_RAY_ACCOUNT]
const compiled = await malloc.compileConstruction({
  construction: built,
	// This is often MallocSPLBuildActionMap
  actionMap: myBuildActionMap,
  amountInAccounts: amountInAccounts,
	// These options are the same as for build
  opts?: opts,
})
```
#### Running
Now to run the results...
```typescript
const txHashes = await malloc.runConstruction(compiled, opts)
```
Here the options correspond to 
```typescript
{
	commitment: {
    /** disable transaction verification step */
    skipPreflight?: boolean;
    /** desired commitment level */
    commitment?: Commitment;
    /** preflight commitment level */
    preflightCommitment?: Commitment;
  },
  /** A callback function that gets called at the start of running the flow with 0 for current
   * number done and total corresponding to the total number of transactions.
   * 
   * Then, after each transaction completes, this callback is called
  onTxDone: (currentNumberDone: number, total: number) => void
}
```
## Putting it all together, here is an example
> Note: this example uses buildCompileRun which combines the build, compile, and run stage
### Example
For information specifically onto what to pass into the inputs of the different
actions, see the @malloc-protocol/spl documentation
<!-- TODO: link to spl -->

```typescript
import { MallocSPLBuildActionMap, splConstants } from "@malloc-protocol/spl";

const malloc = new MallocSdk(
		constants.PIDS.mainnet.MALLOC,
		provider,
		"mainnet-beta"
	);
const txs = await malloc.buildCompileRun(
	{
        actionDatas: {
          swapToUsdc: {
            action: {
              actionTypeUID: splConstants.BUILD_ACTION_UIDS.RAYDIUM_SWAP,
              actionPID: splConstants.PIDS.MAINNET.CPI_ACTION,
              inputs: {
                liquidityPool: solUSDCPool,
              } as BuildRaydiumSwapArgs,
              nextActions: [{ lpDepositUsdcRay: 1 }],
            },
          },
          lpDepositUsdcRay: {
            action: {
              actionPID: splConstants.PIDS.MAINNET.CPI_ACTION,
              actionTypeUID: splConstants.BUILD_ACTION_UIDS.RAYDIUM_LP_DEPOSIT,
              inputs: {
                liquidityPool: usdcRayPool,
              } as BuildRaydiumLPDepositArgs,
              nextActions: [{ farmUsdcRay: 1 }],
            },
          },
          farmUsdcRay: {
            action: {
              actionPID: splConstants.PIDS.MAINNET.CPI_ACTION,
              actionTypeUID: splConstants.BUILD_ACTION_UIDS.RAYDIUM_LP_STAKE,
              inputs: {
                farmPoolKeys: usdcRayFarm,
              } as BuildRaydiumLPStake,
              nextActions: [],
            },
          },

          swapToRay: {
            action: {
              actionTypeUID: splConstants.BUILD_ACTION_UIDS.RAYDIUM_SWAP,
              actionPID: splConstants.PIDS.MAINNET.CPI_ACTION,
              inputs: {
                liquidityPool: solRayPool,
              } as BuildRaydiumSwapArgs,
              nextActions: [{ lpDepositSolRay: 1, lpDepositUsdcRay: 1 }],
            },
          },
          lpDepositSolRay: {
            action: {
              actionPID: splConstants.PIDS.MAINNET.CPI_ACTION,
              actionTypeUID: splConstants.BUILD_ACTION_UIDS.RAYDIUM_LP_DEPOSIT,
              inputs: {
                liquidityPool: solRayPool,
              } as BuildRaydiumLPDepositArgs,
              nextActions: [{ farmSolRay: 1 }],
            },
          },
          farmSolRay: {
            action: {
              actionPID: splConstants.PIDS.MAINNET.CPI_ACTION,
              actionTypeUID: splConstants.BUILD_ACTION_UIDS.RAYDIUM_LP_STAKE,
              inputs: {
                farmPoolKeys: solRayFarm,
              } as BuildRaydiumLPStake,
              nextActions: [],
            },
          },
        },
        source: {
          mints,
          nextActions: {
            swapToRay: 100,
            lpDepositSolRay: 100,
            swapToUsdc: 100,
          },
        },
      },
	[
		MY_SOL_ACCOUNT
	],
	MallocSPLBuildActionMap,
	{},
	{ commitment: { skipPreflight: true, commitment: "single" } }
);
```

## Error handling
Malloc Error's return in the type `_MallocError`:
```typescript
{
  mallocErrorMarker: "MALLOC ERROR MARKER";
  type: MallocErrorType;
  message: string;
  errorCode?: number;
  raw?: any;
}
```
Where type can be 
```typescript
export enum MallocErrorTypes {
	// Corresponds to a an error building the general construction
  MALLOC_BUILDER = "Malloc Builder",
	// Corresponds to an error building a specific action in the construction
  MALLOC_ACTION_BUILDER = "Malloc Action Builder",
	// Corresponds to an error in compiling a built action
  MALLOC_COMPILER = "Malloc Compiler",
	// Corresponds to an error which occurred during runtime.
  MALLOC_RUNNER = "Malloc Runner",
}
```

If a MALLOC_BUILDER, MALLOC_ACTION_BUILDER, or MALLOC_COMPILER error occurs,
there is no harm done -- nothing has been sent on chain and nothing has been executed.

`MALLOC_RUNNER` errors are more dangerous. To get which actions have run successfully,
which has failed, and which have not been ran at all, call `malloc.getErrorInfo(built, e)` where `e` is the thrown error and has the property type of MALLOC_RUNNER. Then
```typescript
{
    successful: string[];
    errored?: string;
    notRan: string[];
}
```
Is returned. If the error did not occur on an action, error will be null.